keyword
stringclasses
7 values
repo_name
stringlengths
8
98
file_path
stringlengths
4
244
file_extension
stringclasses
29 values
file_size
int64
0
84.1M
line_count
int64
0
1.6M
content
stringlengths
1
84.1M
language
stringclasses
14 values
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/canvas/TransformGuiTemplate_pyqt5.py
.py
2,551
56
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'pyqtgraph/canvas/TransformGuiTemplate.ui' # # Created by: PyQt5 UI code generator 5.5.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(224, 117) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(Form.sizePolicy().hasHeightForWidth()) Form.setSizePolicy(sizePolicy) self.verticalLayout = QtWidgets.QVBoxLayout(Form) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setSpacing(1) self.verticalLayout.setObjectName("verticalLayout") self.translateLabel = QtWidgets.QLabel(Form) self.translateLabel.setObjectName("translateLabel") self.verticalLayout.addWidget(self.translateLabel) self.rotateLabel = QtWidgets.QLabel(Form) self.rotateLabel.setObjectName("rotateLabel") self.verticalLayout.addWidget(self.rotateLabel) self.scaleLabel = QtWidgets.QLabel(Form) self.scaleLabel.setObjectName("scaleLabel") self.verticalLayout.addWidget(self.scaleLabel) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.mirrorImageBtn = QtWidgets.QPushButton(Form) self.mirrorImageBtn.setToolTip("") self.mirrorImageBtn.setObjectName("mirrorImageBtn") self.horizontalLayout.addWidget(self.mirrorImageBtn) self.reflectImageBtn = QtWidgets.QPushButton(Form) self.reflectImageBtn.setObjectName("reflectImageBtn") self.horizontalLayout.addWidget(self.reflectImageBtn) self.verticalLayout.addLayout(self.horizontalLayout) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Form")) self.translateLabel.setText(_translate("Form", "Translate:")) self.rotateLabel.setText(_translate("Form", "Rotate:")) self.scaleLabel.setText(_translate("Form", "Scale:")) self.mirrorImageBtn.setText(_translate("Form", "Mirror")) self.reflectImageBtn.setText(_translate("Form", "Reflect"))
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/canvas/CanvasTemplate_pyside.py
.py
5,267
94
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'CanvasTemplate.ui' # # Created: Fri Mar 24 16:09:39 2017 # by: pyside-uic 0.2.15 running on PySide 1.2.2 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(821, 578) self.gridLayout_2 = QtGui.QGridLayout(Form) self.gridLayout_2.setContentsMargins(0, 0, 0, 0) self.gridLayout_2.setSpacing(0) self.gridLayout_2.setObjectName("gridLayout_2") self.splitter = QtGui.QSplitter(Form) self.splitter.setOrientation(QtCore.Qt.Horizontal) self.splitter.setObjectName("splitter") self.view = GraphicsView(self.splitter) self.view.setObjectName("view") self.vsplitter = QtGui.QSplitter(self.splitter) self.vsplitter.setOrientation(QtCore.Qt.Vertical) self.vsplitter.setObjectName("vsplitter") self.canvasCtrlWidget = QtGui.QWidget(self.vsplitter) self.canvasCtrlWidget.setObjectName("canvasCtrlWidget") self.gridLayout = QtGui.QGridLayout(self.canvasCtrlWidget) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setObjectName("gridLayout") self.autoRangeBtn = QtGui.QPushButton(self.canvasCtrlWidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth(self.autoRangeBtn.sizePolicy().hasHeightForWidth()) self.autoRangeBtn.setSizePolicy(sizePolicy) self.autoRangeBtn.setObjectName("autoRangeBtn") self.gridLayout.addWidget(self.autoRangeBtn, 0, 0, 1, 2) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setSpacing(0) self.horizontalLayout.setObjectName("horizontalLayout") self.redirectCheck = QtGui.QCheckBox(self.canvasCtrlWidget) self.redirectCheck.setObjectName("redirectCheck") self.horizontalLayout.addWidget(self.redirectCheck) self.redirectCombo = CanvasCombo(self.canvasCtrlWidget) self.redirectCombo.setObjectName("redirectCombo") self.horizontalLayout.addWidget(self.redirectCombo) self.gridLayout.addLayout(self.horizontalLayout, 1, 0, 1, 2) self.itemList = TreeWidget(self.canvasCtrlWidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(100) sizePolicy.setHeightForWidth(self.itemList.sizePolicy().hasHeightForWidth()) self.itemList.setSizePolicy(sizePolicy) self.itemList.setHeaderHidden(True) self.itemList.setObjectName("itemList") self.itemList.headerItem().setText(0, "1") self.gridLayout.addWidget(self.itemList, 2, 0, 1, 2) self.resetTransformsBtn = QtGui.QPushButton(self.canvasCtrlWidget) self.resetTransformsBtn.setObjectName("resetTransformsBtn") self.gridLayout.addWidget(self.resetTransformsBtn, 3, 0, 1, 2) self.mirrorSelectionBtn = QtGui.QPushButton(self.canvasCtrlWidget) self.mirrorSelectionBtn.setObjectName("mirrorSelectionBtn") self.gridLayout.addWidget(self.mirrorSelectionBtn, 4, 0, 1, 1) self.reflectSelectionBtn = QtGui.QPushButton(self.canvasCtrlWidget) self.reflectSelectionBtn.setObjectName("reflectSelectionBtn") self.gridLayout.addWidget(self.reflectSelectionBtn, 4, 1, 1, 1) self.canvasItemCtrl = QtGui.QWidget(self.vsplitter) self.canvasItemCtrl.setObjectName("canvasItemCtrl") self.ctrlLayout = QtGui.QGridLayout(self.canvasItemCtrl) self.ctrlLayout.setContentsMargins(0, 0, 0, 0) self.ctrlLayout.setSpacing(0) self.ctrlLayout.setContentsMargins(0, 0, 0, 0) self.ctrlLayout.setObjectName("ctrlLayout") self.gridLayout_2.addWidget(self.splitter, 0, 0, 1, 1) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8)) self.autoRangeBtn.setText(QtGui.QApplication.translate("Form", "Auto Range", None, QtGui.QApplication.UnicodeUTF8)) self.redirectCheck.setToolTip(QtGui.QApplication.translate("Form", "Check to display all local items in a remote canvas.", None, QtGui.QApplication.UnicodeUTF8)) self.redirectCheck.setText(QtGui.QApplication.translate("Form", "Redirect", None, QtGui.QApplication.UnicodeUTF8)) self.resetTransformsBtn.setText(QtGui.QApplication.translate("Form", "Reset Transforms", None, QtGui.QApplication.UnicodeUTF8)) self.mirrorSelectionBtn.setText(QtGui.QApplication.translate("Form", "Mirror Selection", None, QtGui.QApplication.UnicodeUTF8)) self.reflectSelectionBtn.setText(QtGui.QApplication.translate("Form", "MirrorXY", None, QtGui.QApplication.UnicodeUTF8)) from .CanvasManager import CanvasCombo from ..widgets.TreeWidget import TreeWidget from ..widgets.GraphicsView import GraphicsView
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/canvas/TransformGuiTemplate_pyside2.py
.py
2,721
56
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'TransformGuiTemplate.ui' # # Created: Sun Sep 18 19:18:41 2016 # by: pyside2-uic running on PySide2 2.0.0~alpha0 # # WARNING! All changes made in this file will be lost! from PySide2 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(224, 117) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(Form.sizePolicy().hasHeightForWidth()) Form.setSizePolicy(sizePolicy) self.verticalLayout = QtWidgets.QVBoxLayout(Form) self.verticalLayout.setSpacing(1) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.translateLabel = QtWidgets.QLabel(Form) self.translateLabel.setObjectName("translateLabel") self.verticalLayout.addWidget(self.translateLabel) self.rotateLabel = QtWidgets.QLabel(Form) self.rotateLabel.setObjectName("rotateLabel") self.verticalLayout.addWidget(self.rotateLabel) self.scaleLabel = QtWidgets.QLabel(Form) self.scaleLabel.setObjectName("scaleLabel") self.verticalLayout.addWidget(self.scaleLabel) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.mirrorImageBtn = QtWidgets.QPushButton(Form) self.mirrorImageBtn.setToolTip("") self.mirrorImageBtn.setObjectName("mirrorImageBtn") self.horizontalLayout.addWidget(self.mirrorImageBtn) self.reflectImageBtn = QtWidgets.QPushButton(Form) self.reflectImageBtn.setObjectName("reflectImageBtn") self.horizontalLayout.addWidget(self.reflectImageBtn) self.verticalLayout.addLayout(self.horizontalLayout) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(QtWidgets.QApplication.translate("Form", "Form", None, -1)) self.translateLabel.setText(QtWidgets.QApplication.translate("Form", "Translate:", None, -1)) self.rotateLabel.setText(QtWidgets.QApplication.translate("Form", "Rotate:", None, -1)) self.scaleLabel.setText(QtWidgets.QApplication.translate("Form", "Scale:", None, -1)) self.mirrorImageBtn.setText(QtWidgets.QApplication.translate("Form", "Mirror", None, -1)) self.reflectImageBtn.setText(QtWidgets.QApplication.translate("Form", "Reflect", None, -1))
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/canvas/Canvas.py
.py
16,264
475
# -*- coding: utf-8 -*- from ..Qt import QtGui, QtCore, QT_LIB from ..graphicsItems.ROI import ROI from ..graphicsItems.ViewBox import ViewBox from ..graphicsItems.GridItem import GridItem if QT_LIB == 'PySide': from .CanvasTemplate_pyside import * elif QT_LIB == 'PyQt4': from .CanvasTemplate_pyqt import * elif QT_LIB == 'PySide2': from .CanvasTemplate_pyside2 import * elif QT_LIB == 'PyQt5': from .CanvasTemplate_pyqt5 import * import numpy as np from .. import debug import weakref import gc from .CanvasManager import CanvasManager from .CanvasItem import CanvasItem, GroupCanvasItem class Canvas(QtGui.QWidget): sigSelectionChanged = QtCore.Signal(object, object) sigItemTransformChanged = QtCore.Signal(object, object) sigItemTransformChangeFinished = QtCore.Signal(object, object) def __init__(self, parent=None, allowTransforms=True, hideCtrl=False, name=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_Form() self.ui.setupUi(self) self.view = ViewBox() self.ui.view.setCentralItem(self.view) self.itemList = self.ui.itemList self.itemList.setSelectionMode(self.itemList.ExtendedSelection) self.allowTransforms = allowTransforms self.multiSelectBox = SelectBox() self.view.addItem(self.multiSelectBox) self.multiSelectBox.hide() self.multiSelectBox.setZValue(1e6) self.ui.mirrorSelectionBtn.hide() self.ui.reflectSelectionBtn.hide() self.ui.resetTransformsBtn.hide() self.redirect = None ## which canvas to redirect items to self.items = [] self.view.setAspectLocked(True) grid = GridItem() self.grid = CanvasItem(grid, name='Grid', movable=False) self.addItem(self.grid) self.hideBtn = QtGui.QPushButton('>', self) self.hideBtn.setFixedWidth(20) self.hideBtn.setFixedHeight(20) self.ctrlSize = 200 self.sizeApplied = False self.hideBtn.clicked.connect(self.hideBtnClicked) self.ui.splitter.splitterMoved.connect(self.splitterMoved) self.ui.itemList.itemChanged.connect(self.treeItemChanged) self.ui.itemList.sigItemMoved.connect(self.treeItemMoved) self.ui.itemList.itemSelectionChanged.connect(self.treeItemSelected) self.ui.autoRangeBtn.clicked.connect(self.autoRange) self.ui.redirectCheck.toggled.connect(self.updateRedirect) self.ui.redirectCombo.currentIndexChanged.connect(self.updateRedirect) self.multiSelectBox.sigRegionChanged.connect(self.multiSelectBoxChanged) self.multiSelectBox.sigRegionChangeFinished.connect(self.multiSelectBoxChangeFinished) self.ui.mirrorSelectionBtn.clicked.connect(self.mirrorSelectionClicked) self.ui.reflectSelectionBtn.clicked.connect(self.reflectSelectionClicked) self.ui.resetTransformsBtn.clicked.connect(self.resetTransformsClicked) self.resizeEvent() if hideCtrl: self.hideBtnClicked() if name is not None: self.registeredName = CanvasManager.instance().registerCanvas(self, name) self.ui.redirectCombo.setHostName(self.registeredName) self.menu = QtGui.QMenu() remAct = QtGui.QAction("Remove item", self.menu) remAct.triggered.connect(self.removeClicked) self.menu.addAction(remAct) self.menu.remAct = remAct self.ui.itemList.contextMenuEvent = self.itemListContextMenuEvent def splitterMoved(self): self.resizeEvent() def hideBtnClicked(self): ctrlSize = self.ui.splitter.sizes()[1] if ctrlSize == 0: cs = self.ctrlSize w = self.ui.splitter.size().width() if cs > w: cs = w - 20 self.ui.splitter.setSizes([w-cs, cs]) self.hideBtn.setText('>') else: self.ctrlSize = ctrlSize self.ui.splitter.setSizes([100, 0]) self.hideBtn.setText('<') self.resizeEvent() def autoRange(self): self.view.autoRange() def resizeEvent(self, ev=None): if ev is not None: QtGui.QWidget.resizeEvent(self, ev) self.hideBtn.move(self.ui.view.size().width() - self.hideBtn.width(), 0) if not self.sizeApplied: self.sizeApplied = True s = min(self.width(), max(100, min(200, self.width()*0.25))) s2 = self.width()-s self.ui.splitter.setSizes([s2, s]) def updateRedirect(self, *args): ### Decide whether/where to redirect items and make it so cname = str(self.ui.redirectCombo.currentText()) man = CanvasManager.instance() if self.ui.redirectCheck.isChecked() and cname != '': redirect = man.getCanvas(cname) else: redirect = None if self.redirect is redirect: return self.redirect = redirect if redirect is None: self.reclaimItems() else: self.redirectItems(redirect) def redirectItems(self, canvas): for i in self.items: if i is self.grid: continue li = i.listItem parent = li.parent() if parent is None: tree = li.treeWidget() if tree is None: print("Skipping item", i, i.name) continue tree.removeTopLevelItem(li) else: parent.removeChild(li) canvas.addItem(i) def reclaimItems(self): items = self.items self.items = [self.grid] items.remove(self.grid) for i in items: i.canvas.removeItem(i) self.addItem(i) def treeItemChanged(self, item, col): try: citem = item.canvasItem() except AttributeError: return if item.checkState(0) == QtCore.Qt.Checked: for i in range(item.childCount()): item.child(i).setCheckState(0, QtCore.Qt.Checked) citem.show() else: for i in range(item.childCount()): item.child(i).setCheckState(0, QtCore.Qt.Unchecked) citem.hide() def treeItemSelected(self): sel = self.selectedItems() if len(sel) == 0: return multi = len(sel) > 1 for i in self.items: ## updated the selected state of every item i.selectionChanged(i in sel, multi) if len(sel)==1: self.multiSelectBox.hide() self.ui.mirrorSelectionBtn.hide() self.ui.reflectSelectionBtn.hide() self.ui.resetTransformsBtn.hide() elif len(sel) > 1: self.showMultiSelectBox() self.sigSelectionChanged.emit(self, sel) def selectedItems(self): """ Return list of all selected canvasItems """ return [item.canvasItem() for item in self.itemList.selectedItems() if item.canvasItem() is not None] def selectItem(self, item): li = item.listItem self.itemList.setCurrentItem(li) def showMultiSelectBox(self): ## Get list of selected canvas items items = self.selectedItems() rect = self.view.itemBoundingRect(items[0].graphicsItem()) for i in items: if not i.isMovable(): ## all items in selection must be movable return br = self.view.itemBoundingRect(i.graphicsItem()) rect = rect|br self.multiSelectBox.blockSignals(True) self.multiSelectBox.setPos([rect.x(), rect.y()]) self.multiSelectBox.setSize(rect.size()) self.multiSelectBox.setAngle(0) self.multiSelectBox.blockSignals(False) self.multiSelectBox.show() self.ui.mirrorSelectionBtn.show() self.ui.reflectSelectionBtn.show() self.ui.resetTransformsBtn.show() def mirrorSelectionClicked(self): for ci in self.selectedItems(): ci.mirrorY() self.showMultiSelectBox() def reflectSelectionClicked(self): for ci in self.selectedItems(): ci.mirrorXY() self.showMultiSelectBox() def resetTransformsClicked(self): for i in self.selectedItems(): i.resetTransformClicked() self.showMultiSelectBox() def multiSelectBoxChanged(self): self.multiSelectBoxMoved() def multiSelectBoxChangeFinished(self): for ci in self.selectedItems(): ci.applyTemporaryTransform() ci.sigTransformChangeFinished.emit(ci) def multiSelectBoxMoved(self): transform = self.multiSelectBox.getGlobalTransform() for ci in self.selectedItems(): ci.setTemporaryTransform(transform) ci.sigTransformChanged.emit(ci) def addGraphicsItem(self, item, **opts): """Add a new GraphicsItem to the scene at pos. Common options are name, pos, scale, and z """ citem = CanvasItem(item, **opts) item._canvasItem = citem self.addItem(citem) return citem def addGroup(self, name, **kargs): group = GroupCanvasItem(name=name) self.addItem(group, **kargs) return group def addItem(self, citem): """ Add an item to the canvas. """ ## Check for redirections if self.redirect is not None: name = self.redirect.addItem(citem) self.items.append(citem) return name if not self.allowTransforms: citem.setMovable(False) citem.sigTransformChanged.connect(self.itemTransformChanged) citem.sigTransformChangeFinished.connect(self.itemTransformChangeFinished) citem.sigVisibilityChanged.connect(self.itemVisibilityChanged) ## Determine name to use in the item list name = citem.opts['name'] if name is None: name = 'item' newname = name ## If name already exists, append a number to the end ## NAH. Let items have the same name if they really want. #c=0 #while newname in self.items: #c += 1 #newname = name + '_%03d' %c #name = newname ## find parent and add item to tree insertLocation = 0 #print "Inserting node:", name ## determine parent list item where this item should be inserted parent = citem.parentItem() if parent in (None, self.view.childGroup): parent = self.itemList.invisibleRootItem() else: parent = parent.listItem ## set Z value above all other siblings if none was specified siblings = [parent.child(i).canvasItem() for i in range(parent.childCount())] z = citem.zValue() if z is None: zvals = [i.zValue() for i in siblings] if parent is self.itemList.invisibleRootItem(): if len(zvals) == 0: z = 0 else: z = max(zvals)+10 else: if len(zvals) == 0: z = parent.canvasItem().zValue() else: z = max(zvals)+1 citem.setZValue(z) ## determine location to insert item relative to its siblings for i in range(parent.childCount()): ch = parent.child(i) zval = ch.canvasItem().graphicsItem().zValue() ## should we use CanvasItem.zValue here? if zval < z: insertLocation = i break else: insertLocation = i+1 node = QtGui.QTreeWidgetItem([name]) flags = node.flags() | QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsDragEnabled if not isinstance(citem, GroupCanvasItem): flags = flags & ~QtCore.Qt.ItemIsDropEnabled node.setFlags(flags) if citem.opts['visible']: node.setCheckState(0, QtCore.Qt.Checked) else: node.setCheckState(0, QtCore.Qt.Unchecked) node.name = name parent.insertChild(insertLocation, node) citem.name = name citem.listItem = node node.canvasItem = weakref.ref(citem) self.items.append(citem) ctrl = citem.ctrlWidget() ctrl.hide() self.ui.ctrlLayout.addWidget(ctrl) ## inform the canvasItem that its parent canvas has changed citem.setCanvas(self) ## Autoscale to fit the first item added (not including the grid). if len(self.items) == 2: self.autoRange() return citem def treeItemMoved(self, item, parent, index): ##Item moved in tree; update Z values if parent is self.itemList.invisibleRootItem(): item.canvasItem().setParentItem(self.view.childGroup) else: item.canvasItem().setParentItem(parent.canvasItem()) siblings = [parent.child(i).canvasItem() for i in range(parent.childCount())] zvals = [i.zValue() for i in siblings] zvals.sort(reverse=True) for i in range(len(siblings)): item = siblings[i] item.setZValue(zvals[i]) def itemVisibilityChanged(self, item): listItem = item.listItem checked = listItem.checkState(0) == QtCore.Qt.Checked vis = item.isVisible() if vis != checked: if vis: listItem.setCheckState(0, QtCore.Qt.Checked) else: listItem.setCheckState(0, QtCore.Qt.Unchecked) def removeItem(self, item): if isinstance(item, QtGui.QTreeWidgetItem): item = item.canvasItem() if isinstance(item, CanvasItem): item.setCanvas(None) listItem = item.listItem listItem.canvasItem = None item.listItem = None self.itemList.removeTopLevelItem(listItem) self.items.remove(item) ctrl = item.ctrlWidget() ctrl.hide() self.ui.ctrlLayout.removeWidget(ctrl) ctrl.setParent(None) else: if hasattr(item, '_canvasItem'): self.removeItem(item._canvasItem) else: self.view.removeItem(item) gc.collect() def clear(self): while len(self.items) > 0: self.removeItem(self.items[0]) def addToScene(self, item): self.view.addItem(item) def removeFromScene(self, item): self.view.removeItem(item) def listItems(self): """Return a dictionary of name:item pairs""" return self.items def getListItem(self, name): return self.items[name] def itemTransformChanged(self, item): self.sigItemTransformChanged.emit(self, item) def itemTransformChangeFinished(self, item): self.sigItemTransformChangeFinished.emit(self, item) def itemListContextMenuEvent(self, ev): self.menuItem = self.itemList.itemAt(ev.pos()) self.menu.popup(ev.globalPos()) def removeClicked(self): for item in self.selectedItems(): self.removeItem(item) self.menuItem = None import gc gc.collect() class SelectBox(ROI): def __init__(self, scalable=False): #QtGui.QGraphicsRectItem.__init__(self, 0, 0, size[0], size[1]) ROI.__init__(self, [0,0], [1,1]) center = [0.5, 0.5] if scalable: self.addScaleHandle([1, 1], center, lockAspect=True) self.addScaleHandle([0, 0], center, lockAspect=True) self.addRotateHandle([0, 1], center) self.addRotateHandle([1, 0], center)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/canvas/CanvasTemplate_pyqt5.py
.py
4,916
93
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'CanvasTemplate.ui' # # Created by: PyQt5 UI code generator 5.7.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(821, 578) self.gridLayout_2 = QtWidgets.QGridLayout(Form) self.gridLayout_2.setContentsMargins(0, 0, 0, 0) self.gridLayout_2.setSpacing(0) self.gridLayout_2.setObjectName("gridLayout_2") self.splitter = QtWidgets.QSplitter(Form) self.splitter.setOrientation(QtCore.Qt.Horizontal) self.splitter.setObjectName("splitter") self.view = GraphicsView(self.splitter) self.view.setObjectName("view") self.vsplitter = QtWidgets.QSplitter(self.splitter) self.vsplitter.setOrientation(QtCore.Qt.Vertical) self.vsplitter.setObjectName("vsplitter") self.canvasCtrlWidget = QtWidgets.QWidget(self.vsplitter) self.canvasCtrlWidget.setObjectName("canvasCtrlWidget") self.gridLayout = QtWidgets.QGridLayout(self.canvasCtrlWidget) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setObjectName("gridLayout") self.autoRangeBtn = QtWidgets.QPushButton(self.canvasCtrlWidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth(self.autoRangeBtn.sizePolicy().hasHeightForWidth()) self.autoRangeBtn.setSizePolicy(sizePolicy) self.autoRangeBtn.setObjectName("autoRangeBtn") self.gridLayout.addWidget(self.autoRangeBtn, 0, 0, 1, 2) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setSpacing(0) self.horizontalLayout.setObjectName("horizontalLayout") self.redirectCheck = QtWidgets.QCheckBox(self.canvasCtrlWidget) self.redirectCheck.setObjectName("redirectCheck") self.horizontalLayout.addWidget(self.redirectCheck) self.redirectCombo = CanvasCombo(self.canvasCtrlWidget) self.redirectCombo.setObjectName("redirectCombo") self.horizontalLayout.addWidget(self.redirectCombo) self.gridLayout.addLayout(self.horizontalLayout, 1, 0, 1, 2) self.itemList = TreeWidget(self.canvasCtrlWidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(100) sizePolicy.setHeightForWidth(self.itemList.sizePolicy().hasHeightForWidth()) self.itemList.setSizePolicy(sizePolicy) self.itemList.setHeaderHidden(True) self.itemList.setObjectName("itemList") self.itemList.headerItem().setText(0, "1") self.gridLayout.addWidget(self.itemList, 2, 0, 1, 2) self.resetTransformsBtn = QtWidgets.QPushButton(self.canvasCtrlWidget) self.resetTransformsBtn.setObjectName("resetTransformsBtn") self.gridLayout.addWidget(self.resetTransformsBtn, 3, 0, 1, 2) self.mirrorSelectionBtn = QtWidgets.QPushButton(self.canvasCtrlWidget) self.mirrorSelectionBtn.setObjectName("mirrorSelectionBtn") self.gridLayout.addWidget(self.mirrorSelectionBtn, 4, 0, 1, 1) self.reflectSelectionBtn = QtWidgets.QPushButton(self.canvasCtrlWidget) self.reflectSelectionBtn.setObjectName("reflectSelectionBtn") self.gridLayout.addWidget(self.reflectSelectionBtn, 4, 1, 1, 1) self.canvasItemCtrl = QtWidgets.QWidget(self.vsplitter) self.canvasItemCtrl.setObjectName("canvasItemCtrl") self.ctrlLayout = QtWidgets.QGridLayout(self.canvasItemCtrl) self.ctrlLayout.setContentsMargins(0, 0, 0, 0) self.ctrlLayout.setSpacing(0) self.ctrlLayout.setObjectName("ctrlLayout") self.gridLayout_2.addWidget(self.splitter, 0, 0, 1, 1) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Form")) self.autoRangeBtn.setText(_translate("Form", "Auto Range")) self.redirectCheck.setToolTip(_translate("Form", "Check to display all local items in a remote canvas.")) self.redirectCheck.setText(_translate("Form", "Redirect")) self.resetTransformsBtn.setText(_translate("Form", "Reset Transforms")) self.mirrorSelectionBtn.setText(_translate("Form", "Mirror Selection")) self.reflectSelectionBtn.setText(_translate("Form", "MirrorXY")) from ..widgets.GraphicsView import GraphicsView from ..widgets.TreeWidget import TreeWidget from .CanvasManager import CanvasCombo
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/canvas/CanvasTemplate_pyside2.py
.py
4,797
88
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'CanvasTemplate.ui' # # Created: Sun Sep 18 19:18:22 2016 # by: pyside2-uic running on PySide2 2.0.0~alpha0 # # WARNING! All changes made in this file will be lost! from PySide2 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(490, 414) self.gridLayout = QtWidgets.QGridLayout(Form) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setSpacing(0) self.gridLayout.setObjectName("gridLayout") self.splitter = QtWidgets.QSplitter(Form) self.splitter.setOrientation(QtCore.Qt.Horizontal) self.splitter.setObjectName("splitter") self.view = GraphicsView(self.splitter) self.view.setObjectName("view") self.layoutWidget = QtWidgets.QWidget(self.splitter) self.layoutWidget.setObjectName("layoutWidget") self.gridLayout_2 = QtWidgets.QGridLayout(self.layoutWidget) self.gridLayout_2.setContentsMargins(0, 0, 0, 0) self.gridLayout_2.setObjectName("gridLayout_2") self.autoRangeBtn = QtWidgets.QPushButton(self.layoutWidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth(self.autoRangeBtn.sizePolicy().hasHeightForWidth()) self.autoRangeBtn.setSizePolicy(sizePolicy) self.autoRangeBtn.setObjectName("autoRangeBtn") self.gridLayout_2.addWidget(self.autoRangeBtn, 2, 0, 1, 2) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setSpacing(0) self.horizontalLayout.setObjectName("horizontalLayout") self.redirectCheck = QtWidgets.QCheckBox(self.layoutWidget) self.redirectCheck.setObjectName("redirectCheck") self.horizontalLayout.addWidget(self.redirectCheck) self.redirectCombo = CanvasCombo(self.layoutWidget) self.redirectCombo.setObjectName("redirectCombo") self.horizontalLayout.addWidget(self.redirectCombo) self.gridLayout_2.addLayout(self.horizontalLayout, 5, 0, 1, 2) self.itemList = TreeWidget(self.layoutWidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(100) sizePolicy.setHeightForWidth(self.itemList.sizePolicy().hasHeightForWidth()) self.itemList.setSizePolicy(sizePolicy) self.itemList.setHeaderHidden(True) self.itemList.setObjectName("itemList") self.itemList.headerItem().setText(0, "1") self.gridLayout_2.addWidget(self.itemList, 6, 0, 1, 2) self.ctrlLayout = QtWidgets.QGridLayout() self.ctrlLayout.setSpacing(0) self.ctrlLayout.setObjectName("ctrlLayout") self.gridLayout_2.addLayout(self.ctrlLayout, 10, 0, 1, 2) self.resetTransformsBtn = QtWidgets.QPushButton(self.layoutWidget) self.resetTransformsBtn.setObjectName("resetTransformsBtn") self.gridLayout_2.addWidget(self.resetTransformsBtn, 7, 0, 1, 1) self.mirrorSelectionBtn = QtWidgets.QPushButton(self.layoutWidget) self.mirrorSelectionBtn.setObjectName("mirrorSelectionBtn") self.gridLayout_2.addWidget(self.mirrorSelectionBtn, 3, 0, 1, 1) self.reflectSelectionBtn = QtWidgets.QPushButton(self.layoutWidget) self.reflectSelectionBtn.setObjectName("reflectSelectionBtn") self.gridLayout_2.addWidget(self.reflectSelectionBtn, 3, 1, 1, 1) self.gridLayout.addWidget(self.splitter, 0, 0, 1, 1) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(QtWidgets.QApplication.translate("Form", "Form", None, -1)) self.autoRangeBtn.setText(QtWidgets.QApplication.translate("Form", "Auto Range", None, -1)) self.redirectCheck.setToolTip(QtWidgets.QApplication.translate("Form", "Check to display all local items in a remote canvas.", None, -1)) self.redirectCheck.setText(QtWidgets.QApplication.translate("Form", "Redirect", None, -1)) self.resetTransformsBtn.setText(QtWidgets.QApplication.translate("Form", "Reset Transforms", None, -1)) self.mirrorSelectionBtn.setText(QtWidgets.QApplication.translate("Form", "Mirror Selection", None, -1)) self.reflectSelectionBtn.setText(QtWidgets.QApplication.translate("Form", "MirrorXY", None, -1)) from ..widgets.TreeWidget import TreeWidget from CanvasManager import CanvasCombo from ..widgets.GraphicsView import GraphicsView
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/canvas/CanvasManager.py
.py
2,206
77
# -*- coding: utf-8 -*- from ..Qt import QtCore, QtGui if not hasattr(QtCore, 'Signal'): QtCore.Signal = QtCore.pyqtSignal import weakref class CanvasManager(QtCore.QObject): SINGLETON = None sigCanvasListChanged = QtCore.Signal() def __init__(self): if CanvasManager.SINGLETON is not None: raise Exception("Can only create one canvas manager.") CanvasManager.SINGLETON = self QtCore.QObject.__init__(self) self.canvases = weakref.WeakValueDictionary() @classmethod def instance(cls): return CanvasManager.SINGLETON def registerCanvas(self, canvas, name): n2 = name i = 0 while n2 in self.canvases: n2 = "%s_%03d" % (name, i) i += 1 self.canvases[n2] = canvas self.sigCanvasListChanged.emit() return n2 def unregisterCanvas(self, name): c = self.canvases[name] del self.canvases[name] self.sigCanvasListChanged.emit() def listCanvases(self): return list(self.canvases.keys()) def getCanvas(self, name): return self.canvases[name] manager = CanvasManager() class CanvasCombo(QtGui.QComboBox): def __init__(self, parent=None): QtGui.QComboBox.__init__(self, parent) man = CanvasManager.instance() man.sigCanvasListChanged.connect(self.updateCanvasList) self.hostName = None self.updateCanvasList() def updateCanvasList(self): canvases = CanvasManager.instance().listCanvases() canvases.insert(0, "") if self.hostName in canvases: canvases.remove(self.hostName) sel = self.currentText() if sel in canvases: self.blockSignals(True) ## change does not affect current selection; block signals during update self.clear() for i in canvases: self.addItem(i) if i == sel: self.setCurrentIndex(self.count()) self.blockSignals(False) def setHostName(self, name): self.hostName = name self.updateCanvasList()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/canvas/CanvasItem.py
.py
18,263
489
# -*- coding: utf-8 -*- import numpy as np from ..Qt import QtGui, QtCore, QtSvg, QT_LIB from ..graphicsItems.ROI import ROI from .. import SRTTransform, ItemGroup if QT_LIB == 'PySide': from . import TransformGuiTemplate_pyside as TransformGuiTemplate elif QT_LIB == 'PyQt4': from . import TransformGuiTemplate_pyqt as TransformGuiTemplate elif QT_LIB == 'PySide2': from . import TransformGuiTemplate_pyside2 as TransformGuiTemplate elif QT_LIB == 'PyQt5': from . import TransformGuiTemplate_pyqt5 as TransformGuiTemplate from .. import debug class SelectBox(ROI): def __init__(self, scalable=False, rotatable=True): #QtGui.QGraphicsRectItem.__init__(self, 0, 0, size[0], size[1]) ROI.__init__(self, [0,0], [1,1], invertible=True) center = [0.5, 0.5] if scalable: self.addScaleHandle([1, 1], center, lockAspect=True) self.addScaleHandle([0, 0], center, lockAspect=True) if rotatable: self.addRotateHandle([0, 1], center) self.addRotateHandle([1, 0], center) class CanvasItem(QtCore.QObject): sigResetUserTransform = QtCore.Signal(object) sigTransformChangeFinished = QtCore.Signal(object) sigTransformChanged = QtCore.Signal(object) """CanvasItem takes care of managing an item's state--alpha, visibility, z-value, transformations, etc. and provides a control widget""" sigVisibilityChanged = QtCore.Signal(object) transformCopyBuffer = None def __init__(self, item, **opts): defOpts = {'name': None, 'z': None, 'movable': True, 'scalable': False, 'rotatable': True, 'visible': True, 'parent':None} #'pos': [0,0], 'scale': [1,1], 'angle':0, defOpts.update(opts) self.opts = defOpts self.selectedAlone = False ## whether this item is the only one selected QtCore.QObject.__init__(self) self.canvas = None self._graphicsItem = item parent = self.opts['parent'] if parent is not None: self._graphicsItem.setParentItem(parent.graphicsItem()) self._parentItem = parent else: self._parentItem = None z = self.opts['z'] if z is not None: item.setZValue(z) self.ctrl = QtGui.QWidget() self.layout = QtGui.QGridLayout() self.layout.setSpacing(0) self.layout.setContentsMargins(0,0,0,0) self.ctrl.setLayout(self.layout) self.alphaLabel = QtGui.QLabel("Alpha") self.alphaSlider = QtGui.QSlider() self.alphaSlider.setMaximum(1023) self.alphaSlider.setOrientation(QtCore.Qt.Horizontal) self.alphaSlider.setValue(1023) self.layout.addWidget(self.alphaLabel, 0, 0) self.layout.addWidget(self.alphaSlider, 0, 1) self.resetTransformBtn = QtGui.QPushButton('Reset Transform') self.copyBtn = QtGui.QPushButton('Copy') self.pasteBtn = QtGui.QPushButton('Paste') self.transformWidget = QtGui.QWidget() self.transformGui = TransformGuiTemplate.Ui_Form() self.transformGui.setupUi(self.transformWidget) self.layout.addWidget(self.transformWidget, 3, 0, 1, 2) self.transformGui.mirrorImageBtn.clicked.connect(self.mirrorY) self.transformGui.reflectImageBtn.clicked.connect(self.mirrorXY) self.layout.addWidget(self.resetTransformBtn, 1, 0, 1, 2) self.layout.addWidget(self.copyBtn, 2, 0, 1, 1) self.layout.addWidget(self.pasteBtn, 2, 1, 1, 1) self.alphaSlider.valueChanged.connect(self.alphaChanged) self.alphaSlider.sliderPressed.connect(self.alphaPressed) self.alphaSlider.sliderReleased.connect(self.alphaReleased) self.resetTransformBtn.clicked.connect(self.resetTransformClicked) self.copyBtn.clicked.connect(self.copyClicked) self.pasteBtn.clicked.connect(self.pasteClicked) self.setMovable(self.opts['movable']) ## update gui to reflect this option if 'transform' in self.opts: self.baseTransform = self.opts['transform'] else: self.baseTransform = SRTTransform() if 'pos' in self.opts and self.opts['pos'] is not None: self.baseTransform.translate(self.opts['pos']) if 'angle' in self.opts and self.opts['angle'] is not None: self.baseTransform.rotate(self.opts['angle']) if 'scale' in self.opts and self.opts['scale'] is not None: self.baseTransform.scale(self.opts['scale']) ## create selection box (only visible when selected) tr = self.baseTransform.saveState() if 'scalable' not in opts and tr['scale'] == (1,1): self.opts['scalable'] = True ## every CanvasItem implements its own individual selection box ## so that subclasses are free to make their own. self.selectBox = SelectBox(scalable=self.opts['scalable'], rotatable=self.opts['rotatable']) self.selectBox.hide() self.selectBox.setZValue(1e6) self.selectBox.sigRegionChanged.connect(self.selectBoxChanged) ## calls selectBoxMoved self.selectBox.sigRegionChangeFinished.connect(self.selectBoxChangeFinished) ## set up the transformations that will be applied to the item ## (It is not safe to use item.setTransform, since the item might count on that not changing) self.itemRotation = QtGui.QGraphicsRotation() self.itemScale = QtGui.QGraphicsScale() self._graphicsItem.setTransformations([self.itemRotation, self.itemScale]) self.tempTransform = SRTTransform() ## holds the additional transform that happens during a move - gets added to the userTransform when move is done. self.userTransform = SRTTransform() ## stores the total transform of the object self.resetUserTransform() def setMovable(self, m): self.opts['movable'] = m if m: self.resetTransformBtn.show() self.copyBtn.show() self.pasteBtn.show() else: self.resetTransformBtn.hide() self.copyBtn.hide() self.pasteBtn.hide() def setCanvas(self, canvas): ## Called by canvas whenever the item is added. ## It is our responsibility to add all graphicsItems to the canvas's scene ## The canvas will automatically add our graphicsitem, ## so we just need to take care of the selectbox. if canvas is self.canvas: return if canvas is None: self.canvas.removeFromScene(self._graphicsItem) self.canvas.removeFromScene(self.selectBox) else: canvas.addToScene(self._graphicsItem) canvas.addToScene(self.selectBox) self.canvas = canvas def graphicsItem(self): """Return the graphicsItem for this canvasItem.""" return self._graphicsItem def parentItem(self): return self._parentItem def setParentItem(self, parent): self._parentItem = parent if parent is not None: if isinstance(parent, CanvasItem): parent = parent.graphicsItem() self.graphicsItem().setParentItem(parent) #def name(self): #return self.opts['name'] def copyClicked(self): CanvasItem.transformCopyBuffer = self.saveTransform() def pasteClicked(self): t = CanvasItem.transformCopyBuffer if t is None: return else: self.restoreTransform(t) def mirrorY(self): if not self.isMovable(): return #flip = self.transformGui.mirrorImageCheck.isChecked() #tr = self.userTransform.saveState() inv = SRTTransform() inv.scale(-1, 1) self.userTransform = self.userTransform * inv self.updateTransform() self.selectBoxFromUser() self.sigTransformChangeFinished.emit(self) #if flip: #if tr['scale'][0] < 0 xor tr['scale'][1] < 0: #return #else: #self.userTransform.setScale([-tr['scale'][0], tr['scale'][1]]) #self.userTransform.setTranslate([-tr['pos'][0], tr['pos'][1]]) #self.userTransform.setRotate(-tr['angle']) #self.updateTransform() #self.selectBoxFromUser() #return #elif not flip: #if tr['scale'][0] > 0 and tr['scale'][1] > 0: #return #else: #self.userTransform.setScale([-tr['scale'][0], tr['scale'][1]]) #self.userTransform.setTranslate([-tr['pos'][0], tr['pos'][1]]) #self.userTransform.setRotate(-tr['angle']) #self.updateTransform() #self.selectBoxFromUser() #return def mirrorXY(self): if not self.isMovable(): return self.rotate(180.) # inv = SRTTransform() # inv.scale(-1, -1) # self.userTransform = self.userTransform * inv #flip lr/ud # s=self.updateTransform() # self.setTranslate(-2*s['pos'][0], -2*s['pos'][1]) # self.selectBoxFromUser() def hasUserTransform(self): #print self.userRotate, self.userTranslate return not self.userTransform.isIdentity() def ctrlWidget(self): return self.ctrl def alphaChanged(self, val): alpha = val / 1023. self._graphicsItem.setOpacity(alpha) def setAlpha(self, alpha): self.alphaSlider.setValue(int(np.clip(alpha * 1023, 0, 1023))) def alpha(self): return self.alphaSlider.value() / 1023. def isMovable(self): return self.opts['movable'] def selectBoxMoved(self): """The selection box has moved; get its transformation information and pass to the graphics item""" self.userTransform = self.selectBox.getGlobalTransform(relativeTo=self.selectBoxBase) self.updateTransform() def scale(self, x, y): self.userTransform.scale(x, y) self.selectBoxFromUser() self.updateTransform() def rotate(self, ang): self.userTransform.rotate(ang) self.selectBoxFromUser() self.updateTransform() def translate(self, x, y): self.userTransform.translate(x, y) self.selectBoxFromUser() self.updateTransform() def setTranslate(self, x, y): self.userTransform.setTranslate(x, y) self.selectBoxFromUser() self.updateTransform() def setRotate(self, angle): self.userTransform.setRotate(angle) self.selectBoxFromUser() self.updateTransform() def setScale(self, x, y): self.userTransform.setScale(x, y) self.selectBoxFromUser() self.updateTransform() def setTemporaryTransform(self, transform): self.tempTransform = transform self.updateTransform() def applyTemporaryTransform(self): """Collapses tempTransform into UserTransform, resets tempTransform""" self.userTransform = self.userTransform * self.tempTransform ## order is important! self.resetTemporaryTransform() self.selectBoxFromUser() ## update the selection box to match the new userTransform def resetTemporaryTransform(self): self.tempTransform = SRTTransform() ## don't use Transform.reset()--this transform might be used elsewhere. self.updateTransform() def transform(self): return self._graphicsItem.transform() def updateTransform(self): """Regenerate the item position from the base, user, and temp transforms""" transform = self.baseTransform * self.userTransform * self.tempTransform ## order is important s = transform.saveState() self._graphicsItem.setPos(*s['pos']) self.itemRotation.setAngle(s['angle']) self.itemScale.setXScale(s['scale'][0]) self.itemScale.setYScale(s['scale'][1]) self.displayTransform(transform) return(s) # return the transform state def displayTransform(self, transform): """Updates transform numbers in the ctrl widget.""" tr = transform.saveState() self.transformGui.translateLabel.setText("Translate: (%f, %f)" %(tr['pos'][0], tr['pos'][1])) self.transformGui.rotateLabel.setText("Rotate: %f degrees" %tr['angle']) self.transformGui.scaleLabel.setText("Scale: (%f, %f)" %(tr['scale'][0], tr['scale'][1])) def resetUserTransform(self): self.userTransform.reset() self.updateTransform() self.selectBox.blockSignals(True) self.selectBoxToItem() self.selectBox.blockSignals(False) self.sigTransformChanged.emit(self) self.sigTransformChangeFinished.emit(self) def resetTransformClicked(self): self.resetUserTransform() self.sigResetUserTransform.emit(self) def restoreTransform(self, tr): try: self.userTransform = SRTTransform(tr) self.updateTransform() self.selectBoxFromUser() ## move select box to match self.sigTransformChanged.emit(self) self.sigTransformChangeFinished.emit(self) except: self.userTransform = SRTTransform() debug.printExc("Failed to load transform:") def saveTransform(self): """Return a dict containing the current user transform""" return self.userTransform.saveState() def selectBoxFromUser(self): """Move the selection box to match the current userTransform""" ## user transform #trans = QtGui.QTransform() #trans.translate(*self.userTranslate) #trans.rotate(-self.userRotate) #x2, y2 = trans.map(*self.selectBoxBase['pos']) self.selectBox.blockSignals(True) self.selectBox.setState(self.selectBoxBase) self.selectBox.applyGlobalTransform(self.userTransform) #self.selectBox.setAngle(self.userRotate) #self.selectBox.setPos([x2, y2]) self.selectBox.blockSignals(False) def selectBoxToItem(self): """Move/scale the selection box so it fits the item's bounding rect. (assumes item is not rotated)""" self.itemRect = self._graphicsItem.boundingRect() rect = self._graphicsItem.mapRectToParent(self.itemRect) self.selectBox.blockSignals(True) self.selectBox.setPos([rect.x(), rect.y()]) self.selectBox.setSize(rect.size()) self.selectBox.setAngle(0) self.selectBoxBase = self.selectBox.getState().copy() self.selectBox.blockSignals(False) def zValue(self): return self.opts['z'] def setZValue(self, z): self.opts['z'] = z if z is not None: self._graphicsItem.setZValue(z) def selectionChanged(self, sel, multi): """ Inform the item that its selection state has changed. ============== ========================================================= **Arguments:** sel (bool) whether the item is currently selected multi (bool) whether there are multiple items currently selected ============== ========================================================= """ self.selectedAlone = sel and not multi self.showSelectBox() if self.selectedAlone: self.ctrlWidget().show() else: self.ctrlWidget().hide() def showSelectBox(self): """Display the selection box around this item if it is selected and movable""" if self.selectedAlone and self.isMovable() and self.isVisible(): #and len(self.canvas.itemList.selectedItems())==1: self.selectBox.show() else: self.selectBox.hide() def hideSelectBox(self): self.selectBox.hide() def selectBoxChanged(self): self.selectBoxMoved() self.sigTransformChanged.emit(self) def selectBoxChangeFinished(self): self.sigTransformChangeFinished.emit(self) def alphaPressed(self): """Hide selection box while slider is moving""" self.hideSelectBox() def alphaReleased(self): self.showSelectBox() def show(self): if self.opts['visible']: return self.opts['visible'] = True self._graphicsItem.show() self.showSelectBox() self.sigVisibilityChanged.emit(self) def hide(self): if not self.opts['visible']: return self.opts['visible'] = False self._graphicsItem.hide() self.hideSelectBox() self.sigVisibilityChanged.emit(self) def setVisible(self, vis): if vis: self.show() else: self.hide() def isVisible(self): return self.opts['visible'] def saveState(self): return { 'type': self.__class__.__name__, 'name': self.name, 'visible': self.isVisible(), 'alpha': self.alpha(), 'userTransform': self.saveTransform(), 'z': self.zValue(), 'scalable': self.opts['scalable'], 'rotatable': self.opts['rotatable'], 'movable': self.opts['movable'], } def restoreState(self, state): self.setVisible(state['visible']) self.setAlpha(state['alpha']) self.restoreTransform(state['userTransform']) self.setZValue(state['z']) class GroupCanvasItem(CanvasItem): """ Canvas item used for grouping others """ def __init__(self, **opts): defOpts = {'movable': False, 'scalable': False} defOpts.update(opts) item = ItemGroup() CanvasItem.__init__(self, item, **defOpts)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/GraphicsLayoutWidget.py
.py
2,878
66
# -*- coding: utf-8 -*- from ..Qt import QtGui, mkQApp from ..graphicsItems.GraphicsLayout import GraphicsLayout from .GraphicsView import GraphicsView __all__ = ['GraphicsLayoutWidget'] class GraphicsLayoutWidget(GraphicsView): """ Convenience class consisting of a :class:`GraphicsView <pyqtgraph.GraphicsView>` with a single :class:`GraphicsLayout <pyqtgraph.GraphicsLayout>` as its central item. This widget is an easy starting point for generating multi-panel figures. Example:: w = pg.GraphicsLayoutWidget() p1 = w.addPlot(row=0, col=0) p2 = w.addPlot(row=0, col=1) v = w.addViewBox(row=1, col=0, colspan=2) ========= ================================================================= parent (QWidget or None) The parent widget. show (bool) If True, then immediately show the widget after it is created. If the widget has no parent, then it will be shown inside a new window. size (width, height) tuple. Optionally resize the widget. Note: if this widget is placed inside a layout, then this argument has no effect. title (str or None) If specified, then set the window title for this widget. kargs All extra arguments are passed to :meth:`GraphicsLayout.__init__ <pyqtgraph.GraphicsLayout.__init__>` ========= ================================================================= This class wraps several methods from its internal GraphicsLayout: :func:`nextRow <pyqtgraph.GraphicsLayout.nextRow>` :func:`nextColumn <pyqtgraph.GraphicsLayout.nextColumn>` :func:`addPlot <pyqtgraph.GraphicsLayout.addPlot>` :func:`addViewBox <pyqtgraph.GraphicsLayout.addViewBox>` :func:`addItem <pyqtgraph.GraphicsLayout.addItem>` :func:`getItem <pyqtgraph.GraphicsLayout.getItem>` :func:`addLabel <pyqtgraph.GraphicsLayout.addLabel>` :func:`addLayout <pyqtgraph.GraphicsLayout.addLayout>` :func:`removeItem <pyqtgraph.GraphicsLayout.removeItem>` :func:`itemIndex <pyqtgraph.GraphicsLayout.itemIndex>` :func:`clear <pyqtgraph.GraphicsLayout.clear>` """ def __init__(self, parent=None, show=False, size=None, title=None, **kargs): mkQApp() GraphicsView.__init__(self, parent) self.ci = GraphicsLayout(**kargs) for n in ['nextRow', 'nextCol', 'nextColumn', 'addPlot', 'addViewBox', 'addItem', 'getItem', 'addLayout', 'addLabel', 'removeItem', 'itemIndex', 'clear']: setattr(self, n, getattr(self.ci, n)) self.setCentralItem(self.ci) if size is not None: self.resize(*size) if title is not None: self.setWindowTitle(title) if show is True: self.show()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/GroupBox.py
.py
3,143
94
from ..Qt import QtGui, QtCore from .PathButton import PathButton from ..python2_3 import basestring class GroupBox(QtGui.QGroupBox): """Subclass of QGroupBox that implements collapse handle. """ sigCollapseChanged = QtCore.Signal(object) def __init__(self, *args): QtGui.QGroupBox.__init__(self, *args) self._collapsed = False # We modify the size policy when the group box is collapsed, so # keep track of the last requested policy: self._lastSizePlocy = self.sizePolicy() self.closePath = QtGui.QPainterPath() self.closePath.moveTo(0, -1) self.closePath.lineTo(0, 1) self.closePath.lineTo(1, 0) self.closePath.lineTo(0, -1) self.openPath = QtGui.QPainterPath() self.openPath.moveTo(-1, 0) self.openPath.lineTo(1, 0) self.openPath.lineTo(0, 1) self.openPath.lineTo(-1, 0) self.collapseBtn = PathButton(path=self.openPath, size=(12, 12), margin=0) self.collapseBtn.setStyleSheet(""" border: none; """) self.collapseBtn.setPen('k') self.collapseBtn.setBrush('w') self.collapseBtn.setParent(self) self.collapseBtn.move(3, 3) self.collapseBtn.setFlat(True) self.collapseBtn.clicked.connect(self.toggleCollapsed) if len(args) > 0 and isinstance(args[0], basestring): self.setTitle(args[0]) def toggleCollapsed(self): self.setCollapsed(not self._collapsed) def collapsed(self): return self._collapsed def setCollapsed(self, c): if c == self._collapsed: return if c is True: self.collapseBtn.setPath(self.closePath) self.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred, closing=True) elif c is False: self.collapseBtn.setPath(self.openPath) self.setSizePolicy(self._lastSizePolicy) else: raise TypeError("Invalid argument %r; must be bool." % c) for ch in self.children(): if isinstance(ch, QtGui.QWidget) and ch is not self.collapseBtn: ch.setVisible(not c) self._collapsed = c self.sigCollapseChanged.emit(c) def setSizePolicy(self, *args, **kwds): QtGui.QGroupBox.setSizePolicy(self, *args) if kwds.pop('closing', False) is True: self._lastSizePolicy = self.sizePolicy() def setHorizontalPolicy(self, *args): QtGui.QGroupBox.setHorizontalPolicy(self, *args) self._lastSizePolicy = self.sizePolicy() def setVerticalPolicy(self, *args): QtGui.QGroupBox.setVerticalPolicy(self, *args) self._lastSizePolicy = self.sizePolicy() def setTitle(self, title): # Leave room for button QtGui.QGroupBox.setTitle(self, " " + title) def widgetGroupInterface(self): return (self.sigCollapseChanged, GroupBox.collapsed, GroupBox.setCollapsed, True)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/LayoutWidget.py
.py
3,430
102
from ..Qt import QtGui, QtCore __all__ = ['LayoutWidget'] class LayoutWidget(QtGui.QWidget): """ Convenience class used for laying out QWidgets in a grid. (It's just a little less effort to use than QGridLayout) """ def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.layout = QtGui.QGridLayout() self.setLayout(self.layout) self.items = {} self.rows = {} self.currentRow = 0 self.currentCol = 0 def nextRow(self): """Advance to next row for automatic widget placement""" self.currentRow += 1 self.currentCol = 0 def nextColumn(self, colspan=1): """Advance to next column, while returning the current column number (generally only for internal use--called by addWidget)""" self.currentCol += colspan return self.currentCol-colspan def nextCol(self, *args, **kargs): """Alias of nextColumn""" return self.nextColumn(*args, **kargs) def addLabel(self, text=' ', row=None, col=None, rowspan=1, colspan=1, **kargs): """ Create a QLabel with *text* and place it in the next available cell (or in the cell specified) All extra keyword arguments are passed to QLabel(). Returns the created widget. """ text = QtGui.QLabel(text, **kargs) self.addWidget(text, row, col, rowspan, colspan) return text def addLayout(self, row=None, col=None, rowspan=1, colspan=1, **kargs): """ Create an empty LayoutWidget and place it in the next available cell (or in the cell specified) All extra keyword arguments are passed to :func:`LayoutWidget.__init__ <pyqtgraph.LayoutWidget.__init__>` Returns the created widget. """ layout = LayoutWidget(**kargs) self.addWidget(layout, row, col, rowspan, colspan) return layout def addWidget(self, item, row=None, col=None, rowspan=1, colspan=1): """ Add a widget to the layout and place it in the next available cell (or in the cell specified). """ if row == 'next': self.nextRow() row = self.currentRow elif row is None: row = self.currentRow if col is None: col = self.nextCol(colspan) if row not in self.rows: self.rows[row] = {} self.rows[row][col] = item self.items[item] = (row, col) self.layout.addWidget(item, row, col, rowspan, colspan) def getWidget(self, row, col): """Return the widget in (*row*, *col*)""" return self.rows[row][col] #def itemIndex(self, item): #for i in range(self.layout.count()): #if self.layout.itemAt(i).graphicsItem() is item: #return i #raise Exception("Could not determine index of item " + str(item)) #def removeItem(self, item): #"""Remove *item* from the layout.""" #ind = self.itemIndex(item) #self.layout.removeAt(ind) #self.scene().removeItem(item) #r,c = self.items[item] #del self.items[item] #del self.rows[r][c] #self.update() #def clear(self): #items = [] #for i in list(self.items.keys()): #self.removeItem(i)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/MatplotlibWidget.py
.py
1,573
50
from ..Qt import QtGui, QtCore, QT_LIB import matplotlib if QT_LIB != 'PyQt5': if QT_LIB == 'PySide': matplotlib.rcParams['backend.qt4']='PySide' from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas try: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar except ImportError: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar else: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar from matplotlib.figure import Figure class MatplotlibWidget(QtGui.QWidget): """ Implements a Matplotlib figure inside a QWidget. Use getFigure() and redraw() to interact with matplotlib. Example:: mw = MatplotlibWidget() subplot = mw.getFigure().add_subplot(111) subplot.plot(x,y) mw.draw() """ def __init__(self, size=(5.0, 4.0), dpi=100): QtGui.QWidget.__init__(self) self.fig = Figure(size, dpi=dpi) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self) self.toolbar = NavigationToolbar(self.canvas, self) self.vbox = QtGui.QVBoxLayout() self.vbox.addWidget(self.toolbar) self.vbox.addWidget(self.canvas) self.setLayout(self.vbox) def getFigure(self): return self.fig def draw(self): self.canvas.draw()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/JoystickButton.py
.py
2,460
95
from ..Qt import QtGui, QtCore __all__ = ['JoystickButton'] class JoystickButton(QtGui.QPushButton): sigStateChanged = QtCore.Signal(object, object) ## self, state def __init__(self, parent=None): QtGui.QPushButton.__init__(self, parent) self.radius = 200 self.setCheckable(True) self.state = None self.setState(0,0) self.setFixedWidth(50) self.setFixedHeight(50) def mousePressEvent(self, ev): self.setChecked(True) self.pressPos = ev.pos() ev.accept() def mouseMoveEvent(self, ev): dif = ev.pos()-self.pressPos self.setState(dif.x(), -dif.y()) def mouseReleaseEvent(self, ev): self.setChecked(False) self.setState(0,0) def wheelEvent(self, ev): ev.accept() def doubleClickEvent(self, ev): ev.accept() def getState(self): return self.state def setState(self, *xy): xy = list(xy) d = (xy[0]**2 + xy[1]**2)**0.5 nxy = [0,0] for i in [0,1]: if xy[i] == 0: nxy[i] = 0 else: nxy[i] = xy[i]/d if d > self.radius: d = self.radius d = (d/self.radius)**2 xy = [nxy[0]*d, nxy[1]*d] w2 = self.width()/2. h2 = self.height()/2 self.spotPos = QtCore.QPoint(w2*(1+xy[0]), h2*(1-xy[1])) self.update() if self.state == xy: return self.state = xy self.sigStateChanged.emit(self, self.state) def paintEvent(self, ev): QtGui.QPushButton.paintEvent(self, ev) p = QtGui.QPainter(self) p.setBrush(QtGui.QBrush(QtGui.QColor(0,0,0))) p.drawEllipse(self.spotPos.x()-3,self.spotPos.y()-3,6,6) def resizeEvent(self, ev): self.setState(*self.state) QtGui.QPushButton.resizeEvent(self, ev) if __name__ == '__main__': app = QtGui.QApplication([]) w = QtGui.QMainWindow() b = JoystickButton() w.setCentralWidget(b) w.show() w.resize(100, 100) def fn(b, s): print("state changed:", s) b.sigStateChanged.connect(fn) ## Start Qt event loop unless running in interactive mode. import sys if sys.flags.interactive != 1: app.exec_()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/GraphicsView.py
.py
16,246
425
# -*- coding: utf-8 -*- """ GraphicsView.py - Extension of QGraphicsView Copyright 2010 Luke Campagnola Distributed under MIT/X11 license. See license.txt for more information. """ from ..Qt import QtCore, QtGui, QT_LIB try: from ..Qt import QtOpenGL HAVE_OPENGL = True except ImportError: HAVE_OPENGL = False from ..Point import Point import sys, os import warnings from .FileDialog import FileDialog from ..GraphicsScene import GraphicsScene import numpy as np from .. import functions as fn from .. import debug as debug from .. import getConfigOption __all__ = ['GraphicsView'] class GraphicsView(QtGui.QGraphicsView): """Re-implementation of QGraphicsView that removes scrollbars and allows unambiguous control of the viewed coordinate range. Also automatically creates a GraphicsScene and a central QGraphicsWidget that is automatically scaled to the full view geometry. This widget is the basis for :class:`PlotWidget <pyqtgraph.PlotWidget>`, :class:`GraphicsLayoutWidget <pyqtgraph.GraphicsLayoutWidget>`, and the view widget in :class:`ImageView <pyqtgraph.ImageView>`. By default, the view coordinate system matches the widget's pixel coordinates and automatically updates when the view is resized. This can be overridden by setting autoPixelRange=False. The exact visible range can be set with setRange(). The view can be panned using the middle mouse button and scaled using the right mouse button if enabled via enableMouse() (but ordinarily, we use ViewBox for this functionality).""" sigDeviceRangeChanged = QtCore.Signal(object, object) sigDeviceTransformChanged = QtCore.Signal(object) sigMouseReleased = QtCore.Signal(object) sigSceneMouseMoved = QtCore.Signal(object) #sigRegionChanged = QtCore.Signal(object) sigScaleChanged = QtCore.Signal(object) lastFileDir = None def __init__(self, parent=None, useOpenGL=None, background='default'): """ ============== ============================================================ **Arguments:** parent Optional parent widget useOpenGL If True, the GraphicsView will use OpenGL to do all of its rendering. This can improve performance on some systems, but may also introduce bugs (the combination of QGraphicsView and QGLWidget is still an 'experimental' feature of Qt) background Set the background color of the GraphicsView. Accepts any single argument accepted by :func:`mkColor <pyqtgraph.mkColor>`. By default, the background color is determined using the 'backgroundColor' configuration option (see :func:`setConfigOptions <pyqtgraph.setConfigOptions>`). ============== ============================================================ """ self.closed = False QtGui.QGraphicsView.__init__(self, parent) # This connects a cleanup function to QApplication.aboutToQuit. It is # called from here because we have no good way to react when the # QApplication is created by the user. # See pyqtgraph.__init__.py from .. import _connectCleanup _connectCleanup() if useOpenGL is None: useOpenGL = getConfigOption('useOpenGL') self.useOpenGL(useOpenGL) self.setCacheMode(self.CacheBackground) ## This might help, but it's probably dangerous in the general case.. #self.setOptimizationFlag(self.DontSavePainterState, True) self.setBackgroundRole(QtGui.QPalette.NoRole) self.setBackground(background) self.setFocusPolicy(QtCore.Qt.StrongFocus) self.setFrameShape(QtGui.QFrame.NoFrame) self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setTransformationAnchor(QtGui.QGraphicsView.NoAnchor) self.setResizeAnchor(QtGui.QGraphicsView.AnchorViewCenter) self.setViewportUpdateMode(QtGui.QGraphicsView.MinimalViewportUpdate) self.lockedViewports = [] self.lastMousePos = None self.setMouseTracking(True) self.aspectLocked = False self.range = QtCore.QRectF(0, 0, 1, 1) self.autoPixelRange = True self.currentItem = None self.clearMouse() self.updateMatrix() # GraphicsScene must have parent or expect crashes! self.sceneObj = GraphicsScene(parent=self) self.setScene(self.sceneObj) ## Workaround for PySide crash ## This ensures that the scene will outlive the view. if QT_LIB == 'PySide': self.sceneObj._view_ref_workaround = self ## by default we set up a central widget with a grid layout. ## this can be replaced if needed. self.centralWidget = None self.setCentralItem(QtGui.QGraphicsWidget()) self.centralLayout = QtGui.QGraphicsGridLayout() self.centralWidget.setLayout(self.centralLayout) self.mouseEnabled = False self.scaleCenter = False ## should scaling center around view center (True) or mouse click (False) self.clickAccepted = False def setAntialiasing(self, aa): """Enable or disable default antialiasing. Note that this will only affect items that do not specify their own antialiasing options.""" if aa: self.setRenderHints(self.renderHints() | QtGui.QPainter.Antialiasing) else: self.setRenderHints(self.renderHints() & ~QtGui.QPainter.Antialiasing) def setBackground(self, background): """ Set the background color of the GraphicsView. To use the defaults specified py pyqtgraph.setConfigOption, use background='default'. To make the background transparent, use background=None. """ self._background = background if background == 'default': background = getConfigOption('background') brush = fn.mkBrush(background) self.setBackgroundBrush(brush) def paintEvent(self, ev): self.scene().prepareForPaint() return QtGui.QGraphicsView.paintEvent(self, ev) def render(self, *args, **kwds): self.scene().prepareForPaint() return QtGui.QGraphicsView.render(self, *args, **kwds) def close(self): self.centralWidget = None self.scene().clear() self.currentItem = None self.sceneObj = None self.closed = True self.setViewport(None) super(GraphicsView, self).close() def useOpenGL(self, b=True): if b: if not HAVE_OPENGL: raise Exception("Requested to use OpenGL with QGraphicsView, but QtOpenGL module is not available.") v = QtOpenGL.QGLWidget() else: v = QtGui.QWidget() self.setViewport(v) def keyPressEvent(self, ev): self.scene().keyPressEvent(ev) ## bypass view, hand event directly to scene ## (view likes to eat arrow key events) def setCentralItem(self, item): return self.setCentralWidget(item) def setCentralWidget(self, item): """Sets a QGraphicsWidget to automatically fill the entire view (the item will be automatically resize whenever the GraphicsView is resized).""" if self.centralWidget is not None: self.scene().removeItem(self.centralWidget) self.centralWidget = item if item is not None: self.sceneObj.addItem(item) self.resizeEvent(None) def addItem(self, *args): return self.scene().addItem(*args) def removeItem(self, *args): return self.scene().removeItem(*args) def enableMouse(self, b=True): self.mouseEnabled = b self.autoPixelRange = (not b) def clearMouse(self): self.mouseTrail = [] self.lastButtonReleased = None def resizeEvent(self, ev): if self.closed: return if self.autoPixelRange: self.range = QtCore.QRectF(0, 0, self.size().width(), self.size().height()) GraphicsView.setRange(self, self.range, padding=0, disableAutoPixel=False) ## we do this because some subclasses like to redefine setRange in an incompatible way. self.updateMatrix() def updateMatrix(self, propagate=True): self.setSceneRect(self.range) if self.autoPixelRange: self.resetTransform() else: if self.aspectLocked: self.fitInView(self.range, QtCore.Qt.KeepAspectRatio) else: self.fitInView(self.range, QtCore.Qt.IgnoreAspectRatio) if propagate: for v in self.lockedViewports: v.setXRange(self.range, padding=0) self.sigDeviceRangeChanged.emit(self, self.range) self.sigDeviceTransformChanged.emit(self) def viewRect(self): """Return the boundaries of the view in scene coordinates""" ## easier to just return self.range ? r = QtCore.QRectF(self.rect()) return self.viewportTransform().inverted()[0].mapRect(r) def visibleRange(self): ## for backward compatibility return self.viewRect() def translate(self, dx, dy): self.range.adjust(dx, dy, dx, dy) self.updateMatrix() def scale(self, sx, sy, center=None): scale = [sx, sy] if self.aspectLocked: scale[0] = scale[1] if self.scaleCenter: center = None if center is None: center = self.range.center() w = self.range.width() / scale[0] h = self.range.height() / scale[1] self.range = QtCore.QRectF(center.x() - (center.x()-self.range.left()) / scale[0], center.y() - (center.y()-self.range.top()) /scale[1], w, h) self.updateMatrix() self.sigScaleChanged.emit(self) def setRange(self, newRect=None, padding=0.05, lockAspect=None, propagate=True, disableAutoPixel=True): if disableAutoPixel: self.autoPixelRange=False if newRect is None: newRect = self.visibleRange() padding = 0 padding = Point(padding) newRect = QtCore.QRectF(newRect) pw = newRect.width() * padding[0] ph = newRect.height() * padding[1] newRect = newRect.adjusted(-pw, -ph, pw, ph) scaleChanged = False if self.range.width() != newRect.width() or self.range.height() != newRect.height(): scaleChanged = True self.range = newRect #print "New Range:", self.range if self.centralWidget is not None: self.centralWidget.setGeometry(self.range) self.updateMatrix(propagate) if scaleChanged: self.sigScaleChanged.emit(self) def scaleToImage(self, image): """Scales such that pixels in image are the same size as screen pixels. This may result in a significant performance increase.""" pxSize = image.pixelSize() image.setPxMode(True) try: self.sigScaleChanged.disconnect(image.setScaledMode) except (TypeError, RuntimeError): pass tl = image.sceneBoundingRect().topLeft() w = self.size().width() * pxSize[0] h = self.size().height() * pxSize[1] range = QtCore.QRectF(tl.x(), tl.y(), w, h) GraphicsView.setRange(self, range, padding=0) self.sigScaleChanged.connect(image.setScaledMode) def lockXRange(self, v1): if not v1 in self.lockedViewports: self.lockedViewports.append(v1) def setXRange(self, r, padding=0.05): r1 = QtCore.QRectF(self.range) r1.setLeft(r.left()) r1.setRight(r.right()) GraphicsView.setRange(self, r1, padding=[padding, 0], propagate=False) def setYRange(self, r, padding=0.05): r1 = QtCore.QRectF(self.range) r1.setTop(r.top()) r1.setBottom(r.bottom()) GraphicsView.setRange(self, r1, padding=[0, padding], propagate=False) def wheelEvent(self, ev): QtGui.QGraphicsView.wheelEvent(self, ev) if not self.mouseEnabled: ev.ignore() return delta = 0 if QT_LIB in ['PyQt4', 'PySide']: delta = ev.delta() else: delta = ev.angleDelta().x() if delta == 0: delta = ev.angleDelta().y() sc = 1.001 ** delta #self.scale *= sc #self.updateMatrix() self.scale(sc, sc) def setAspectLocked(self, s): self.aspectLocked = s def leaveEvent(self, ev): self.scene().leaveEvent(ev) ## inform scene when mouse leaves def mousePressEvent(self, ev): QtGui.QGraphicsView.mousePressEvent(self, ev) if not self.mouseEnabled: return self.lastMousePos = Point(ev.pos()) self.mousePressPos = ev.pos() self.clickAccepted = ev.isAccepted() if not self.clickAccepted: self.scene().clearSelection() return ## Everything below disabled for now.. def mouseReleaseEvent(self, ev): QtGui.QGraphicsView.mouseReleaseEvent(self, ev) if not self.mouseEnabled: return self.sigMouseReleased.emit(ev) self.lastButtonReleased = ev.button() return ## Everything below disabled for now.. def mouseMoveEvent(self, ev): if self.lastMousePos is None: self.lastMousePos = Point(ev.pos()) delta = Point(ev.pos() - QtCore.QPoint(*self.lastMousePos)) self.lastMousePos = Point(ev.pos()) QtGui.QGraphicsView.mouseMoveEvent(self, ev) if not self.mouseEnabled: return self.sigSceneMouseMoved.emit(self.mapToScene(ev.pos())) if self.clickAccepted: ## Ignore event if an item in the scene has already claimed it. return if ev.buttons() == QtCore.Qt.RightButton: delta = Point(np.clip(delta[0], -50, 50), np.clip(-delta[1], -50, 50)) scale = 1.01 ** delta self.scale(scale[0], scale[1], center=self.mapToScene(self.mousePressPos)) self.sigDeviceRangeChanged.emit(self, self.range) elif ev.buttons() in [QtCore.Qt.MidButton, QtCore.Qt.LeftButton]: ## Allow panning by left or mid button. px = self.pixelSize() tr = -delta * px self.translate(tr[0], tr[1]) self.sigDeviceRangeChanged.emit(self, self.range) def pixelSize(self): """Return vector with the length and width of one view pixel in scene coordinates""" p0 = Point(0,0) p1 = Point(1,1) tr = self.transform().inverted()[0] p01 = tr.map(p0) p11 = tr.map(p1) return Point(p11 - p01) def dragEnterEvent(self, ev): ev.ignore() ## not sure why, but for some reason this class likes to consume drag events def _del(self): try: if self.parentWidget() is None and self.isVisible(): msg = "Visible window deleted. To prevent this, store a reference to the window object." try: warnings.warn(msg, RuntimeWarning, stacklevel=2) except TypeError: # warnings module not available during interpreter shutdown pass except RuntimeError: pass if sys.version_info[0] == 3 and sys.version_info[1] >= 4: GraphicsView.__del__ = GraphicsView._del
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/HistogramLUTWidget.py
.py
940
34
""" Widget displaying an image histogram along with gradient editor. Can be used to adjust the appearance of images. This is a wrapper around HistogramLUTItem """ from ..Qt import QtGui, QtCore from .GraphicsView import GraphicsView from ..graphicsItems.HistogramLUTItem import HistogramLUTItem __all__ = ['HistogramLUTWidget'] class HistogramLUTWidget(GraphicsView): def __init__(self, parent=None, *args, **kargs): background = kargs.pop('background', 'default') GraphicsView.__init__(self, parent, useOpenGL=False, background=background) self.item = HistogramLUTItem(*args, **kargs) self.setCentralItem(self.item) self.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Expanding) self.setMinimumWidth(95) def sizeHint(self): return QtCore.QSize(115, 200) def __getattr__(self, attr): return getattr(self.item, attr)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/TableWidget.py
.py
18,472
508
# -*- coding: utf-8 -*- import numpy as np from ..Qt import QtGui, QtCore from ..python2_3 import asUnicode, basestring from .. import metaarray __all__ = ['TableWidget'] def _defersort(fn): def defersort(self, *args, **kwds): # may be called recursively; only the first call needs to block sorting setSorting = False if self._sorting is None: self._sorting = self.isSortingEnabled() setSorting = True self.setSortingEnabled(False) try: return fn(self, *args, **kwds) finally: if setSorting: self.setSortingEnabled(self._sorting) self._sorting = None return defersort class TableWidget(QtGui.QTableWidget): """Extends QTableWidget with some useful functions for automatic data handling and copy / export context menu. Can automatically format and display a variety of data types (see :func:`setData() <pyqtgraph.TableWidget.setData>` for more information. """ def __init__(self, *args, **kwds): """ All positional arguments are passed to QTableWidget.__init__(). ===================== ================================================= **Keyword Arguments** editable (bool) If True, cells in the table can be edited by the user. Default is False. sortable (bool) If True, the table may be soted by clicking on column headers. Note that this also causes rows to appear initially shuffled until a sort column is selected. Default is True. *(added in version 0.9.9)* ===================== ================================================= """ QtGui.QTableWidget.__init__(self, *args) self.itemClass = TableWidgetItem self.setVerticalScrollMode(self.ScrollPerPixel) self.setSelectionMode(QtGui.QAbstractItemView.ContiguousSelection) self.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) self.clear() kwds.setdefault('sortable', True) kwds.setdefault('editable', False) self.setEditable(kwds.pop('editable')) self.setSortingEnabled(kwds.pop('sortable')) if len(kwds) > 0: raise TypeError("Invalid keyword arguments '%s'" % kwds.keys()) self._sorting = None # used when temporarily disabling sorting self._formats = {None: None} # stores per-column formats and entire table format self.sortModes = {} # stores per-column sort mode self.itemChanged.connect(self.handleItemChanged) self.contextMenu = QtGui.QMenu() self.contextMenu.addAction('Copy Selection').triggered.connect(self.copySel) self.contextMenu.addAction('Copy All').triggered.connect(self.copyAll) self.contextMenu.addAction('Save Selection').triggered.connect(self.saveSel) self.contextMenu.addAction('Save All').triggered.connect(self.saveAll) def clear(self): """Clear all contents from the table.""" QtGui.QTableWidget.clear(self) self.verticalHeadersSet = False self.horizontalHeadersSet = False self.items = [] self.setRowCount(0) self.setColumnCount(0) self.sortModes = {} def setData(self, data): """Set the data displayed in the table. Allowed formats are: * numpy arrays * numpy record arrays * metaarrays * list-of-lists [[1,2,3], [4,5,6]] * dict-of-lists {'x': [1,2,3], 'y': [4,5,6]} * list-of-dicts [{'x': 1, 'y': 4}, {'x': 2, 'y': 5}, ...] """ self.clear() self.appendData(data) self.resizeColumnsToContents() @_defersort def appendData(self, data): """ Add new rows to the table. See :func:`setData() <pyqtgraph.TableWidget.setData>` for accepted data types. """ startRow = self.rowCount() fn0, header0 = self.iteratorFn(data) if fn0 is None: self.clear() return it0 = fn0(data) try: first = next(it0) except StopIteration: return fn1, header1 = self.iteratorFn(first) if fn1 is None: self.clear() return firstVals = [x for x in fn1(first)] self.setColumnCount(len(firstVals)) if not self.verticalHeadersSet and header0 is not None: labels = [self.verticalHeaderItem(i).text() for i in range(self.rowCount())] self.setRowCount(startRow + len(header0)) self.setVerticalHeaderLabels(labels + header0) self.verticalHeadersSet = True if not self.horizontalHeadersSet and header1 is not None: self.setHorizontalHeaderLabels(header1) self.horizontalHeadersSet = True i = startRow self.setRow(i, firstVals) for row in it0: i += 1 self.setRow(i, [x for x in fn1(row)]) if (self._sorting and self.horizontalHeadersSet and self.horizontalHeader().sortIndicatorSection() >= self.columnCount()): self.sortByColumn(0, QtCore.Qt.AscendingOrder) def setEditable(self, editable=True): self.editable = editable for item in self.items: item.setEditable(editable) def setFormat(self, format, column=None): """ Specify the default text formatting for the entire table, or for a single column if *column* is specified. If a string is specified, it is used as a format string for converting float values (and all other types are converted using str). If a function is specified, it will be called with the item as its only argument and must return a string. Setting format = None causes the default formatter to be used instead. Added in version 0.9.9. """ if format is not None and not isinstance(format, basestring) and not callable(format): raise ValueError("Format argument must string, callable, or None. (got %s)" % format) self._formats[column] = format if column is None: # update format of all items that do not have a column format # specified for c in range(self.columnCount()): if self._formats.get(c, None) is None: for r in range(self.rowCount()): item = self.item(r, c) if item is None: continue item.setFormat(format) else: # set all items in the column to use this format, or the default # table format if None was specified. if format is None: format = self._formats[None] for r in range(self.rowCount()): item = self.item(r, column) if item is None: continue item.setFormat(format) def iteratorFn(self, data): ## Return 1) a function that will provide an iterator for data and 2) a list of header strings if isinstance(data, list) or isinstance(data, tuple): return lambda d: d.__iter__(), None elif isinstance(data, dict): return lambda d: iter(d.values()), list(map(asUnicode, data.keys())) elif (hasattr(data, 'implements') and data.implements('MetaArray')): if data.axisHasColumns(0): header = [asUnicode(data.columnName(0, i)) for i in range(data.shape[0])] elif data.axisHasValues(0): header = list(map(asUnicode, data.xvals(0))) else: header = None return self.iterFirstAxis, header elif isinstance(data, np.ndarray): return self.iterFirstAxis, None elif isinstance(data, np.void): return self.iterate, list(map(asUnicode, data.dtype.names)) elif data is None: return (None,None) elif np.isscalar(data): return self.iterateScalar, None else: msg = "Don't know how to iterate over data type: {!s}".format(type(data)) raise TypeError(msg) def iterFirstAxis(self, data): for i in range(data.shape[0]): yield data[i] def iterate(self, data): # for numpy.void, which can be iterated but mysteriously # has no __iter__ (??) for x in data: yield x def iterateScalar(self, data): yield data def appendRow(self, data): self.appendData([data]) @_defersort def addRow(self, vals): row = self.rowCount() self.setRowCount(row + 1) self.setRow(row, vals) @_defersort def setRow(self, row, vals): if row > self.rowCount() - 1: self.setRowCount(row + 1) for col in range(len(vals)): val = vals[col] item = self.itemClass(val, row) item.setEditable(self.editable) sortMode = self.sortModes.get(col, None) if sortMode is not None: item.setSortMode(sortMode) format = self._formats.get(col, self._formats[None]) item.setFormat(format) self.items.append(item) self.setItem(row, col, item) item.setValue(val) # Required--the text-change callback is invoked # when we call setItem. def setSortMode(self, column, mode): """ Set the mode used to sort *column*. ============== ======================================================== **Sort Modes** value Compares item.value if available; falls back to text comparison. text Compares item.text() index Compares by the order in which items were inserted. ============== ======================================================== Added in version 0.9.9 """ for r in range(self.rowCount()): item = self.item(r, column) if hasattr(item, 'setSortMode'): item.setSortMode(mode) self.sortModes[column] = mode def sizeHint(self): # based on http://stackoverflow.com/a/7195443/54056 width = sum(self.columnWidth(i) for i in range(self.columnCount())) width += self.verticalHeader().sizeHint().width() width += self.verticalScrollBar().sizeHint().width() width += self.frameWidth() * 2 height = sum(self.rowHeight(i) for i in range(self.rowCount())) height += self.verticalHeader().sizeHint().height() height += self.horizontalScrollBar().sizeHint().height() return QtCore.QSize(width, height) def serialize(self, useSelection=False): """Convert entire table (or just selected area) into tab-separated text values""" if useSelection: selection = self.selectedRanges()[0] rows = list(range(selection.topRow(), selection.bottomRow() + 1)) columns = list(range(selection.leftColumn(), selection.rightColumn() + 1)) else: rows = list(range(self.rowCount())) columns = list(range(self.columnCount())) data = [] if self.horizontalHeadersSet: row = [] if self.verticalHeadersSet: row.append(asUnicode('')) for c in columns: row.append(asUnicode(self.horizontalHeaderItem(c).text())) data.append(row) for r in rows: row = [] if self.verticalHeadersSet: row.append(asUnicode(self.verticalHeaderItem(r).text())) for c in columns: item = self.item(r, c) if item is not None: row.append(asUnicode(item.value)) else: row.append(asUnicode('')) data.append(row) s = '' for row in data: s += ('\t'.join(row) + '\n') return s def copySel(self): """Copy selected data to clipboard.""" QtGui.QApplication.clipboard().setText(self.serialize(useSelection=True)) def copyAll(self): """Copy all data to clipboard.""" QtGui.QApplication.clipboard().setText(self.serialize(useSelection=False)) def saveSel(self): """Save selected data to file.""" self.save(self.serialize(useSelection=True)) def saveAll(self): """Save all data to file.""" self.save(self.serialize(useSelection=False)) def save(self, data): fileName = QtGui.QFileDialog.getSaveFileName(self, "Save As..", "", "Tab-separated values (*.tsv)") if isinstance(fileName, tuple): fileName = fileName[0] # Qt4/5 API difference if fileName == '': return with open(fileName, 'w') as fd: fd.write(data) def contextMenuEvent(self, ev): self.contextMenu.popup(ev.globalPos()) def keyPressEvent(self, ev): if ev.key() == QtCore.Qt.Key_C and ev.modifiers() == QtCore.Qt.ControlModifier: ev.accept() self.copySel() else: QtGui.QTableWidget.keyPressEvent(self, ev) def handleItemChanged(self, item): item.itemChanged() class TableWidgetItem(QtGui.QTableWidgetItem): def __init__(self, val, index, format=None): QtGui.QTableWidgetItem.__init__(self, '') self._blockValueChange = False self._format = None self._defaultFormat = '%0.3g' self.sortMode = 'value' self.index = index flags = QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled self.setFlags(flags) self.setValue(val) self.setFormat(format) def setEditable(self, editable): """ Set whether this item is user-editable. """ if editable: self.setFlags(self.flags() | QtCore.Qt.ItemIsEditable) else: self.setFlags(self.flags() & ~QtCore.Qt.ItemIsEditable) def setSortMode(self, mode): """ Set the mode used to sort this item against others in its column. ============== ======================================================== **Sort Modes** value Compares item.value if available; falls back to text comparison. text Compares item.text() index Compares by the order in which items were inserted. ============== ======================================================== """ modes = ('value', 'text', 'index', None) if mode not in modes: raise ValueError('Sort mode must be one of %s' % str(modes)) self.sortMode = mode def setFormat(self, fmt): """Define the conversion from item value to displayed text. If a string is specified, it is used as a format string for converting float values (and all other types are converted using str). If a function is specified, it will be called with the item as its only argument and must return a string. Added in version 0.9.9. """ if fmt is not None and not isinstance(fmt, basestring) and not callable(fmt): raise ValueError("Format argument must string, callable, or None. (got %s)" % fmt) self._format = fmt self._updateText() def _updateText(self): self._blockValueChange = True try: self._text = self.format() self.setText(self._text) finally: self._blockValueChange = False def setValue(self, value): self.value = value self._updateText() def itemChanged(self): """Called when the data of this item has changed.""" if self.text() != self._text: self.textChanged() def textChanged(self): """Called when this item's text has changed for any reason.""" self._text = self.text() if self._blockValueChange: # text change was result of value or format change; do not # propagate. return try: self.value = type(self.value)(self.text()) except ValueError: self.value = str(self.text()) def format(self): if callable(self._format): return self._format(self) if isinstance(self.value, (float, np.floating)): if self._format is None: return self._defaultFormat % self.value else: return self._format % self.value else: return asUnicode(self.value) def __lt__(self, other): if self.sortMode == 'index' and hasattr(other, 'index'): return self.index < other.index if self.sortMode == 'value' and hasattr(other, 'value'): return self.value < other.value else: return self.text() < other.text() if __name__ == '__main__': app = QtGui.QApplication([]) win = QtGui.QMainWindow() t = TableWidget() win.setCentralWidget(t) win.resize(800,600) win.show() ll = [[1,2,3,4,5]] * 20 ld = [{'x': 1, 'y': 2, 'z': 3}] * 20 dl = {'x': list(range(20)), 'y': list(range(20)), 'z': list(range(20))} a = np.ones((20, 5)) ra = np.ones((20,), dtype=[('x', int), ('y', int), ('z', int)]) t.setData(ll) ma = metaarray.MetaArray(np.ones((20, 3)), info=[ {'values': np.linspace(1, 5, 20)}, {'cols': [ {'name': 'x'}, {'name': 'y'}, {'name': 'z'}, ]} ]) t.setData(ma)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/DataTreeWidget.py
.py
4,479
124
# -*- coding: utf-8 -*- from ..Qt import QtGui, QtCore from ..pgcollections import OrderedDict from .TableWidget import TableWidget from ..python2_3 import asUnicode import types, traceback import numpy as np try: import metaarray HAVE_METAARRAY = True except: HAVE_METAARRAY = False __all__ = ['DataTreeWidget'] class DataTreeWidget(QtGui.QTreeWidget): """ Widget for displaying hierarchical python data structures (eg, nested dicts, lists, and arrays) """ def __init__(self, parent=None, data=None): QtGui.QTreeWidget.__init__(self, parent) self.setVerticalScrollMode(self.ScrollPerPixel) self.setData(data) self.setColumnCount(3) self.setHeaderLabels(['key / index', 'type', 'value']) self.setAlternatingRowColors(True) def setData(self, data, hideRoot=False): """data should be a dictionary.""" self.clear() self.widgets = [] self.nodes = {} self.buildTree(data, self.invisibleRootItem(), hideRoot=hideRoot) self.expandToDepth(3) self.resizeColumnToContents(0) def buildTree(self, data, parent, name='', hideRoot=False, path=()): if hideRoot: node = parent else: node = QtGui.QTreeWidgetItem([name, "", ""]) parent.addChild(node) # record the path to the node so it can be retrieved later # (this is used by DiffTreeWidget) self.nodes[path] = node typeStr, desc, childs, widget = self.parse(data) node.setText(1, typeStr) node.setText(2, desc) # Truncate description and add text box if needed if len(desc) > 100: desc = desc[:97] + '...' if widget is None: widget = QtGui.QPlainTextEdit(asUnicode(data)) widget.setMaximumHeight(200) widget.setReadOnly(True) # Add widget to new subnode if widget is not None: self.widgets.append(widget) subnode = QtGui.QTreeWidgetItem(["", "", ""]) node.addChild(subnode) self.setItemWidget(subnode, 0, widget) self.setFirstItemColumnSpanned(subnode, True) # recurse to children for key, data in childs.items(): self.buildTree(data, node, asUnicode(key), path=path+(key,)) def parse(self, data): """ Given any python object, return: * type * a short string representation * a dict of sub-objects to be parsed * optional widget to display as sub-node """ # defaults for all objects typeStr = type(data).__name__ if typeStr == 'instance': typeStr += ": " + data.__class__.__name__ widget = None desc = "" childs = {} # type-specific changes if isinstance(data, dict): desc = "length=%d" % len(data) if isinstance(data, OrderedDict): childs = data else: childs = OrderedDict(sorted(data.items())) elif isinstance(data, (list, tuple)): desc = "length=%d" % len(data) childs = OrderedDict(enumerate(data)) elif HAVE_METAARRAY and (hasattr(data, 'implements') and data.implements('MetaArray')): childs = OrderedDict([ ('data', data.view(np.ndarray)), ('meta', data.infoCopy()) ]) elif isinstance(data, np.ndarray): desc = "shape=%s dtype=%s" % (data.shape, data.dtype) table = TableWidget() table.setData(data) table.setMaximumHeight(200) widget = table elif isinstance(data, types.TracebackType): ## convert traceback to a list of strings frames = list(map(str.strip, traceback.format_list(traceback.extract_tb(data)))) #childs = OrderedDict([ #(i, {'file': child[0], 'line': child[1], 'function': child[2], 'code': child[3]}) #for i, child in enumerate(frames)]) #childs = OrderedDict([(i, ch) for i,ch in enumerate(frames)]) widget = QtGui.QPlainTextEdit(asUnicode('\n'.join(frames))) widget.setMaximumHeight(200) widget.setReadOnly(True) else: desc = asUnicode(data) return typeStr, desc, childs, widget
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/GradientWidget.py
.py
2,901
75
# -*- coding: utf-8 -*- from ..Qt import QtGui, QtCore from .GraphicsView import GraphicsView from ..graphicsItems.GradientEditorItem import GradientEditorItem import weakref import numpy as np __all__ = ['GradientWidget'] class GradientWidget(GraphicsView): """ Widget displaying an editable color gradient. The user may add, move, recolor, or remove colors from the gradient. Additionally, a context menu allows the user to select from pre-defined gradients. """ sigGradientChanged = QtCore.Signal(object) sigGradientChangeFinished = QtCore.Signal(object) def __init__(self, parent=None, orientation='bottom', *args, **kargs): """ The *orientation* argument may be 'bottom', 'top', 'left', or 'right' indicating whether the gradient is displayed horizontally (top, bottom) or vertically (left, right) and on what side of the gradient the editable ticks will appear. All other arguments are passed to :func:`GradientEditorItem.__init__ <pyqtgraph.GradientEditorItem.__init__>`. Note: For convenience, this class wraps methods from :class:`GradientEditorItem <pyqtgraph.GradientEditorItem>`. """ GraphicsView.__init__(self, parent, useOpenGL=False, background=None) self.maxDim = 31 kargs['tickPen'] = 'k' self.item = GradientEditorItem(*args, **kargs) self.item.sigGradientChanged.connect(self.sigGradientChanged) self.item.sigGradientChangeFinished.connect(self.sigGradientChangeFinished) self.setCentralItem(self.item) self.setOrientation(orientation) self.setCacheMode(self.CacheNone) self.setRenderHints(QtGui.QPainter.Antialiasing | QtGui.QPainter.TextAntialiasing) self.setFrameStyle(QtGui.QFrame.NoFrame | QtGui.QFrame.Plain) #self.setBackgroundRole(QtGui.QPalette.NoRole) #self.setBackgroundBrush(QtGui.QBrush(QtCore.Qt.NoBrush)) #self.setAutoFillBackground(False) #self.setAttribute(QtCore.Qt.WA_PaintOnScreen, False) #self.setAttribute(QtCore.Qt.WA_OpaquePaintEvent, True) def setOrientation(self, ort): """Set the orientation of the widget. May be one of 'bottom', 'top', 'left', or 'right'.""" self.item.setOrientation(ort) self.orientation = ort self.setMaxDim() def setMaxDim(self, mx=None): if mx is None: mx = self.maxDim else: self.maxDim = mx if self.orientation in ['bottom', 'top']: self.setFixedHeight(mx) self.setMaximumWidth(16777215) else: self.setFixedWidth(mx) self.setMaximumHeight(16777215) def __getattr__(self, attr): ### wrap methods from GradientEditorItem return getattr(self.item, attr)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/VerticalLabel.py
.py
3,360
99
# -*- coding: utf-8 -*- from ..Qt import QtGui, QtCore __all__ = ['VerticalLabel'] #class VerticalLabel(QtGui.QLabel): #def paintEvent(self, ev): #p = QtGui.QPainter(self) #p.rotate(-90) #self.hint = p.drawText(QtCore.QRect(-self.height(), 0, self.height(), self.width()), QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter, self.text()) #p.end() #self.setMinimumWidth(self.hint.height()) #self.setMinimumHeight(self.hint.width()) #def sizeHint(self): #if hasattr(self, 'hint'): #return QtCore.QSize(self.hint.height(), self.hint.width()) #else: #return QtCore.QSize(16, 50) class VerticalLabel(QtGui.QLabel): def __init__(self, text, orientation='vertical', forceWidth=True): QtGui.QLabel.__init__(self, text) self.forceWidth = forceWidth self.orientation = None self.setOrientation(orientation) def setOrientation(self, o): if self.orientation == o: return self.orientation = o self.update() self.updateGeometry() def paintEvent(self, ev): p = QtGui.QPainter(self) #p.setBrush(QtGui.QBrush(QtGui.QColor(100, 100, 200))) #p.setPen(QtGui.QPen(QtGui.QColor(50, 50, 100))) #p.drawRect(self.rect().adjusted(0, 0, -1, -1)) #p.setPen(QtGui.QPen(QtGui.QColor(255, 255, 255))) if self.orientation == 'vertical': p.rotate(-90) rgn = QtCore.QRect(-self.height(), 0, self.height(), self.width()) else: rgn = self.contentsRect() align = self.alignment() #align = QtCore.Qt.AlignTop|QtCore.Qt.AlignHCenter self.hint = p.drawText(rgn, align, self.text()) p.end() if self.orientation == 'vertical': self.setMaximumWidth(self.hint.height()) self.setMinimumWidth(0) self.setMaximumHeight(16777215) if self.forceWidth: self.setMinimumHeight(self.hint.width()) else: self.setMinimumHeight(0) else: self.setMaximumHeight(self.hint.height()) self.setMinimumHeight(0) self.setMaximumWidth(16777215) if self.forceWidth: self.setMinimumWidth(self.hint.width()) else: self.setMinimumWidth(0) def sizeHint(self): if self.orientation == 'vertical': if hasattr(self, 'hint'): return QtCore.QSize(self.hint.height(), self.hint.width()) else: return QtCore.QSize(19, 50) else: if hasattr(self, 'hint'): return QtCore.QSize(self.hint.width(), self.hint.height()) else: return QtCore.QSize(50, 19) if __name__ == '__main__': app = QtGui.QApplication([]) win = QtGui.QMainWindow() w = QtGui.QWidget() l = QtGui.QGridLayout() w.setLayout(l) l1 = VerticalLabel("text 1", orientation='horizontal') l2 = VerticalLabel("text 2") l3 = VerticalLabel("text 3") l4 = VerticalLabel("text 4", orientation='horizontal') l.addWidget(l1, 0, 0) l.addWidget(l2, 1, 1) l.addWidget(l3, 2, 2) l.addWidget(l4, 3, 3) win.setCentralWidget(w) win.show()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/__init__.py
.py
0
0
null
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/DiffTreeWidget.py
.py
5,928
164
# -*- coding: utf-8 -*- from ..Qt import QtGui, QtCore from ..pgcollections import OrderedDict from .DataTreeWidget import DataTreeWidget from .. import functions as fn import types, traceback import numpy as np __all__ = ['DiffTreeWidget'] class DiffTreeWidget(QtGui.QWidget): """ Widget for displaying differences between hierarchical python data structures (eg, nested dicts, lists, and arrays) """ def __init__(self, parent=None, a=None, b=None): QtGui.QWidget.__init__(self, parent) self.layout = QtGui.QHBoxLayout() self.setLayout(self.layout) self.trees = [DataTreeWidget(self), DataTreeWidget(self)] for t in self.trees: self.layout.addWidget(t) if a is not None: self.setData(a, b) def setData(self, a, b): """ Set the data to be compared in this widget. """ self.data = (a, b) self.trees[0].setData(a) self.trees[1].setData(b) return self.compare(a, b) def compare(self, a, b, path=()): """ Compare data structure *a* to structure *b*. Return True if the objects match completely. Otherwise, return a structure that describes the differences: { 'type': bool 'len': bool, 'str': bool, 'shape': bool, 'dtype': bool, 'mask': array, } """ bad = (255, 200, 200) diff = [] # generate typestr, desc, childs for each object typeA, descA, childsA, _ = self.trees[0].parse(a) typeB, descB, childsB, _ = self.trees[1].parse(b) if typeA != typeB: self.setColor(path, 1, bad) if descA != descB: self.setColor(path, 2, bad) if isinstance(a, dict) and isinstance(b, dict): keysA = set(a.keys()) keysB = set(b.keys()) for key in keysA - keysB: self.setColor(path+(key,), 0, bad, tree=0) for key in keysB - keysA: self.setColor(path+(key,), 0, bad, tree=1) for key in keysA & keysB: self.compare(a[key], b[key], path+(key,)) elif isinstance(a, (list, tuple)) and isinstance(b, (list, tuple)): for i in range(max(len(a), len(b))): if len(a) <= i: self.setColor(path+(i,), 0, bad, tree=1) elif len(b) <= i: self.setColor(path+(i,), 0, bad, tree=0) else: self.compare(a[i], b[i], path+(i,)) elif isinstance(a, np.ndarray) and isinstance(b, np.ndarray) and a.shape == b.shape: tableNodes = [tree.nodes[path].child(0) for tree in self.trees] if a.dtype.fields is None and b.dtype.fields is None: eq = self.compareArrays(a, b) if not np.all(eq): for n in tableNodes: n.setBackground(0, fn.mkBrush(bad)) #for i in np.argwhere(~eq): else: if a.dtype == b.dtype: for i,k in enumerate(a.dtype.fields.keys()): eq = self.compareArrays(a[k], b[k]) if not np.all(eq): for n in tableNodes: n.setBackground(0, fn.mkBrush(bad)) #for j in np.argwhere(~eq): # dict: compare keys, then values where keys match # list: # array: compare elementwise for same shape def compareArrays(self, a, b): intnan = -9223372036854775808 # happens when np.nan is cast to int anans = np.isnan(a) | (a == intnan) bnans = np.isnan(b) | (b == intnan) eq = anans == bnans mask = ~anans eq[mask] = np.allclose(a[mask], b[mask]) return eq def setColor(self, path, column, color, tree=None): brush = fn.mkBrush(color) # Color only one tree if specified. if tree is None: trees = self.trees else: trees = [self.trees[tree]] for tree in trees: item = tree.nodes[path] item.setBackground(column, brush) def _compare(self, a, b): """ Compare data structure *a* to structure *b*. """ # Check test structures are the same assert type(info) is type(expect) if hasattr(info, '__len__'): assert len(info) == len(expect) if isinstance(info, dict): for k in info: assert k in expect for k in expect: assert k in info self.compare_results(info[k], expect[k]) elif isinstance(info, list): for i in range(len(info)): self.compare_results(info[i], expect[i]) elif isinstance(info, np.ndarray): assert info.shape == expect.shape assert info.dtype == expect.dtype if info.dtype.fields is None: intnan = -9223372036854775808 # happens when np.nan is cast to int inans = np.isnan(info) | (info == intnan) enans = np.isnan(expect) | (expect == intnan) assert np.all(inans == enans) mask = ~inans assert np.allclose(info[mask], expect[mask]) else: for k in info.dtype.fields.keys(): self.compare_results(info[k], expect[k]) else: try: assert info == expect except Exception: raise NotImplementedError("Cannot compare objects of type %s" % type(info))
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/CheckTable.py
.py
3,361
94
# -*- coding: utf-8 -*- from ..Qt import QtGui, QtCore from . import VerticalLabel __all__ = ['CheckTable'] class CheckTable(QtGui.QWidget): sigStateChanged = QtCore.Signal(object, object, object) # (row, col, state) def __init__(self, columns): QtGui.QWidget.__init__(self) self.layout = QtGui.QGridLayout() self.layout.setSpacing(0) self.setLayout(self.layout) self.headers = [] self.columns = columns col = 1 for c in columns: label = VerticalLabel.VerticalLabel(c, orientation='vertical') self.headers.append(label) self.layout.addWidget(label, 0, col) col += 1 self.rowNames = [] self.rowWidgets = [] self.oldRows = {} ## remember settings from removed rows; reapply if they reappear. def updateRows(self, rows): for r in self.rowNames[:]: if r not in rows: self.removeRow(r) for r in rows: if r not in self.rowNames: self.addRow(r) def addRow(self, name): label = QtGui.QLabel(name) row = len(self.rowNames)+1 self.layout.addWidget(label, row, 0) checks = [] col = 1 for c in self.columns: check = QtGui.QCheckBox('') check.col = c check.row = name self.layout.addWidget(check, row, col) checks.append(check) if name in self.oldRows: check.setChecked(self.oldRows[name][col]) col += 1 #QtCore.QObject.connect(check, QtCore.SIGNAL('stateChanged(int)'), self.checkChanged) check.stateChanged.connect(self.checkChanged) self.rowNames.append(name) self.rowWidgets.append([label] + checks) def removeRow(self, name): row = self.rowNames.index(name) self.oldRows[name] = self.saveState()['rows'][row] ## save for later self.rowNames.pop(row) for w in self.rowWidgets[row]: w.setParent(None) #QtCore.QObject.disconnect(w, QtCore.SIGNAL('stateChanged(int)'), self.checkChanged) if isinstance(w, QtGui.QCheckBox): w.stateChanged.disconnect(self.checkChanged) self.rowWidgets.pop(row) for i in range(row, len(self.rowNames)): widgets = self.rowWidgets[i] for j in range(len(widgets)): widgets[j].setParent(None) self.layout.addWidget(widgets[j], i+1, j) def checkChanged(self, state): check = QtCore.QObject.sender(self) #self.emit(QtCore.SIGNAL('stateChanged'), check.row, check.col, state) self.sigStateChanged.emit(check.row, check.col, state) def saveState(self): rows = [] for i in range(len(self.rowNames)): row = [self.rowNames[i]] + [c.isChecked() for c in self.rowWidgets[i][1:]] rows.append(row) return {'cols': self.columns, 'rows': rows} def restoreState(self, state): rows = [r[0] for r in state['rows']] self.updateRows(rows) for r in state['rows']: rowNum = self.rowNames.index(r[0]) for i in range(1, len(r)): self.rowWidgets[rowNum][i].setChecked(r[i])
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/PathButton.py
.py
1,606
52
from ..Qt import QtGui, QtCore from .. import functions as fn __all__ = ['PathButton'] class PathButton(QtGui.QPushButton): """Simple PushButton extension that paints a QPainterPath centered on its face. """ def __init__(self, parent=None, path=None, pen='default', brush=None, size=(30,30), margin=7): QtGui.QPushButton.__init__(self, parent) self.margin = margin self.path = None if pen == 'default': pen = 'k' self.setPen(pen) self.setBrush(brush) if path is not None: self.setPath(path) if size is not None: self.setFixedWidth(size[0]) self.setFixedHeight(size[1]) def setBrush(self, brush): self.brush = fn.mkBrush(brush) def setPen(self, *args, **kwargs): self.pen = fn.mkPen(*args, **kwargs) def setPath(self, path): self.path = path self.update() def paintEvent(self, ev): QtGui.QPushButton.paintEvent(self, ev) margin = self.margin geom = QtCore.QRectF(0, 0, self.width(), self.height()).adjusted(margin, margin, -margin, -margin) rect = self.path.boundingRect() scale = min(geom.width() / float(rect.width()), geom.height() / float(rect.height())) p = QtGui.QPainter(self) p.setRenderHint(p.Antialiasing) p.translate(geom.center()) p.scale(scale, scale) p.translate(-rect.center()) p.setPen(self.pen) p.setBrush(self.brush) p.drawPath(self.path) p.end()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/ColorButton.py
.py
3,755
92
# -*- coding: utf-8 -*- from ..Qt import QtGui, QtCore from .. import functions as functions __all__ = ['ColorButton'] class ColorButton(QtGui.QPushButton): """ **Bases:** QtGui.QPushButton Button displaying a color and allowing the user to select a new color. ====================== ============================================================ **Signals:** sigColorChanging(self) emitted whenever a new color is picked in the color dialog sigColorChanged(self) emitted when the selected color is accepted (user clicks OK) ====================== ============================================================ """ sigColorChanging = QtCore.Signal(object) ## emitted whenever a new color is picked in the color dialog sigColorChanged = QtCore.Signal(object) ## emitted when the selected color is accepted (user clicks OK) def __init__(self, parent=None, color=(128,128,128)): QtGui.QPushButton.__init__(self, parent) self.setColor(color) self.colorDialog = QtGui.QColorDialog() self.colorDialog.setOption(QtGui.QColorDialog.ShowAlphaChannel, True) self.colorDialog.setOption(QtGui.QColorDialog.DontUseNativeDialog, True) self.colorDialog.currentColorChanged.connect(self.dialogColorChanged) self.colorDialog.rejected.connect(self.colorRejected) self.colorDialog.colorSelected.connect(self.colorSelected) #QtCore.QObject.connect(self.colorDialog, QtCore.SIGNAL('currentColorChanged(const QColor&)'), self.currentColorChanged) #QtCore.QObject.connect(self.colorDialog, QtCore.SIGNAL('rejected()'), self.currentColorRejected) self.clicked.connect(self.selectColor) self.setMinimumHeight(15) self.setMinimumWidth(15) def paintEvent(self, ev): QtGui.QPushButton.paintEvent(self, ev) p = QtGui.QPainter(self) rect = self.rect().adjusted(6, 6, -6, -6) ## draw white base, then texture for indicating transparency, then actual color p.setBrush(functions.mkBrush('w')) p.drawRect(rect) p.setBrush(QtGui.QBrush(QtCore.Qt.DiagCrossPattern)) p.drawRect(rect) p.setBrush(functions.mkBrush(self._color)) p.drawRect(rect) p.end() def setColor(self, color, finished=True): """Sets the button's color and emits both sigColorChanged and sigColorChanging.""" self._color = functions.mkColor(color) self.update() if finished: self.sigColorChanged.emit(self) else: self.sigColorChanging.emit(self) def selectColor(self): self.origColor = self.color() self.colorDialog.setCurrentColor(self.color()) self.colorDialog.open() def dialogColorChanged(self, color): if color.isValid(): self.setColor(color, finished=False) def colorRejected(self): self.setColor(self.origColor, finished=False) def colorSelected(self, color): self.setColor(self._color, finished=True) def saveState(self): return functions.colorTuple(self._color) def restoreState(self, state): self.setColor(state) def color(self, mode='qcolor'): color = functions.mkColor(self._color) if mode == 'qcolor': return color elif mode == 'byte': return (color.red(), color.green(), color.blue(), color.alpha()) elif mode == 'float': return (color.red()/255., color.green()/255., color.blue()/255., color.alpha()/255.) def widgetGroupInterface(self): return (self.sigColorChanged, ColorButton.saveState, ColorButton.restoreState)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/ProgressDialog.py
.py
9,297
263
# -*- coding: utf-8 -*- from ..Qt import QtGui, QtCore __all__ = ['ProgressDialog'] class ProgressDialog(QtGui.QProgressDialog): """ Extends QProgressDialog: * Adds context management so the dialog may be used in `with` statements * Allows nesting multiple progress dialogs Example:: with ProgressDialog("Processing..", minVal, maxVal) as dlg: # do stuff dlg.setValue(i) ## could also use dlg += 1 if dlg.wasCanceled(): raise Exception("Processing canceled by user") """ allDialogs = [] def __init__(self, labelText, minimum=0, maximum=100, cancelText='Cancel', parent=None, wait=250, busyCursor=False, disable=False, nested=False): """ ============== ================================================================ **Arguments:** labelText (required) cancelText Text to display on cancel button, or None to disable it. minimum maximum parent wait Length of time (im ms) to wait before displaying dialog busyCursor If True, show busy cursor until dialog finishes disable If True, the progress dialog will not be displayed and calls to wasCanceled() will always return False. If ProgressDialog is entered from a non-gui thread, it will always be disabled. nested (bool) If True, then this progress bar will be displayed inside any pre-existing progress dialogs that also allow nesting. ============== ================================================================ """ # attributes used for nesting dialogs self.nestedLayout = None self._nestableWidgets = None self._nestingReady = False self._topDialog = None self._subBars = [] self.nested = nested isGuiThread = QtCore.QThread.currentThread() == QtCore.QCoreApplication.instance().thread() self.disabled = disable or (not isGuiThread) if self.disabled: return noCancel = False if cancelText is None: cancelText = '' noCancel = True self.busyCursor = busyCursor QtGui.QProgressDialog.__init__(self, labelText, cancelText, minimum, maximum, parent) # If this will be a nested dialog, then we ignore the wait time if nested is True and len(ProgressDialog.allDialogs) > 0: self.setMinimumDuration(2**30) else: self.setMinimumDuration(wait) self.setWindowModality(QtCore.Qt.WindowModal) self.setValue(self.minimum()) if noCancel: self.setCancelButton(None) def __enter__(self): if self.disabled: return self if self.busyCursor: QtGui.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor)) if self.nested and len(ProgressDialog.allDialogs) > 0: topDialog = ProgressDialog.allDialogs[0] topDialog._addSubDialog(self) self._topDialog = topDialog topDialog.canceled.connect(self.cancel) ProgressDialog.allDialogs.append(self) return self def __exit__(self, exType, exValue, exTrace): if self.disabled: return if self.busyCursor: QtGui.QApplication.restoreOverrideCursor() if self._topDialog is not None: self._topDialog._removeSubDialog(self) ProgressDialog.allDialogs.pop(-1) self.setValue(self.maximum()) def __iadd__(self, val): """Use inplace-addition operator for easy incrementing.""" if self.disabled: return self self.setValue(self.value()+val) return self def _addSubDialog(self, dlg): # insert widgets from another dialog into this one. # set a new layout and arrange children into it (if needed). self._prepareNesting() bar, btn = dlg._extractWidgets() # where should we insert this widget? Find the first slot with a # "removed" widget (that was left as a placeholder) inserted = False for i,bar2 in enumerate(self._subBars): if bar2.hidden: self._subBars.pop(i) bar2.hide() bar2.setParent(None) self._subBars.insert(i, bar) inserted = True break if not inserted: self._subBars.append(bar) # reset the layout while self.nestedLayout.count() > 0: self.nestedLayout.takeAt(0) for b in self._subBars: self.nestedLayout.addWidget(b) def _removeSubDialog(self, dlg): # don't remove the widget just yet; instead we hide it and leave it in # as a placeholder. bar, btn = dlg._extractWidgets() bar.hide() def _prepareNesting(self): # extract all child widgets and place into a new layout that we can add to if self._nestingReady is False: # top layout contains progress bars + cancel button at the bottom self._topLayout = QtGui.QGridLayout() self.setLayout(self._topLayout) self._topLayout.setContentsMargins(0, 0, 0, 0) # A vbox to contain all progress bars self.nestedVBox = QtGui.QWidget() self._topLayout.addWidget(self.nestedVBox, 0, 0, 1, 2) self.nestedLayout = QtGui.QVBoxLayout() self.nestedVBox.setLayout(self.nestedLayout) # re-insert all widgets bar, btn = self._extractWidgets() self.nestedLayout.addWidget(bar) self._subBars.append(bar) self._topLayout.addWidget(btn, 1, 1, 1, 1) self._topLayout.setColumnStretch(0, 100) self._topLayout.setColumnStretch(1, 1) self._topLayout.setRowStretch(0, 100) self._topLayout.setRowStretch(1, 1) self._nestingReady = True def _extractWidgets(self): # return: # 1. a single widget containing the label and progress bar # 2. the cancel button if self._nestableWidgets is None: widgets = [ch for ch in self.children() if isinstance(ch, QtGui.QWidget)] label = [ch for ch in self.children() if isinstance(ch, QtGui.QLabel)][0] bar = [ch for ch in self.children() if isinstance(ch, QtGui.QProgressBar)][0] btn = [ch for ch in self.children() if isinstance(ch, QtGui.QPushButton)][0] sw = ProgressWidget(label, bar) self._nestableWidgets = (sw, btn) return self._nestableWidgets def resizeEvent(self, ev): if self._nestingReady: # don't let progress dialog manage widgets anymore. return return QtGui.QProgressDialog.resizeEvent(self, ev) ## wrap all other functions to make sure they aren't being called from non-gui threads def setValue(self, val): if self.disabled: return QtGui.QProgressDialog.setValue(self, val) # Qt docs say this should happen automatically, but that doesn't seem # to be the case. if self.windowModality() == QtCore.Qt.WindowModal: QtGui.QApplication.processEvents() def setLabelText(self, val): if self.disabled: return QtGui.QProgressDialog.setLabelText(self, val) def setMaximum(self, val): if self.disabled: return QtGui.QProgressDialog.setMaximum(self, val) def setMinimum(self, val): if self.disabled: return QtGui.QProgressDialog.setMinimum(self, val) def wasCanceled(self): if self.disabled: return False return QtGui.QProgressDialog.wasCanceled(self) def maximum(self): if self.disabled: return 0 return QtGui.QProgressDialog.maximum(self) def minimum(self): if self.disabled: return 0 return QtGui.QProgressDialog.minimum(self) class ProgressWidget(QtGui.QWidget): """Container for a label + progress bar that also allows its child widgets to be hidden without changing size. """ def __init__(self, label, bar): QtGui.QWidget.__init__(self) self.hidden = False self.layout = QtGui.QVBoxLayout() self.setLayout(self.layout) self.label = label self.bar = bar self.layout.addWidget(label) self.layout.addWidget(bar) def eventFilter(self, obj, ev): return ev.type() == QtCore.QEvent.Paint def hide(self): # hide label and bar, but continue occupying the same space in the layout for widget in (self.label, self.bar): widget.installEventFilter(self) widget.update() self.hidden = True
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/TreeWidget.py
.py
14,366
397
# -*- coding: utf-8 -*- from ..Qt import QtGui, QtCore from weakref import * __all__ = ['TreeWidget', 'TreeWidgetItem'] class TreeWidget(QtGui.QTreeWidget): """Extends QTreeWidget to allow internal drag/drop with widgets in the tree. Also maintains the expanded state of subtrees as they are moved. This class demonstrates the absurd lengths one must go to to make drag/drop work.""" sigItemMoved = QtCore.Signal(object, object, object) # (item, parent, index) sigItemCheckStateChanged = QtCore.Signal(object, object) sigItemTextChanged = QtCore.Signal(object, object) sigColumnCountChanged = QtCore.Signal(object, object) # self, count def __init__(self, parent=None): QtGui.QTreeWidget.__init__(self, parent) # wrap this item so that we can propagate tree change information # to children. self._invRootItem = InvisibleRootItem(QtGui.QTreeWidget.invisibleRootItem(self)) self.setAcceptDrops(True) self.setDragEnabled(True) self.setEditTriggers(QtGui.QAbstractItemView.EditKeyPressed|QtGui.QAbstractItemView.SelectedClicked) self.placeholders = [] self.childNestingLimit = None self.itemClicked.connect(self._itemClicked) def setItemWidget(self, item, col, wid): """ Overrides QTreeWidget.setItemWidget such that widgets are added inside an invisible wrapper widget. This makes it possible to move the item in and out of the tree without its widgets being automatically deleted. """ w = QtGui.QWidget() ## foster parent / surrogate child widget l = QtGui.QVBoxLayout() l.setContentsMargins(0,0,0,0) w.setLayout(l) w.setSizePolicy(wid.sizePolicy()) w.setMinimumHeight(wid.minimumHeight()) w.setMinimumWidth(wid.minimumWidth()) l.addWidget(wid) w.realChild = wid self.placeholders.append(w) QtGui.QTreeWidget.setItemWidget(self, item, col, w) def itemWidget(self, item, col): w = QtGui.QTreeWidget.itemWidget(self, item, col) if w is not None and hasattr(w, 'realChild'): w = w.realChild return w def dropMimeData(self, parent, index, data, action): item = self.currentItem() p = parent #print "drop", item, "->", parent, index while True: if p is None: break if p is item: return False #raise Exception("Can not move item into itself.") p = p.parent() if not self.itemMoving(item, parent, index): return False currentParent = item.parent() if currentParent is None: currentParent = self.invisibleRootItem() if parent is None: parent = self.invisibleRootItem() if currentParent is parent and index > parent.indexOfChild(item): index -= 1 self.prepareMove(item) currentParent.removeChild(item) #print " insert child to index", index parent.insertChild(index, item) ## index will not be correct self.setCurrentItem(item) self.recoverMove(item) #self.emit(QtCore.SIGNAL('itemMoved'), item, parent, index) self.sigItemMoved.emit(item, parent, index) return True def itemMoving(self, item, parent, index): """Called when item has been dropped elsewhere in the tree. Return True to accept the move, False to reject.""" return True def prepareMove(self, item): item.__widgets = [] item.__expanded = item.isExpanded() for i in range(self.columnCount()): w = self.itemWidget(item, i) item.__widgets.append(w) if w is None: continue w.setParent(None) for i in range(item.childCount()): self.prepareMove(item.child(i)) def recoverMove(self, item): for i in range(self.columnCount()): w = item.__widgets[i] if w is None: continue self.setItemWidget(item, i, w) for i in range(item.childCount()): self.recoverMove(item.child(i)) item.setExpanded(False) ## Items do not re-expand correctly unless they are collapsed first. QtGui.QApplication.instance().processEvents() item.setExpanded(item.__expanded) def collapseTree(self, item): item.setExpanded(False) for i in range(item.childCount()): self.collapseTree(item.child(i)) def removeTopLevelItem(self, item): for i in range(self.topLevelItemCount()): if self.topLevelItem(i) is item: self.takeTopLevelItem(i) return raise Exception("Item '%s' not in top-level items." % str(item)) def listAllItems(self, item=None): items = [] if item != None: items.append(item) else: item = self.invisibleRootItem() for cindex in range(item.childCount()): foundItems = self.listAllItems(item=item.child(cindex)) for f in foundItems: items.append(f) return items def dropEvent(self, ev): QtGui.QTreeWidget.dropEvent(self, ev) self.updateDropFlags() def updateDropFlags(self): ### intended to put a limit on how deep nests of children can go. ### self.childNestingLimit is upheld when moving items without children, but if the item being moved has children/grandchildren, the children/grandchildren ### can end up over the childNestingLimit. if self.childNestingLimit == None: pass # enable drops in all items (but only if there are drops that aren't enabled? for performance...) else: items = self.listAllItems() for item in items: parentCount = 0 p = item.parent() while p is not None: parentCount += 1 p = p.parent() if parentCount >= self.childNestingLimit: item.setFlags(item.flags() & (~QtCore.Qt.ItemIsDropEnabled)) else: item.setFlags(item.flags() | QtCore.Qt.ItemIsDropEnabled) @staticmethod def informTreeWidgetChange(item): if hasattr(item, 'treeWidgetChanged'): item.treeWidgetChanged() for i in range(item.childCount()): TreeWidget.informTreeWidgetChange(item.child(i)) def addTopLevelItem(self, item): QtGui.QTreeWidget.addTopLevelItem(self, item) self.informTreeWidgetChange(item) def addTopLevelItems(self, items): QtGui.QTreeWidget.addTopLevelItems(self, items) for item in items: self.informTreeWidgetChange(item) def insertTopLevelItem(self, index, item): QtGui.QTreeWidget.insertTopLevelItem(self, index, item) self.informTreeWidgetChange(item) def insertTopLevelItems(self, index, items): QtGui.QTreeWidget.insertTopLevelItems(self, index, items) for item in items: self.informTreeWidgetChange(item) def takeTopLevelItem(self, index): item = self.topLevelItem(index) if item is not None: self.prepareMove(item) item = QtGui.QTreeWidget.takeTopLevelItem(self, index) self.prepareMove(item) self.informTreeWidgetChange(item) return item def topLevelItems(self): return [self.topLevelItem(i) for i in range(self.topLevelItemCount())] def clear(self): items = self.topLevelItems() for item in items: self.prepareMove(item) QtGui.QTreeWidget.clear(self) ## Why do we want to do this? It causes RuntimeErrors. #for item in items: #self.informTreeWidgetChange(item) def invisibleRootItem(self): return self._invRootItem def itemFromIndex(self, index): """Return the item and column corresponding to a QModelIndex. """ col = index.column() rows = [] while index.row() >= 0: rows.insert(0, index.row()) index = index.parent() item = self.topLevelItem(rows[0]) for row in rows[1:]: item = item.child(row) return item, col def setColumnCount(self, c): QtGui.QTreeWidget.setColumnCount(self, c) self.sigColumnCountChanged.emit(self, c) def _itemClicked(self, item, col): if hasattr(item, 'itemClicked'): item.itemClicked(col) class TreeWidgetItem(QtGui.QTreeWidgetItem): """ TreeWidgetItem that keeps track of its own widgets and expansion state. * Widgets may be added to columns before the item is added to a tree. * Expanded state may be set before item is added to a tree. * Adds setCheked and isChecked methods. * Adds addChildren, insertChildren, and takeChildren methods. """ def __init__(self, *args): QtGui.QTreeWidgetItem.__init__(self, *args) self._widgets = {} # col: widget self._tree = None self._expanded = False def setChecked(self, column, checked): self.setCheckState(column, QtCore.Qt.Checked if checked else QtCore.Qt.Unchecked) def isChecked(self, col): return self.checkState(col) == QtCore.Qt.Checked def setExpanded(self, exp): self._expanded = exp QtGui.QTreeWidgetItem.setExpanded(self, exp) def isExpanded(self): return self._expanded def setWidget(self, column, widget): if column in self._widgets: self.removeWidget(column) self._widgets[column] = widget tree = self.treeWidget() if tree is None: return else: tree.setItemWidget(self, column, widget) def removeWidget(self, column): del self._widgets[column] tree = self.treeWidget() if tree is None: return tree.removeItemWidget(self, column) def treeWidgetChanged(self): tree = self.treeWidget() if self._tree is tree: return self._tree = self.treeWidget() if tree is None: return for col, widget in self._widgets.items(): tree.setItemWidget(self, col, widget) QtGui.QTreeWidgetItem.setExpanded(self, self._expanded) def childItems(self): return [self.child(i) for i in range(self.childCount())] def addChild(self, child): QtGui.QTreeWidgetItem.addChild(self, child) TreeWidget.informTreeWidgetChange(child) def addChildren(self, childs): QtGui.QTreeWidgetItem.addChildren(self, childs) for child in childs: TreeWidget.informTreeWidgetChange(child) def insertChild(self, index, child): QtGui.QTreeWidgetItem.insertChild(self, index, child) TreeWidget.informTreeWidgetChange(child) def insertChildren(self, index, childs): QtGui.QTreeWidgetItem.addChildren(self, index, childs) for child in childs: TreeWidget.informTreeWidgetChange(child) def removeChild(self, child): QtGui.QTreeWidgetItem.removeChild(self, child) TreeWidget.informTreeWidgetChange(child) def takeChild(self, index): child = QtGui.QTreeWidgetItem.takeChild(self, index) TreeWidget.informTreeWidgetChange(child) return child def takeChildren(self): childs = QtGui.QTreeWidgetItem.takeChildren(self) for child in childs: TreeWidget.informTreeWidgetChange(child) return childs def setData(self, column, role, value): # credit: ekhumoro # http://stackoverflow.com/questions/13662020/how-to-implement-itemchecked-and-itemunchecked-signals-for-qtreewidget-in-pyqt4 checkstate = self.checkState(column) text = self.text(column) QtGui.QTreeWidgetItem.setData(self, column, role, value) treewidget = self.treeWidget() if treewidget is None: return if (role == QtCore.Qt.CheckStateRole and checkstate != self.checkState(column)): treewidget.sigItemCheckStateChanged.emit(self, column) elif (role in (QtCore.Qt.DisplayRole, QtCore.Qt.EditRole) and text != self.text(column)): treewidget.sigItemTextChanged.emit(self, column) def itemClicked(self, col): """Called when this item is clicked on. Override this method to react to user clicks. """ class InvisibleRootItem(object): """Wrapper around a TreeWidget's invisible root item that calls TreeWidget.informTreeWidgetChange when child items are added/removed. """ def __init__(self, item): self._real_item = item def addChild(self, child): self._real_item.addChild(child) TreeWidget.informTreeWidgetChange(child) def addChildren(self, childs): self._real_item.addChildren(childs) for child in childs: TreeWidget.informTreeWidgetChange(child) def insertChild(self, index, child): self._real_item.insertChild(index, child) TreeWidget.informTreeWidgetChange(child) def insertChildren(self, index, childs): self._real_item.addChildren(index, childs) for child in childs: TreeWidget.informTreeWidgetChange(child) def removeChild(self, child): self._real_item.removeChild(child) TreeWidget.informTreeWidgetChange(child) def takeChild(self, index): child = self._real_item.takeChild(index) TreeWidget.informTreeWidgetChange(child) return child def takeChildren(self): childs = self._real_item.takeChildren() for child in childs: TreeWidget.informTreeWidgetChange(child) return childs def __getattr__(self, attr): return getattr(self._real_item, attr)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/FeedbackButton.py
.py
6,429
163
# -*- coding: utf-8 -*- from ..Qt import QtCore, QtGui __all__ = ['FeedbackButton'] class FeedbackButton(QtGui.QPushButton): """ QPushButton which flashes success/failure indication for slow or asynchronous procedures. """ ### For thread-safetyness sigCallSuccess = QtCore.Signal(object, object, object) sigCallFailure = QtCore.Signal(object, object, object) sigCallProcess = QtCore.Signal(object, object, object) sigReset = QtCore.Signal() def __init__(self, *args): QtGui.QPushButton.__init__(self, *args) self.origStyle = None self.origText = self.text() self.origStyle = self.styleSheet() self.origTip = self.toolTip() self.limitedTime = True #self.textTimer = QtCore.QTimer() #self.tipTimer = QtCore.QTimer() #self.textTimer.timeout.connect(self.setText) #self.tipTimer.timeout.connect(self.setToolTip) self.sigCallSuccess.connect(self.success) self.sigCallFailure.connect(self.failure) self.sigCallProcess.connect(self.processing) self.sigReset.connect(self.reset) def feedback(self, success, message=None, tip="", limitedTime=True): """Calls success() or failure(). If you want the message to be displayed until the user takes an action, set limitedTime to False. Then call self.reset() after the desired action.Threadsafe.""" if success: self.success(message, tip, limitedTime=limitedTime) else: self.failure(message, tip, limitedTime=limitedTime) def success(self, message=None, tip="", limitedTime=True): """Displays specified message on button and flashes button green to let user know action was successful. If you want the success to be displayed until the user takes an action, set limitedTime to False. Then call self.reset() after the desired action. Threadsafe.""" isGuiThread = QtCore.QThread.currentThread() == QtCore.QCoreApplication.instance().thread() if isGuiThread: self.setEnabled(True) #print "success" self.startBlink("#0F0", message, tip, limitedTime=limitedTime) else: self.sigCallSuccess.emit(message, tip, limitedTime) def failure(self, message=None, tip="", limitedTime=True): """Displays specified message on button and flashes button red to let user know there was an error. If you want the error to be displayed until the user takes an action, set limitedTime to False. Then call self.reset() after the desired action. Threadsafe. """ isGuiThread = QtCore.QThread.currentThread() == QtCore.QCoreApplication.instance().thread() if isGuiThread: self.setEnabled(True) #print "fail" self.startBlink("#F00", message, tip, limitedTime=limitedTime) else: self.sigCallFailure.emit(message, tip, limitedTime) def processing(self, message="Processing..", tip="", processEvents=True): """Displays specified message on button to let user know the action is in progress. Threadsafe. """ isGuiThread = QtCore.QThread.currentThread() == QtCore.QCoreApplication.instance().thread() if isGuiThread: self.setEnabled(False) self.setText(message, temporary=True) self.setToolTip(tip, temporary=True) if processEvents: QtGui.QApplication.processEvents() else: self.sigCallProcess.emit(message, tip, processEvents) def reset(self): """Resets the button to its original text and style. Threadsafe.""" isGuiThread = QtCore.QThread.currentThread() == QtCore.QCoreApplication.instance().thread() if isGuiThread: self.limitedTime = True self.setText() self.setToolTip() self.setStyleSheet() else: self.sigReset.emit() def startBlink(self, color, message=None, tip="", limitedTime=True): #if self.origStyle is None: #self.origStyle = self.styleSheet() #self.origText = self.text() self.setFixedHeight(self.height()) if message is not None: self.setText(message, temporary=True) self.setToolTip(tip, temporary=True) self.count = 0 #self.indStyle = "QPushButton {border: 2px solid %s; border-radius: 5px}" % color self.indStyle = "QPushButton {background-color: %s}" % color self.limitedTime = limitedTime self.borderOn() if limitedTime: QtCore.QTimer.singleShot(2000, self.setText) QtCore.QTimer.singleShot(10000, self.setToolTip) def borderOn(self): self.setStyleSheet(self.indStyle, temporary=True) if self.limitedTime or self.count <=2: QtCore.QTimer.singleShot(100, self.borderOff) def borderOff(self): self.setStyleSheet() self.count += 1 if self.count >= 2: if self.limitedTime: return QtCore.QTimer.singleShot(30, self.borderOn) def setText(self, text=None, temporary=False): if text is None: text = self.origText #print text QtGui.QPushButton.setText(self, text) if not temporary: self.origText = text def setToolTip(self, text=None, temporary=False): if text is None: text = self.origTip QtGui.QPushButton.setToolTip(self, text) if not temporary: self.origTip = text def setStyleSheet(self, style=None, temporary=False): if style is None: style = self.origStyle QtGui.QPushButton.setStyleSheet(self, style) if not temporary: self.origStyle = style if __name__ == '__main__': import time app = QtGui.QApplication([]) win = QtGui.QMainWindow() btn = FeedbackButton("Button") fail = True def click(): btn.processing("Hold on..") time.sleep(2.0) global fail fail = not fail if fail: btn.failure(message="FAIL.", tip="There was a failure. Get over it.") else: btn.success(message="Bueno!") btn.clicked.connect(click) win.setCentralWidget(btn) win.show()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/ColorMapWidget.py
.py
10,709
269
from ..Qt import QtGui, QtCore from .. import parametertree as ptree import numpy as np from ..pgcollections import OrderedDict from .. import functions as fn __all__ = ['ColorMapWidget'] class ColorMapWidget(ptree.ParameterTree): """ This class provides a widget allowing the user to customize color mapping for multi-column data. Given a list of field names, the user may specify multiple criteria for assigning colors to each record in a numpy record array. Multiple criteria are evaluated and combined into a single color for each record by user-defined compositing methods. For simpler color mapping using a single gradient editor, see :class:`GradientWidget <pyqtgraph.GradientWidget>` """ sigColorMapChanged = QtCore.Signal(object) def __init__(self, parent=None): ptree.ParameterTree.__init__(self, parent=parent, showHeader=False) self.params = ColorMapParameter() self.setParameters(self.params) self.params.sigTreeStateChanged.connect(self.mapChanged) ## wrap a couple methods self.setFields = self.params.setFields self.map = self.params.map def mapChanged(self): self.sigColorMapChanged.emit(self) def widgetGroupInterface(self): return (self.sigColorMapChanged, self.saveState, self.restoreState) def saveState(self): return self.params.saveState() def restoreState(self, state): self.params.restoreState(state) def addColorMap(self, name): """Add a new color mapping and return the created parameter. """ return self.params.addNew(name) class ColorMapParameter(ptree.types.GroupParameter): sigColorMapChanged = QtCore.Signal(object) def __init__(self): self.fields = {} ptree.types.GroupParameter.__init__(self, name='Color Map', addText='Add Mapping..', addList=[]) self.sigTreeStateChanged.connect(self.mapChanged) def mapChanged(self): self.sigColorMapChanged.emit(self) def addNew(self, name): fieldSpec = self.fields[name] mode = fieldSpec.get('mode', 'range') if mode == 'range': item = RangeColorMapItem(name, self.fields[name]) elif mode == 'enum': item = EnumColorMapItem(name, self.fields[name]) defaults = fieldSpec.get('defaults', {}) for k, v in defaults.items(): if k == 'colormap': item.setValue(v) else: item[k] = v self.addChild(item) return item def fieldNames(self): return self.fields.keys() def setFields(self, fields): """ Set the list of fields to be used by the mapper. The format of *fields* is:: [ (fieldName, {options}), ... ] ============== ============================================================ Field Options: mode Either 'range' or 'enum' (default is range). For 'range', The user may specify a gradient of colors to be applied linearly across a specific range of values. For 'enum', the user specifies a single color for each unique value (see *values* option). units String indicating the units of the data for this field. values List of unique values for which the user may assign a color when mode=='enum'. Optionally may specify a dict instead {value: name}. defaults Dict of default values to apply to color map items when they are created. Valid keys are 'colormap' to provide a default color map, or otherwise they a string or tuple indicating the parameter to be set, such as 'Operation' or ('Channels..', 'Red'). ============== ============================================================ """ self.fields = OrderedDict(fields) #self.fields = fields #self.fields.sort() names = self.fieldNames() self.setAddList(names) def map(self, data, mode='byte'): """ Return an array of colors corresponding to *data*. ============== ================================================================= **Arguments:** data A numpy record array where the fields in data.dtype match those defined by a prior call to setFields(). mode Either 'byte' or 'float'. For 'byte', the method returns an array of dtype ubyte with values scaled 0-255. For 'float', colors are returned as 0.0-1.0 float values. ============== ================================================================= """ if isinstance(data, dict): data = np.array([tuple(data.values())], dtype=[(k, float) for k in data.keys()]) colors = np.zeros((len(data),4)) for item in self.children(): if not item['Enabled']: continue chans = item.param('Channels..') mask = np.empty((len(data), 4), dtype=bool) for i,f in enumerate(['Red', 'Green', 'Blue', 'Alpha']): mask[:,i] = chans[f] colors2 = item.map(data) op = item['Operation'] if op == 'Add': colors[mask] = colors[mask] + colors2[mask] elif op == 'Multiply': colors[mask] *= colors2[mask] elif op == 'Overlay': a = colors2[:,3:4] c3 = colors * (1-a) + colors2 * a c3[:,3:4] = colors[:,3:4] + (1-colors[:,3:4]) * a colors = c3 elif op == 'Set': colors[mask] = colors2[mask] colors = np.clip(colors, 0, 1) if mode == 'byte': colors = (colors * 255).astype(np.ubyte) return colors def saveState(self): items = OrderedDict() for item in self: itemState = item.saveState(filter='user') itemState['field'] = item.fieldName items[item.name()] = itemState state = {'fields': self.fields, 'items': items} return state def restoreState(self, state): if 'fields' in state: self.setFields(state['fields']) for name, itemState in state['items'].items(): item = self.addNew(itemState['field']) item.restoreState(itemState) class RangeColorMapItem(ptree.types.SimpleParameter): mapType = 'range' def __init__(self, name, opts): self.fieldName = name units = opts.get('units', '') ptree.types.SimpleParameter.__init__(self, name=name, autoIncrementName=True, type='colormap', removable=True, renamable=True, children=[ #dict(name="Field", type='list', value=name, values=fields), dict(name='Min', type='float', value=0.0, suffix=units, siPrefix=True), dict(name='Max', type='float', value=1.0, suffix=units, siPrefix=True), dict(name='Operation', type='list', value='Overlay', values=['Overlay', 'Add', 'Multiply', 'Set']), dict(name='Channels..', type='group', expanded=False, children=[ dict(name='Red', type='bool', value=True), dict(name='Green', type='bool', value=True), dict(name='Blue', type='bool', value=True), dict(name='Alpha', type='bool', value=True), ]), dict(name='Enabled', type='bool', value=True), dict(name='NaN', type='color'), ]) def map(self, data): data = data[self.fieldName] scaled = np.clip((data-self['Min']) / (self['Max']-self['Min']), 0, 1) cmap = self.value() colors = cmap.map(scaled, mode='float') mask = np.isnan(data) | np.isinf(data) nanColor = self['NaN'] nanColor = (nanColor.red()/255., nanColor.green()/255., nanColor.blue()/255., nanColor.alpha()/255.) colors[mask] = nanColor return colors class EnumColorMapItem(ptree.types.GroupParameter): mapType = 'enum' def __init__(self, name, opts): self.fieldName = name vals = opts.get('values', []) if isinstance(vals, list): vals = OrderedDict([(v,str(v)) for v in vals]) childs = [{'name': v, 'type': 'color'} for v in vals] childs = [] for val,vname in vals.items(): ch = ptree.Parameter.create(name=vname, type='color') ch.maskValue = val childs.append(ch) ptree.types.GroupParameter.__init__(self, name=name, autoIncrementName=True, removable=True, renamable=True, children=[ dict(name='Values', type='group', children=childs), dict(name='Operation', type='list', value='Overlay', values=['Overlay', 'Add', 'Multiply', 'Set']), dict(name='Channels..', type='group', expanded=False, children=[ dict(name='Red', type='bool', value=True), dict(name='Green', type='bool', value=True), dict(name='Blue', type='bool', value=True), dict(name='Alpha', type='bool', value=True), ]), dict(name='Enabled', type='bool', value=True), dict(name='Default', type='color'), ]) def map(self, data): data = data[self.fieldName] colors = np.empty((len(data), 4)) default = np.array(fn.colorTuple(self['Default'])) / 255. colors[:] = default for v in self.param('Values'): mask = data == v.maskValue c = np.array(fn.colorTuple(v.value())) / 255. colors[mask] = c #scaled = np.clip((data-self['Min']) / (self['Max']-self['Min']), 0, 1) #cmap = self.value() #colors = cmap.map(scaled, mode='float') #mask = np.isnan(data) | np.isinf(data) #nanColor = self['NaN'] #nanColor = (nanColor.red()/255., nanColor.green()/255., nanColor.blue()/255., nanColor.alpha()/255.) #colors[mask] = nanColor return colors
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/BusyCursor.py
.py
1,218
35
from ..Qt import QtGui, QtCore, QT_LIB __all__ = ['BusyCursor'] class BusyCursor(object): """Class for displaying a busy mouse cursor during long operations. Usage:: with pyqtgraph.BusyCursor(): doLongOperation() May be nested. If called from a non-gui thread, then the cursor will not be affected. """ active = [] def __enter__(self): app = QtCore.QCoreApplication.instance() isGuiThread = (app is not None) and (QtCore.QThread.currentThread() == app.thread()) if isGuiThread and QtGui.QApplication.instance() is not None: if QT_LIB == 'PySide': # pass CursorShape rather than QCursor for PySide # see https://bugreports.qt.io/browse/PYSIDE-243 QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor) else: QtGui.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor)) BusyCursor.active.append(self) self._active = True else: self._active = False def __exit__(self, *args): if self._active: BusyCursor.active.pop(-1) QtGui.QApplication.restoreOverrideCursor()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/SpinBox.py
.py
24,520
608
# -*- coding: utf-8 -*- from math import log from decimal import Decimal as D ## Use decimal to avoid accumulating floating-point errors import decimal import weakref import re from ..Qt import QtGui, QtCore from ..python2_3 import asUnicode, basestring from ..SignalProxy import SignalProxy from .. import functions as fn __all__ = ['SpinBox'] class SpinBox(QtGui.QAbstractSpinBox): """ **Bases:** QtGui.QAbstractSpinBox Extension of QSpinBox widget for selection of a numerical value. Adds many extra features: * SI prefix notation (eg, automatically display "300 mV" instead of "0.003 V") * Float values with linear and decimal stepping (1-9, 10-90, 100-900, etc.) * Option for unbounded values * Delayed signals (allows multiple rapid changes with only one change signal) * Customizable text formatting ============================= ============================================== **Signals:** valueChanged(value) Same as QSpinBox; emitted every time the value has changed. sigValueChanged(self) Emitted when value has changed, but also combines multiple rapid changes into one signal (eg, when rolling the mouse wheel). sigValueChanging(self, value) Emitted immediately for all value changes. ============================= ============================================== """ ## There's a PyQt bug that leaks a reference to the ## QLineEdit returned from QAbstractSpinBox.lineEdit() ## This makes it possible to crash the entire program ## by making accesses to the LineEdit after the spinBox has been deleted. ## I have no idea how to get around this.. valueChanged = QtCore.Signal(object) # (value) for compatibility with QSpinBox sigValueChanged = QtCore.Signal(object) # (self) sigValueChanging = QtCore.Signal(object, object) # (self, value) sent immediately; no delay. def __init__(self, parent=None, value=0.0, **kwargs): """ ============== ======================================================================== **Arguments:** parent Sets the parent widget for this SpinBox (optional). Default is None. value (float/int) initial value. Default is 0.0. ============== ======================================================================== All keyword arguments are passed to :func:`setOpts`. """ QtGui.QAbstractSpinBox.__init__(self, parent) self.lastValEmitted = None self.lastText = '' self.textValid = True ## If false, we draw a red border self.setMinimumWidth(0) self._lastFontHeight = None self.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred) self.errorBox = ErrorBox(self.lineEdit()) self.opts = { 'bounds': [None, None], 'wrapping': False, ## normal arithmetic step 'step': D('0.01'), ## if 'dec' is false, the spinBox steps by 'step' every time ## if 'dec' is True, the step size is relative to the value ## 'step' needs to be an integral divisor of ten, ie 'step'*n=10 for some integer value of n (but only if dec is True) 'log': False, # deprecated 'dec': False, ## if true, does decimal stepping. ie from 1-10 it steps by 'step', from 10 to 100 it steps by 10*'step', etc. ## if true, minStep must be set in order to cross zero. 'int': False, ## Set True to force value to be integer 'suffix': '', 'siPrefix': False, ## Set to True to display numbers with SI prefix (ie, 100pA instead of 1e-10A) 'delay': 0.3, ## delay sending wheel update signals for 300ms 'delayUntilEditFinished': True, ## do not send signals until text editing has finished 'decimals': 6, 'format': asUnicode("{scaledValue:.{decimals}g}{suffixGap}{siPrefix}{suffix}"), 'regex': fn.FLOAT_REGEX, 'evalFunc': D, 'compactHeight': True, # manually remove extra margin outside of text } self.decOpts = ['step', 'minStep'] self.val = D(asUnicode(value)) ## Value is precise decimal. Ordinary math not allowed. self.updateText() self.skipValidate = False self.setCorrectionMode(self.CorrectToPreviousValue) self.setKeyboardTracking(False) self.proxy = SignalProxy(self.sigValueChanging, slot=self.delayedChange, delay=self.opts['delay']) self.setOpts(**kwargs) self._updateHeight() self.editingFinished.connect(self.editingFinishedEvent) def event(self, ev): ret = QtGui.QAbstractSpinBox.event(self, ev) if ev.type() == QtCore.QEvent.KeyPress and ev.key() == QtCore.Qt.Key_Return: ret = True ## For some reason, spinbox pretends to ignore return key press return ret def setOpts(self, **opts): """Set options affecting the behavior of the SpinBox. ============== ======================================================================== **Arguments:** bounds (min,max) Minimum and maximum values allowed in the SpinBox. Either may be None to leave the value unbounded. By default, values are unbounded. suffix (str) suffix (units) to display after the numerical value. By default, suffix is an empty str. siPrefix (bool) If True, then an SI prefix is automatically prepended to the units and the value is scaled accordingly. For example, if value=0.003 and suffix='V', then the SpinBox will display "300 mV" (but a call to SpinBox.value will still return 0.003). Default is False. step (float) The size of a single step. This is used when clicking the up/ down arrows, when rolling the mouse wheel, or when pressing keyboard arrows while the widget has keyboard focus. Note that the interpretation of this value is different when specifying the 'dec' argument. Default is 0.01. dec (bool) If True, then the step value will be adjusted to match the current size of the variable (for example, a value of 15 might step in increments of 1 whereas a value of 1500 would step in increments of 100). In this case, the 'step' argument is interpreted *relative* to the current value. The most common 'step' values when dec=True are 0.1, 0.2, 0.5, and 1.0. Default is False. minStep (float) When dec=True, this specifies the minimum allowable step size. int (bool) if True, the value is forced to integer type. Default is False wrapping (bool) If True and both bounds are not None, spin box has circular behavior. decimals (int) Number of decimal values to display. Default is 6. format (str) Formatting string used to generate the text shown. Formatting is done with ``str.format()`` and makes use of several arguments: * *value* - the unscaled value of the spin box * *suffix* - the suffix string * *scaledValue* - the scaled value to use when an SI prefix is present * *siPrefix* - the SI prefix string (if any), or an empty string if this feature has been disabled * *suffixGap* - a single space if a suffix is present, or an empty string otherwise. regex (str or RegexObject) Regular expression used to parse the spinbox text. May contain the following group names: * *number* - matches the numerical portion of the string (mandatory) * *siPrefix* - matches the SI prefix string * *suffix* - matches the suffix string Default is defined in ``pyqtgraph.functions.FLOAT_REGEX``. evalFunc (callable) Fucntion that converts a numerical string to a number, preferrably a Decimal instance. This function handles only the numerical of the text; it does not have access to the suffix or SI prefix. compactHeight (bool) if True, then set the maximum height of the spinbox based on the height of its font. This allows more compact packing on platforms with excessive widget decoration. Default is True. ============== ======================================================================== """ #print opts for k,v in opts.items(): if k == 'bounds': self.setMinimum(v[0], update=False) self.setMaximum(v[1], update=False) elif k == 'min': self.setMinimum(v, update=False) elif k == 'max': self.setMaximum(v, update=False) elif k in ['step', 'minStep']: self.opts[k] = D(asUnicode(v)) elif k == 'value': pass ## don't set value until bounds have been set elif k == 'format': self.opts[k] = asUnicode(v) elif k == 'regex' and isinstance(v, basestring): self.opts[k] = re.compile(v) elif k in self.opts: self.opts[k] = v else: raise TypeError("Invalid keyword argument '%s'." % k) if 'value' in opts: self.setValue(opts['value']) ## If bounds have changed, update value to match if 'bounds' in opts and 'value' not in opts: self.setValue() ## sanity checks: if self.opts['int']: if 'step' in opts: step = opts['step'] ## not necessary.. #if int(step) != step: #raise Exception('Integer SpinBox must have integer step size.') else: self.opts['step'] = int(self.opts['step']) if 'minStep' in opts: step = opts['minStep'] if int(step) != step: raise Exception('Integer SpinBox must have integer minStep size.') else: ms = int(self.opts.get('minStep', 1)) if ms < 1: ms = 1 self.opts['minStep'] = ms if 'delay' in opts: self.proxy.setDelay(opts['delay']) self.updateText() def setMaximum(self, m, update=True): """Set the maximum allowed value (or None for no limit)""" if m is not None: m = D(asUnicode(m)) self.opts['bounds'][1] = m if update: self.setValue() def setMinimum(self, m, update=True): """Set the minimum allowed value (or None for no limit)""" if m is not None: m = D(asUnicode(m)) self.opts['bounds'][0] = m if update: self.setValue() def wrapping(self): """Return whether or not the spin box is circular.""" return self.opts['wrapping'] def setWrapping(self, s): """Set whether spin box is circular. Both bounds must be set for this to have an effect.""" self.opts['wrapping'] = s def setPrefix(self, p): """Set a string prefix. """ self.setOpts(prefix=p) def setRange(self, r0, r1): """Set the upper and lower limits for values in the spinbox. """ self.setOpts(bounds = [r0,r1]) def setProperty(self, prop, val): ## for QSpinBox compatibility if prop == 'value': #if type(val) is QtCore.QVariant: #val = val.toDouble()[0] self.setValue(val) else: print("Warning: SpinBox.setProperty('%s', ..) not supported." % prop) def setSuffix(self, suf): """Set the string suffix appended to the spinbox text. """ self.setOpts(suffix=suf) def setSingleStep(self, step): """Set the step size used when responding to the mouse wheel, arrow buttons, or arrow keys. """ self.setOpts(step=step) def setDecimals(self, decimals): """Set the number of decimals to be displayed when formatting numeric values. """ self.setOpts(decimals=decimals) def selectNumber(self): """ Select the numerical portion of the text to allow quick editing by the user. """ le = self.lineEdit() text = asUnicode(le.text()) m = self.opts['regex'].match(text) if m is None: return s,e = m.start('number'), m.end('number') le.setSelection(s, e-s) def focusInEvent(self, ev): super(SpinBox, self).focusInEvent(ev) self.selectNumber() def value(self): """ Return the value of this SpinBox. """ if self.opts['int']: return int(self.val) else: return float(self.val) def setValue(self, value=None, update=True, delaySignal=False): """Set the value of this SpinBox. If the value is out of bounds, it will be clipped to the nearest boundary or wrapped if wrapping is enabled. If the spin is integer type, the value will be coerced to int. Returns the actual value set. If value is None, then the current value is used (this is for resetting the value after bounds, etc. have changed) """ if value is None: value = self.value() bounds = self.opts['bounds'] if None not in bounds and self.opts['wrapping'] is True: # Casting of Decimals to floats required to avoid unexpected behavior of remainder operator value = float(value) l, u = float(bounds[0]), float(bounds[1]) value = (value - l) % (u - l) + l else: if bounds[0] is not None and value < bounds[0]: value = bounds[0] if bounds[1] is not None and value > bounds[1]: value = bounds[1] if self.opts['int']: value = int(value) if not isinstance(value, D): value = D(asUnicode(value)) if value == self.val: return prev = self.val self.val = value if update: self.updateText(prev=prev) self.sigValueChanging.emit(self, float(self.val)) ## change will be emitted in 300ms if there are no subsequent changes. if not delaySignal: self.emitChanged() return value def emitChanged(self): self.lastValEmitted = self.val self.valueChanged.emit(float(self.val)) self.sigValueChanged.emit(self) def delayedChange(self): try: if self.val != self.lastValEmitted: self.emitChanged() except RuntimeError: pass ## This can happen if we try to handle a delayed signal after someone else has already deleted the underlying C++ object. def widgetGroupInterface(self): return (self.valueChanged, SpinBox.value, SpinBox.setValue) def sizeHint(self): return QtCore.QSize(120, 0) def stepEnabled(self): return self.StepUpEnabled | self.StepDownEnabled def stepBy(self, n): n = D(int(n)) ## n must be integral number of steps. s = [D(-1), D(1)][n >= 0] ## determine sign of step val = self.val for i in range(int(abs(n))): if self.opts['log']: raise Exception("Log mode no longer supported.") # step = abs(val) * self.opts['step'] # if 'minStep' in self.opts: # step = max(step, self.opts['minStep']) # val += step * s if self.opts['dec']: if val == 0: step = self.opts['minStep'] exp = None else: vs = [D(-1), D(1)][val >= 0] #exp = D(int(abs(val*(D('1.01')**(s*vs))).log10())) fudge = D('1.01')**(s*vs) ## fudge factor. at some places, the step size depends on the step sign. exp = abs(val * fudge).log10().quantize(1, decimal.ROUND_FLOOR) step = self.opts['step'] * D(10)**exp if 'minStep' in self.opts: step = max(step, self.opts['minStep']) val += s * step #print "Exp:", exp, "step", step, "val", val else: val += s*self.opts['step'] if 'minStep' in self.opts and abs(val) < self.opts['minStep']: val = D(0) self.setValue(val, delaySignal=True) ## note all steps (arrow buttons, wheel, up/down keys..) emit delayed signals only. def valueInRange(self, value): bounds = self.opts['bounds'] if bounds[0] is not None and value < bounds[0]: return False if bounds[1] is not None and value > bounds[1]: return False if self.opts.get('int', False): if int(value) != value: return False return True def updateText(self, prev=None): # temporarily disable validation self.skipValidate = True txt = self.formatText(prev=prev) # actually set the text self.lineEdit().setText(txt) self.lastText = txt # re-enable the validation self.skipValidate = False def formatText(self, prev=None): # get the number of decimal places to print decimals = self.opts['decimals'] suffix = self.opts['suffix'] # format the string val = self.value() if self.opts['siPrefix'] is True and len(self.opts['suffix']) > 0: # SI prefix was requested, so scale the value accordingly if self.val == 0 and prev is not None: # special case: if it's zero use the previous prefix (s, p) = fn.siScale(prev) else: (s, p) = fn.siScale(val) parts = {'value': val, 'suffix': suffix, 'decimals': decimals, 'siPrefix': p, 'scaledValue': s*val} else: # no SI prefix /suffix requested; scale is 1 parts = {'value': val, 'suffix': suffix, 'decimals': decimals, 'siPrefix': '', 'scaledValue': val} parts['suffixGap'] = '' if (parts['suffix'] == '' and parts['siPrefix'] == '') else ' ' return self.opts['format'].format(**parts) def validate(self, strn, pos): if self.skipValidate: ret = QtGui.QValidator.Acceptable else: try: val = self.interpret() if val is False: ret = QtGui.QValidator.Intermediate else: if self.valueInRange(val): if not self.opts['delayUntilEditFinished']: self.setValue(val, update=False) ret = QtGui.QValidator.Acceptable else: ret = QtGui.QValidator.Intermediate except: import sys sys.excepthook(*sys.exc_info()) ret = QtGui.QValidator.Intermediate ## draw / clear border if ret == QtGui.QValidator.Intermediate: self.textValid = False elif ret == QtGui.QValidator.Acceptable: self.textValid = True ## note: if text is invalid, we don't change the textValid flag ## since the text will be forced to its previous state anyway self.update() self.errorBox.setVisible(not self.textValid) ## support 2 different pyqt APIs. Bleh. if hasattr(QtCore, 'QString'): return (ret, pos) else: return (ret, strn, pos) def fixup(self, strn): # fixup is called when the spinbox loses focus with an invalid or intermediate string self.updateText() # support both PyQt APIs (for Python 2 and 3 respectively) # http://pyqt.sourceforge.net/Docs/PyQt4/python_v3.html#qvalidator try: strn.clear() strn.append(self.lineEdit().text()) except AttributeError: return self.lineEdit().text() def interpret(self): """Return value of text or False if text is invalid.""" strn = self.lineEdit().text() # tokenize into numerical value, si prefix, and suffix try: val, siprefix, suffix = fn.siParse(strn, self.opts['regex'], suffix=self.opts['suffix']) except Exception: return False # check suffix if suffix != self.opts['suffix'] or (suffix == '' and siprefix != ''): return False # generate value val = self.opts['evalFunc'](val) if self.opts['int']: val = int(fn.siApply(val, siprefix)) else: try: val = fn.siApply(val, siprefix) except Exception: import sys sys.excepthook(*sys.exc_info()) return False return val def editingFinishedEvent(self): """Edit has finished; set value.""" #print "Edit finished." if asUnicode(self.lineEdit().text()) == self.lastText: #print "no text change." return try: val = self.interpret() except Exception: return if val is False: #print "value invalid:", str(self.lineEdit().text()) return if val == self.val: #print "no value change:", val, self.val return self.setValue(val, delaySignal=False) ## allow text update so that values are reformatted pretty-like def _updateHeight(self): # SpinBox has very large margins on some platforms; this is a hack to remove those # margins and allow more compact packing of controls. if not self.opts['compactHeight']: self.setMaximumHeight(1e6) return h = QtGui.QFontMetrics(self.font()).height() if self._lastFontHeight != h: self._lastFontHeight = h self.setMaximumHeight(h) def paintEvent(self, ev): self._updateHeight() QtGui.QAbstractSpinBox.paintEvent(self, ev) class ErrorBox(QtGui.QWidget): """Red outline to draw around lineedit when value is invalid. (for some reason, setting border from stylesheet does not work) """ def __init__(self, parent): QtGui.QWidget.__init__(self, parent) parent.installEventFilter(self) self.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents) self._resize() self.setVisible(False) def eventFilter(self, obj, ev): if ev.type() == QtCore.QEvent.Resize: self._resize() return False def _resize(self): self.setGeometry(0, 0, self.parent().width(), self.parent().height()) def paintEvent(self, ev): p = QtGui.QPainter(self) p.setPen(fn.mkPen(color='r', width=2)) p.drawRect(self.rect()) p.end()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/DataFilterWidget.py
.py
7,637
210
from ..Qt import QtGui, QtCore from .. import parametertree as ptree import numpy as np from ..pgcollections import OrderedDict from .. import functions as fn from ..python2_3 import basestring __all__ = ['DataFilterWidget'] class DataFilterWidget(ptree.ParameterTree): """ This class allows the user to filter multi-column data sets by specifying multiple criteria Wraps methods from DataFilterParameter: setFields, generateMask, filterData, and describe. """ sigFilterChanged = QtCore.Signal(object) def __init__(self): ptree.ParameterTree.__init__(self, showHeader=False) self.params = DataFilterParameter() self.setParameters(self.params) self.params.sigFilterChanged.connect(self.sigFilterChanged) self.setFields = self.params.setFields self.generateMask = self.params.generateMask self.filterData = self.params.filterData self.describe = self.params.describe def parameters(self): return self.params def addFilter(self, name): """Add a new filter and return the created parameter item. """ return self.params.addNew(name) class DataFilterParameter(ptree.types.GroupParameter): """A parameter group that specifies a set of filters to apply to tabular data. """ sigFilterChanged = QtCore.Signal(object) def __init__(self): self.fields = {} ptree.types.GroupParameter.__init__(self, name='Data Filter', addText='Add filter..', addList=[]) self.sigTreeStateChanged.connect(self.filterChanged) def filterChanged(self): self.sigFilterChanged.emit(self) def addNew(self, name): mode = self.fields[name].get('mode', 'range') if mode == 'range': child = self.addChild(RangeFilterItem(name, self.fields[name])) elif mode == 'enum': child = self.addChild(EnumFilterItem(name, self.fields[name])) return child def fieldNames(self): return self.fields.keys() def setFields(self, fields): """Set the list of fields that are available to be filtered. *fields* must be a dict or list of tuples that maps field names to a specification describing the field. Each specification is itself a dict with either ``'mode':'range'`` or ``'mode':'enum'``:: filter.setFields([ ('field1', {'mode': 'range'}), ('field2', {'mode': 'enum', 'values': ['val1', 'val2', 'val3']}), ('field3', {'mode': 'enum', 'values': {'val1':True, 'val2':False, 'val3':True}}), ]) """ with fn.SignalBlock(self.sigTreeStateChanged, self.filterChanged): self.fields = OrderedDict(fields) names = self.fieldNames() self.setAddList(names) # update any existing filters for ch in self.children(): name = ch.fieldName if name in fields: ch.updateFilter(fields[name]) self.sigFilterChanged.emit(self) def filterData(self, data): if len(data) == 0: return data return data[self.generateMask(data)] def generateMask(self, data): """Return a boolean mask indicating whether each item in *data* passes the filter critera. """ mask = np.ones(len(data), dtype=bool) if len(data) == 0: return mask for fp in self: if fp.value() is False: continue mask &= fp.generateMask(data, mask.copy()) #key, mn, mx = fp.fieldName, fp['Min'], fp['Max'] #vals = data[key] #mask &= (vals >= mn) #mask &= (vals < mx) ## Use inclusive minimum and non-inclusive maximum. This makes it easier to create non-overlapping selections return mask def describe(self): """Return a list of strings describing the currently enabled filters.""" desc = [] for fp in self: if fp.value() is False: continue desc.append(fp.describe()) return desc class RangeFilterItem(ptree.types.SimpleParameter): def __init__(self, name, opts): self.fieldName = name units = opts.get('units', '') self.units = units ptree.types.SimpleParameter.__init__(self, name=name, autoIncrementName=True, type='bool', value=True, removable=True, renamable=True, children=[ #dict(name="Field", type='list', value=name, values=fields), dict(name='Min', type='float', value=0.0, suffix=units, siPrefix=True), dict(name='Max', type='float', value=1.0, suffix=units, siPrefix=True), ]) def generateMask(self, data, mask): vals = data[self.fieldName][mask] mask[mask] = (vals >= self['Min']) & (vals < self['Max']) ## Use inclusive minimum and non-inclusive maximum. This makes it easier to create non-overlapping selections return mask def describe(self): return "%s < %s < %s" % (fn.siFormat(self['Min'], suffix=self.units), self.fieldName, fn.siFormat(self['Max'], suffix=self.units)) def updateFilter(self, opts): pass class EnumFilterItem(ptree.types.SimpleParameter): def __init__(self, name, opts): self.fieldName = name ptree.types.SimpleParameter.__init__(self, name=name, autoIncrementName=True, type='bool', value=True, removable=True, renamable=True) self.setEnumVals(opts) def generateMask(self, data, startMask): vals = data[self.fieldName][startMask] mask = np.ones(len(vals), dtype=bool) otherMask = np.ones(len(vals), dtype=bool) for c in self: key = c.maskValue if key == '__other__': m = ~otherMask else: m = vals != key otherMask &= m if c.value() is False: mask &= m startMask[startMask] = mask return startMask def describe(self): vals = [ch.name() for ch in self if ch.value() is True] return "%s: %s" % (self.fieldName, ', '.join(vals)) def updateFilter(self, opts): self.setEnumVals(opts) def setEnumVals(self, opts): vals = opts.get('values', {}) prevState = {} for ch in self.children(): prevState[ch.name()] = ch.value() self.removeChild(ch) if not isinstance(vals, dict): vals = OrderedDict([(v,(str(v), True)) for v in vals]) # Each filterable value can come with either (1) a string name, (2) a bool # indicating whether the value is enabled by default, or (3) a tuple providing # both. for val,valopts in vals.items(): if isinstance(valopts, bool): enabled = valopts vname = str(val) elif isinstance(valopts, basestring): enabled = True vname = valopts elif isinstance(valopts, tuple): vname, enabled = valopts ch = ptree.Parameter.create(name=vname, type='bool', value=prevState.get(vname, enabled)) ch.maskValue = val self.addChild(ch) ch = ptree.Parameter.create(name='(other)', type='bool', value=prevState.get('(other)', True)) ch.maskValue = '__other__' self.addChild(ch)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/FileDialog.py
.py
478
14
from ..Qt import QtGui, QtCore import sys __all__ = ['FileDialog'] class FileDialog(QtGui.QFileDialog): ## Compatibility fix for OSX: ## For some reason the native dialog doesn't show up when you set AcceptMode to AcceptSave on OS X, so we don't use the native dialog def __init__(self, *args): QtGui.QFileDialog.__init__(self, *args) if sys.platform == 'darwin': self.setOption(QtGui.QFileDialog.DontUseNativeDialog)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/ValueLabel.py
.py
2,872
73
from ..Qt import QtCore, QtGui from ..ptime import time from .. import functions as fn __all__ = ['ValueLabel'] class ValueLabel(QtGui.QLabel): """ QLabel specifically for displaying numerical values. Extends QLabel adding some extra functionality: - displaying units with si prefix - built-in exponential averaging """ def __init__(self, parent=None, suffix='', siPrefix=False, averageTime=0, formatStr=None): """ ============== ================================================================================== **Arguments:** suffix (str or None) The suffix to place after the value siPrefix (bool) Whether to add an SI prefix to the units and display a scaled value averageTime (float) The length of time in seconds to average values. If this value is 0, then no averaging is performed. As this value increases the display value will appear to change more slowly and smoothly. formatStr (str) Optionally, provide a format string to use when displaying text. The text will be generated by calling formatStr.format(value=, avgValue=, suffix=) (see Python documentation on str.format) This option is not compatible with siPrefix ============== ================================================================================== """ QtGui.QLabel.__init__(self, parent) self.values = [] self.averageTime = averageTime ## no averaging by default self.suffix = suffix self.siPrefix = siPrefix if formatStr is None: formatStr = '{avgValue:0.2g} {suffix}' self.formatStr = formatStr def setValue(self, value): now = time() self.values.append((now, value)) cutoff = now - self.averageTime while len(self.values) > 0 and self.values[0][0] < cutoff: self.values.pop(0) self.update() def setFormatStr(self, text): self.formatStr = text self.update() def setAverageTime(self, t): self.averageTime = t def averageValue(self): return sum(v[1] for v in self.values) / float(len(self.values)) def paintEvent(self, ev): self.setText(self.generateText()) return QtGui.QLabel.paintEvent(self, ev) def generateText(self): if len(self.values) == 0: return '' avg = self.averageValue() val = self.values[-1][1] if self.siPrefix: return fn.siFormat(avg, suffix=self.suffix) else: return self.formatStr.format(value=val, avgValue=avg, suffix=self.suffix)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/ComboBox.py
.py
8,134
246
import sys from ..Qt import QtGui, QtCore from ..SignalProxy import SignalProxy from ..pgcollections import OrderedDict from ..python2_3 import asUnicode, basestring class ComboBox(QtGui.QComboBox): """Extends QComboBox to add extra functionality. * Handles dict mappings -- user selects a text key, and the ComboBox indicates the selected value. * Requires item strings to be unique * Remembers selected value if list is cleared and subsequently repopulated * setItems() replaces the items in the ComboBox and blocks signals if the value ultimately does not change. """ def __init__(self, parent=None, items=None, default=None): QtGui.QComboBox.__init__(self, parent) self.currentIndexChanged.connect(self.indexChanged) self._ignoreIndexChange = False #self.value = default if 'darwin' in sys.platform: ## because MacOSX can show names that are wider than the comboBox self.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToMinimumContentsLength) #self.setMinimumContentsLength(10) self._chosenText = None self._items = OrderedDict() if items is not None: self.setItems(items) if default is not None: self.setValue(default) def setValue(self, value): """Set the selected item to the first one having the given value.""" text = None for k,v in self._items.items(): if v == value: text = k break if text is None: raise ValueError(value) self.setText(text) def setText(self, text): """Set the selected item to the first one having the given text.""" ind = self.findText(text) if ind == -1: raise ValueError(text) #self.value = value self.setCurrentIndex(ind) def value(self): """ If items were given as a list of strings, then return the currently selected text. If items were given as a dict, then return the value corresponding to the currently selected key. If the combo list is empty, return None. """ if self.count() == 0: return None text = asUnicode(self.currentText()) return self._items[text] def ignoreIndexChange(func): # Decorator that prevents updates to self._chosenText def fn(self, *args, **kwds): prev = self._ignoreIndexChange self._ignoreIndexChange = True try: ret = func(self, *args, **kwds) finally: self._ignoreIndexChange = prev return ret return fn def blockIfUnchanged(func): # decorator that blocks signal emission during complex operations # and emits currentIndexChanged only if the value has actually # changed at the end. def fn(self, *args, **kwds): prevVal = self.value() blocked = self.signalsBlocked() self.blockSignals(True) try: ret = func(self, *args, **kwds) finally: self.blockSignals(blocked) # only emit if the value has changed if self.value() != prevVal: self.currentIndexChanged.emit(self.currentIndex()) return ret return fn @ignoreIndexChange @blockIfUnchanged def setItems(self, items): """ *items* may be a list, a tuple, or a dict. If a dict is given, then the keys are used to populate the combo box and the values will be used for both value() and setValue(). """ prevVal = self.value() self.blockSignals(True) try: self.clear() self.addItems(items) finally: self.blockSignals(False) # only emit if we were not able to re-set the original value if self.value() != prevVal: self.currentIndexChanged.emit(self.currentIndex()) def items(self): return self.items.copy() def updateList(self, items): # for backward compatibility return self.setItems(items) def indexChanged(self, index): # current index has changed; need to remember new 'chosen text' if self._ignoreIndexChange: return self._chosenText = asUnicode(self.currentText()) def setCurrentIndex(self, index): QtGui.QComboBox.setCurrentIndex(self, index) def itemsChanged(self): # try to set the value to the last one selected, if it is available. if self._chosenText is not None: try: self.setText(self._chosenText) except ValueError: pass @ignoreIndexChange def insertItem(self, *args): raise NotImplementedError() #QtGui.QComboBox.insertItem(self, *args) #self.itemsChanged() @ignoreIndexChange def insertItems(self, *args): raise NotImplementedError() #QtGui.QComboBox.insertItems(self, *args) #self.itemsChanged() @ignoreIndexChange def addItem(self, *args, **kwds): # Need to handle two different function signatures for QComboBox.addItem try: if isinstance(args[0], basestring): text = args[0] if len(args) == 2: value = args[1] else: value = kwds.get('value', text) else: text = args[1] if len(args) == 3: value = args[2] else: value = kwds.get('value', text) except IndexError: raise TypeError("First or second argument of addItem must be a string.") if text in self._items: raise Exception('ComboBox already has item named "%s".' % text) self._items[text] = value QtGui.QComboBox.addItem(self, *args) self.itemsChanged() def setItemValue(self, name, value): if name not in self._items: self.addItem(name, value) else: self._items[name] = value @ignoreIndexChange @blockIfUnchanged def addItems(self, items): if isinstance(items, list) or isinstance(items, tuple): texts = items items = dict([(x, x) for x in items]) elif isinstance(items, dict): texts = list(items.keys()) else: raise TypeError("items argument must be list or dict or tuple (got %s)." % type(items)) for t in texts: if t in self._items: raise Exception('ComboBox already has item named "%s".' % t) for k,v in items.items(): self._items[k] = v QtGui.QComboBox.addItems(self, list(texts)) self.itemsChanged() @ignoreIndexChange def clear(self): self._items = OrderedDict() QtGui.QComboBox.clear(self) self.itemsChanged() def saveState(self): ind = self.currentIndex() data = self.itemData(ind) #if not data.isValid(): if data is not None: try: if not data.isValid(): data = None else: data = data.toInt()[0] except AttributeError: pass if data is None: return asUnicode(self.itemText(ind)) else: return data def restoreState(self, v): if type(v) is int: ind = self.findData(v) if ind > -1: self.setCurrentIndex(ind) return self.setCurrentIndex(self.findText(str(v))) def widgetGroupInterface(self): return (self.currentIndexChanged, self.saveState, self.restoreState)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/RemoteGraphicsView.py
.py
14,359
334
from ..Qt import QtGui, QtCore, QT_LIB if QT_LIB in ['PyQt4', 'PyQt5']: import sip from .. import multiprocess as mp from .GraphicsView import GraphicsView from .. import CONFIG_OPTIONS import numpy as np import mmap, tempfile, ctypes, atexit, sys, random __all__ = ['RemoteGraphicsView'] class SerializableWheelEvent: """ Contains all information of a QWheelEvent, is serializable and can generate QWheelEvents. Methods have the functionality of their QWheelEvent equivalent. """ def __init__(self, _pos, _globalPos, _delta, _buttons, _modifiers, _orientation): self._pos = _pos self._globalPos = _globalPos self._delta = _delta self._buttons = _buttons self._modifiers = _modifiers self._orientation_vertical = _orientation == QtCore.Qt.Vertical def pos(self): return self._pos def globalPos(self): return self._globalPos def delta(self): return self._delta def orientation(self): if self._orientation_vertical: return QtCore.Qt.Vertical else: return QtCore.Qt.Horizontal def angleDelta(self): if self._orientation_vertical: return QtCore.QPoint(0, self._delta) else: return QtCore.QPoint(self._delta, 0) def buttons(self): return QtCore.Qt.MouseButtons(self._buttons) def modifiers(self): return QtCore.Qt.KeyboardModifiers(self._modifiers) def toQWheelEvent(self): """ Generate QWheelEvent from SerializableWheelEvent. """ if QT_LIB in ['PyQt4', 'PySide']: return QtGui.QWheelEvent(self.pos(), self.globalPos(), self.delta(), self.buttons(), self.modifiers(), self.orientation()) else: return QtGui.QWheelEvent(self.pos(), self.globalPos(), QtCore.QPoint(), self.angleDelta(), self.delta(), self.orientation(), self.buttons(), self.modifiers()) class RemoteGraphicsView(QtGui.QWidget): """ Replacement for GraphicsView that does all scene management and rendering on a remote process, while displaying on the local widget. GraphicsItems must be created by proxy to the remote process. """ def __init__(self, parent=None, *args, **kwds): """ The keyword arguments 'useOpenGL' and 'backgound', if specified, are passed to the remote GraphicsView.__init__(). All other keyword arguments are passed to multiprocess.QtProcess.__init__(). """ self._img = None self._imgReq = None self._sizeHint = (640,480) ## no clue why this is needed, but it seems to be the default sizeHint for GraphicsView. ## without it, the widget will not compete for space against another GraphicsView. QtGui.QWidget.__init__(self) # separate local keyword arguments from remote. remoteKwds = {} for kwd in ['useOpenGL', 'background']: if kwd in kwds: remoteKwds[kwd] = kwds.pop(kwd) self._proc = mp.QtProcess(**kwds) self.pg = self._proc._import('pyqtgraph') self.pg.setConfigOptions(**CONFIG_OPTIONS) rpgRemote = self._proc._import('pyqtgraph.widgets.RemoteGraphicsView') self._view = rpgRemote.Renderer(*args, **remoteKwds) self._view._setProxyOptions(deferGetattr=True) self.setFocusPolicy(QtCore.Qt.StrongFocus) self.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) self.setMouseTracking(True) self.shm = None shmFileName = self._view.shmFileName() if sys.platform.startswith('win'): self.shmtag = shmFileName else: self.shmFile = open(shmFileName, 'r') self._view.sceneRendered.connect(mp.proxy(self.remoteSceneChanged)) #, callSync='off')) ## Note: we need synchronous signals ## even though there is no return value-- ## this informs the renderer that it is ## safe to begin rendering again. for method in ['scene', 'setCentralItem']: setattr(self, method, getattr(self._view, method)) def resizeEvent(self, ev): ret = QtGui.QWidget.resizeEvent(self, ev) self._view.resize(self.size(), _callSync='off') return ret def sizeHint(self): return QtCore.QSize(*self._sizeHint) def remoteSceneChanged(self, data): w, h, size, newfile = data #self._sizeHint = (whint, hhint) if self.shm is None or self.shm.size != size: if self.shm is not None: self.shm.close() if sys.platform.startswith('win'): self.shmtag = newfile ## on windows, we create a new tag for every resize self.shm = mmap.mmap(-1, size, self.shmtag) ## can't use tmpfile on windows because the file can only be opened once. elif sys.platform == 'darwin': self.shmFile.close() self.shmFile = open(self._view.shmFileName(), 'r') self.shm = mmap.mmap(self.shmFile.fileno(), size, mmap.MAP_SHARED, mmap.PROT_READ) else: self.shm = mmap.mmap(self.shmFile.fileno(), size, mmap.MAP_SHARED, mmap.PROT_READ) self.shm.seek(0) data = self.shm.read(w*h*4) self._img = QtGui.QImage(data, w, h, QtGui.QImage.Format_ARGB32) self._img.data = data # data must be kept alive or PySide 1.2.1 (and probably earlier) will crash. self.update() def paintEvent(self, ev): if self._img is None: return p = QtGui.QPainter(self) p.drawImage(self.rect(), self._img, QtCore.QRect(0, 0, self._img.width(), self._img.height())) p.end() def mousePressEvent(self, ev): self._view.mousePressEvent(int(ev.type()), ev.pos(), ev.pos(), int(ev.button()), int(ev.buttons()), int(ev.modifiers()), _callSync='off') ev.accept() return QtGui.QWidget.mousePressEvent(self, ev) def mouseReleaseEvent(self, ev): self._view.mouseReleaseEvent(int(ev.type()), ev.pos(), ev.pos(), int(ev.button()), int(ev.buttons()), int(ev.modifiers()), _callSync='off') ev.accept() return QtGui.QWidget.mouseReleaseEvent(self, ev) def mouseMoveEvent(self, ev): self._view.mouseMoveEvent(int(ev.type()), ev.pos(), ev.pos(), int(ev.button()), int(ev.buttons()), int(ev.modifiers()), _callSync='off') ev.accept() return QtGui.QWidget.mouseMoveEvent(self, ev) def wheelEvent(self, ev): delta = 0 orientation = QtCore.Qt.Horizontal if QT_LIB in ['PyQt4', 'PySide']: delta = ev.delta() orientation = ev.orientation() else: delta = ev.angleDelta().x() if delta == 0: orientation = QtCore.Qt.Vertical delta = ev.angleDelta().y() serializableEvent = SerializableWheelEvent(ev.pos(), ev.pos(), delta, int(ev.buttons()), int(ev.modifiers()), orientation) self._view.wheelEvent(serializableEvent, _callSync='off') ev.accept() return QtGui.QWidget.wheelEvent(self, ev) def keyEvent(self, ev): if self._view.keyEvent(int(ev.type()), int(ev.modifiers()), text, autorep, count): ev.accept() return QtGui.QWidget.keyEvent(self, ev) def enterEvent(self, ev): self._view.enterEvent(int(ev.type()), _callSync='off') return QtGui.QWidget.enterEvent(self, ev) def leaveEvent(self, ev): self._view.leaveEvent(int(ev.type()), _callSync='off') return QtGui.QWidget.leaveEvent(self, ev) def remoteProcess(self): """Return the remote process handle. (see multiprocess.remoteproxy.RemoteEventHandler)""" return self._proc def close(self): """Close the remote process. After this call, the widget will no longer be updated.""" self._proc.close() class Renderer(GraphicsView): ## Created by the remote process to handle render requests sceneRendered = QtCore.Signal(object) def __init__(self, *args, **kwds): ## Create shared memory for rendered image #pg.dbg(namespace={'r': self}) if sys.platform.startswith('win'): self.shmtag = "pyqtgraph_shmem_" + ''.join([chr((random.getrandbits(20)%25) + 97) for i in range(20)]) self.shm = mmap.mmap(-1, mmap.PAGESIZE, self.shmtag) # use anonymous mmap on windows else: self.shmFile = tempfile.NamedTemporaryFile(prefix='pyqtgraph_shmem_') self.shmFile.write(b'\x00' * (mmap.PAGESIZE+1)) self.shmFile.flush() fd = self.shmFile.fileno() self.shm = mmap.mmap(fd, mmap.PAGESIZE, mmap.MAP_SHARED, mmap.PROT_WRITE) atexit.register(self.close) GraphicsView.__init__(self, *args, **kwds) self.scene().changed.connect(self.update) self.img = None self.renderTimer = QtCore.QTimer() self.renderTimer.timeout.connect(self.renderView) self.renderTimer.start(16) def close(self): self.shm.close() if not sys.platform.startswith('win'): self.shmFile.close() def shmFileName(self): if sys.platform.startswith('win'): return self.shmtag else: return self.shmFile.name def update(self): self.img = None return GraphicsView.update(self) def resize(self, size): oldSize = self.size() GraphicsView.resize(self, size) self.resizeEvent(QtGui.QResizeEvent(size, oldSize)) self.update() def renderView(self): if self.img is None: ## make sure shm is large enough and get its address if self.width() == 0 or self.height() == 0: return size = self.width() * self.height() * 4 if size > self.shm.size(): if sys.platform.startswith('win'): ## windows says "WindowsError: [Error 87] the parameter is incorrect" if we try to resize the mmap self.shm.close() ## it also says (sometimes) 'access is denied' if we try to reuse the tag. self.shmtag = "pyqtgraph_shmem_" + ''.join([chr((random.getrandbits(20)%25) + 97) for i in range(20)]) self.shm = mmap.mmap(-1, size, self.shmtag) elif sys.platform == 'darwin': self.shm.close() self.shmFile.close() self.shmFile = tempfile.NamedTemporaryFile(prefix='pyqtgraph_shmem_') self.shmFile.write(b'\x00' * (size + 1)) self.shmFile.flush() self.shm = mmap.mmap(self.shmFile.fileno(), size, mmap.MAP_SHARED, mmap.PROT_WRITE) else: self.shm.resize(size) ## render the scene directly to shared memory if QT_LIB in ['PySide', 'PySide2']: ch = ctypes.c_char.from_buffer(self.shm, 0) #ch = ctypes.c_char_p(address) self.img = QtGui.QImage(ch, self.width(), self.height(), QtGui.QImage.Format_ARGB32) else: address = ctypes.addressof(ctypes.c_char.from_buffer(self.shm, 0)) # different versions of pyqt have different requirements here.. try: self.img = QtGui.QImage(sip.voidptr(address), self.width(), self.height(), QtGui.QImage.Format_ARGB32) except TypeError: try: self.img = QtGui.QImage(memoryview(buffer(self.shm)), self.width(), self.height(), QtGui.QImage.Format_ARGB32) except TypeError: # Works on PyQt 4.9.6 self.img = QtGui.QImage(address, self.width(), self.height(), QtGui.QImage.Format_ARGB32) self.img.fill(0xffffffff) p = QtGui.QPainter(self.img) self.render(p, self.viewRect(), self.rect()) p.end() self.sceneRendered.emit((self.width(), self.height(), self.shm.size(), self.shmFileName())) def mousePressEvent(self, typ, pos, gpos, btn, btns, mods): typ = QtCore.QEvent.Type(typ) btn = QtCore.Qt.MouseButton(btn) btns = QtCore.Qt.MouseButtons(btns) mods = QtCore.Qt.KeyboardModifiers(mods) return GraphicsView.mousePressEvent(self, QtGui.QMouseEvent(typ, pos, gpos, btn, btns, mods)) def mouseMoveEvent(self, typ, pos, gpos, btn, btns, mods): typ = QtCore.QEvent.Type(typ) btn = QtCore.Qt.MouseButton(btn) btns = QtCore.Qt.MouseButtons(btns) mods = QtCore.Qt.KeyboardModifiers(mods) return GraphicsView.mouseMoveEvent(self, QtGui.QMouseEvent(typ, pos, gpos, btn, btns, mods)) def mouseReleaseEvent(self, typ, pos, gpos, btn, btns, mods): typ = QtCore.QEvent.Type(typ) btn = QtCore.Qt.MouseButton(btn) btns = QtCore.Qt.MouseButtons(btns) mods = QtCore.Qt.KeyboardModifiers(mods) return GraphicsView.mouseReleaseEvent(self, QtGui.QMouseEvent(typ, pos, gpos, btn, btns, mods)) def wheelEvent(self, ev): return GraphicsView.wheelEvent(self, ev.toQWheelEvent()) def keyEvent(self, typ, mods, text, autorep, count): typ = QtCore.QEvent.Type(typ) mods = QtCore.Qt.KeyboardModifiers(mods) GraphicsView.keyEvent(self, QtGui.QKeyEvent(typ, mods, text, autorep, count)) return ev.accepted() def enterEvent(self, typ): ev = QtCore.QEvent(QtCore.QEvent.Type(typ)) return GraphicsView.enterEvent(self, ev) def leaveEvent(self, typ): ev = QtCore.QEvent(QtCore.QEvent.Type(typ)) return GraphicsView.leaveEvent(self, ev)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/PlotWidget.py
.py
4,167
101
# -*- coding: utf-8 -*- """ PlotWidget.py - Convenience class--GraphicsView widget displaying a single PlotItem Copyright 2010 Luke Campagnola Distributed under MIT/X11 license. See license.txt for more information. """ from ..Qt import QtCore, QtGui from .GraphicsView import * from ..graphicsItems.PlotItem import * __all__ = ['PlotWidget'] class PlotWidget(GraphicsView): # signals wrapped from PlotItem / ViewBox sigRangeChanged = QtCore.Signal(object, object) sigTransformChanged = QtCore.Signal(object) """ :class:`GraphicsView <pyqtgraph.GraphicsView>` widget with a single :class:`PlotItem <pyqtgraph.PlotItem>` inside. The following methods are wrapped directly from PlotItem: :func:`addItem <pyqtgraph.PlotItem.addItem>`, :func:`removeItem <pyqtgraph.PlotItem.removeItem>`, :func:`clear <pyqtgraph.PlotItem.clear>`, :func:`setAxisItems <pyqtgraph.PlotItem.setAxisItems>`, :func:`setXRange <pyqtgraph.ViewBox.setXRange>`, :func:`setYRange <pyqtgraph.ViewBox.setYRange>`, :func:`setRange <pyqtgraph.ViewBox.setRange>`, :func:`autoRange <pyqtgraph.ViewBox.autoRange>`, :func:`setXLink <pyqtgraph.ViewBox.setXLink>`, :func:`setYLink <pyqtgraph.ViewBox.setYLink>`, :func:`viewRect <pyqtgraph.ViewBox.viewRect>`, :func:`setMouseEnabled <pyqtgraph.ViewBox.setMouseEnabled>`, :func:`enableAutoRange <pyqtgraph.ViewBox.enableAutoRange>`, :func:`disableAutoRange <pyqtgraph.ViewBox.disableAutoRange>`, :func:`setAspectLocked <pyqtgraph.ViewBox.setAspectLocked>`, :func:`setLimits <pyqtgraph.ViewBox.setLimits>`, :func:`register <pyqtgraph.ViewBox.register>`, :func:`unregister <pyqtgraph.ViewBox.unregister>` For all other methods, use :func:`getPlotItem <pyqtgraph.PlotWidget.getPlotItem>`. """ def __init__(self, parent=None, background='default', **kargs): """When initializing PlotWidget, *parent* and *background* are passed to :func:`GraphicsWidget.__init__() <pyqtgraph.GraphicsWidget.__init__>` and all others are passed to :func:`PlotItem.__init__() <pyqtgraph.PlotItem.__init__>`.""" GraphicsView.__init__(self, parent, background=background) self.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) self.enableMouse(False) self.plotItem = PlotItem(**kargs) self.setCentralItem(self.plotItem) ## Explicitly wrap methods from plotItem ## NOTE: If you change this list, update the documentation above as well. for m in ['addItem', 'removeItem', 'autoRange', 'clear', 'setAxisItems', 'setXRange', 'setYRange', 'setRange', 'setAspectLocked', 'setMouseEnabled', 'setXLink', 'setYLink', 'enableAutoRange', 'disableAutoRange', 'setLimits', 'register', 'unregister', 'viewRect']: setattr(self, m, getattr(self.plotItem, m)) #QtCore.QObject.connect(self.plotItem, QtCore.SIGNAL('viewChanged'), self.viewChanged) self.plotItem.sigRangeChanged.connect(self.viewRangeChanged) def close(self): self.plotItem.close() self.plotItem = None #self.scene().clear() #self.mPlotItem.close() self.setParent(None) super(PlotWidget, self).close() def __getattr__(self, attr): ## implicitly wrap methods from plotItem if hasattr(self.plotItem, attr): m = getattr(self.plotItem, attr) if hasattr(m, '__call__'): return m raise AttributeError(attr) def viewRangeChanged(self, view, range): #self.emit(QtCore.SIGNAL('viewChanged'), *args) self.sigRangeChanged.emit(self, range) def widgetGroupInterface(self): return (None, PlotWidget.saveState, PlotWidget.restoreState) def saveState(self): return self.plotItem.saveState() def restoreState(self, state): return self.plotItem.restoreState(state) def getPlotItem(self): """Return the PlotItem contained within.""" return self.plotItem
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/ScatterPlotWidget.py
.py
11,193
287
from ..Qt import QtGui, QtCore from .PlotWidget import PlotWidget from .DataFilterWidget import DataFilterParameter from .ColorMapWidget import ColorMapParameter from .. import parametertree as ptree from .. import functions as fn from .. import getConfigOption from ..graphicsItems.TextItem import TextItem import numpy as np from ..pgcollections import OrderedDict __all__ = ['ScatterPlotWidget'] class ScatterPlotWidget(QtGui.QSplitter): """ This is a high-level widget for exploring relationships in tabular data. Given a multi-column record array, the widget displays a scatter plot of a specific subset of the data. Includes controls for selecting the columns to plot, filtering data, and determining symbol color and shape. The widget consists of four components: 1) A list of column names from which the user may select 1 or 2 columns to plot. If one column is selected, the data for that column will be plotted in a histogram-like manner by using :func:`pseudoScatter() <pyqtgraph.pseudoScatter>`. If two columns are selected, then the scatter plot will be generated with x determined by the first column that was selected and y by the second. 2) A DataFilter that allows the user to select a subset of the data by specifying multiple selection criteria. 3) A ColorMap that allows the user to determine how points are colored by specifying multiple criteria. 4) A PlotWidget for displaying the data. """ sigScatterPlotClicked = QtCore.Signal(object, object) def __init__(self, parent=None): QtGui.QSplitter.__init__(self, QtCore.Qt.Horizontal) self.ctrlPanel = QtGui.QSplitter(QtCore.Qt.Vertical) self.addWidget(self.ctrlPanel) self.fieldList = QtGui.QListWidget() self.fieldList.setSelectionMode(self.fieldList.ExtendedSelection) self.ptree = ptree.ParameterTree(showHeader=False) self.filter = DataFilterParameter() self.colorMap = ColorMapParameter() self.params = ptree.Parameter.create(name='params', type='group', children=[self.filter, self.colorMap]) self.ptree.setParameters(self.params, showTop=False) self.plot = PlotWidget() self.ctrlPanel.addWidget(self.fieldList) self.ctrlPanel.addWidget(self.ptree) self.addWidget(self.plot) fg = fn.mkColor(getConfigOption('foreground')) fg.setAlpha(150) self.filterText = TextItem(border=getConfigOption('foreground'), color=fg) self.filterText.setPos(60,20) self.filterText.setParentItem(self.plot.plotItem) self.data = None self.indices = None self.mouseOverField = None self.scatterPlot = None self.selectionScatter = None self.selectedIndices = [] self.style = dict(pen=None, symbol='o') self._visibleXY = None # currently plotted points self._visibleData = None # currently plotted records self._visibleIndices = None self._indexMap = None self.fieldList.itemSelectionChanged.connect(self.fieldSelectionChanged) self.filter.sigFilterChanged.connect(self.filterChanged) self.colorMap.sigColorMapChanged.connect(self.updatePlot) def setFields(self, fields, mouseOverField=None): """ Set the list of field names/units to be processed. The format of *fields* is the same as used by :func:`ColorMapWidget.setFields <pyqtgraph.widgets.ColorMapWidget.ColorMapParameter.setFields>` """ self.fields = OrderedDict(fields) self.mouseOverField = mouseOverField self.fieldList.clear() for f,opts in fields: item = QtGui.QListWidgetItem(f) item.opts = opts item = self.fieldList.addItem(item) self.filter.setFields(fields) self.colorMap.setFields(fields) def setSelectedFields(self, *fields): self.fieldList.itemSelectionChanged.disconnect(self.fieldSelectionChanged) try: self.fieldList.clearSelection() for f in fields: i = self.fields.keys().index(f) item = self.fieldList.item(i) item.setSelected(True) finally: self.fieldList.itemSelectionChanged.connect(self.fieldSelectionChanged) self.fieldSelectionChanged() def setData(self, data): """ Set the data to be processed and displayed. Argument must be a numpy record array. """ self.data = data self.indices = np.arange(len(data)) self.filtered = None self.filteredIndices = None self.updatePlot() def setSelectedIndices(self, inds): """Mark the specified indices as selected. Must be a sequence of integers that index into the array given in setData(). """ self.selectedIndices = inds self.updateSelected() def setSelectedPoints(self, points): """Mark the specified points as selected. Must be a list of points as generated by the sigScatterPlotClicked signal. """ self.setSelectedIndices([pt.originalIndex for pt in points]) def fieldSelectionChanged(self): sel = self.fieldList.selectedItems() if len(sel) > 2: self.fieldList.blockSignals(True) try: for item in sel[1:-1]: item.setSelected(False) finally: self.fieldList.blockSignals(False) self.updatePlot() def filterChanged(self, f): self.filtered = None self.updatePlot() desc = self.filter.describe() if len(desc) == 0: self.filterText.setVisible(False) else: self.filterText.setText('\n'.join(desc)) self.filterText.setVisible(True) def updatePlot(self): self.plot.clear() if self.data is None or len(self.data) == 0: return if self.filtered is None: mask = self.filter.generateMask(self.data) self.filtered = self.data[mask] self.filteredIndices = self.indices[mask] data = self.filtered if len(data) == 0: return colors = np.array([fn.mkBrush(*x) for x in self.colorMap.map(data)]) style = self.style.copy() ## Look up selected columns and units sel = list([str(item.text()) for item in self.fieldList.selectedItems()]) units = list([item.opts.get('units', '') for item in self.fieldList.selectedItems()]) if len(sel) == 0: self.plot.setTitle('') return if len(sel) == 1: self.plot.setLabels(left=('N', ''), bottom=(sel[0], units[0]), title='') if len(data) == 0: return #x = data[sel[0]] #y = None xy = [data[sel[0]], None] elif len(sel) == 2: self.plot.setLabels(left=(sel[1],units[1]), bottom=(sel[0],units[0])) if len(data) == 0: return xy = [data[sel[0]], data[sel[1]]] #xydata = [] #for ax in [0,1]: #d = data[sel[ax]] ### scatter catecorical values just a bit so they show up better in the scatter plot. ##if sel[ax] in ['MorphologyBSMean', 'MorphologyTDMean', 'FIType']: ##d += np.random.normal(size=len(cells), scale=0.1) #xydata.append(d) #x,y = xydata ## convert enum-type fields to float, set axis labels enum = [False, False] for i in [0,1]: axis = self.plot.getAxis(['bottom', 'left'][i]) if xy[i] is not None and (self.fields[sel[i]].get('mode', None) == 'enum' or xy[i].dtype.kind in ('S', 'O')): vals = self.fields[sel[i]].get('values', list(set(xy[i]))) xy[i] = np.array([vals.index(x) if x in vals else len(vals) for x in xy[i]], dtype=float) axis.setTicks([list(enumerate(vals))]) enum[i] = True else: axis.setTicks(None) # reset to automatic ticking ## mask out any nan values mask = np.ones(len(xy[0]), dtype=bool) if xy[0].dtype.kind == 'f': mask &= np.isfinite(xy[0]) if xy[1] is not None and xy[1].dtype.kind == 'f': mask &= np.isfinite(xy[1]) xy[0] = xy[0][mask] style['symbolBrush'] = colors[mask] data = data[mask] indices = self.filteredIndices[mask] ## Scatter y-values for a histogram-like appearance if xy[1] is None: ## column scatter plot xy[1] = fn.pseudoScatter(xy[0]) else: ## beeswarm plots xy[1] = xy[1][mask] for ax in [0,1]: if not enum[ax]: continue imax = int(xy[ax].max()) if len(xy[ax]) > 0 else 0 for i in range(imax+1): keymask = xy[ax] == i scatter = fn.pseudoScatter(xy[1-ax][keymask], bidir=True) if len(scatter) == 0: continue smax = np.abs(scatter).max() if smax != 0: scatter *= 0.2 / smax xy[ax][keymask] += scatter if self.scatterPlot is not None: try: self.scatterPlot.sigPointsClicked.disconnect(self.plotClicked) except: pass self._visibleXY = xy self._visibleData = data self._visibleIndices = indices self._indexMap = None self.scatterPlot = self.plot.plot(xy[0], xy[1], data=data, **style) self.scatterPlot.sigPointsClicked.connect(self.plotClicked) self.updateSelected() def updateSelected(self): if self._visibleXY is None: return # map from global index to visible index indMap = self._getIndexMap() inds = [indMap[i] for i in self.selectedIndices if i in indMap] x,y = self._visibleXY[0][inds], self._visibleXY[1][inds] if self.selectionScatter is not None: self.plot.plotItem.removeItem(self.selectionScatter) if len(x) == 0: return self.selectionScatter = self.plot.plot(x, y, pen=None, symbol='s', symbolSize=12, symbolBrush=None, symbolPen='y') def _getIndexMap(self): # mapping from original data index to visible point index if self._indexMap is None: self._indexMap = {j:i for i,j in enumerate(self._visibleIndices)} return self._indexMap def plotClicked(self, plot, points): # Tag each point with its index into the original dataset for pt in points: pt.originalIndex = self._visibleIndices[pt.index()] self.sigScatterPlotClicked.emit(self, points)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/MultiPlotWidget.py
.py
2,986
79
# -*- coding: utf-8 -*- """ MultiPlotWidget.py - Convenience class--GraphicsView widget displaying a MultiPlotItem Copyright 2010 Luke Campagnola Distributed under MIT/X11 license. See license.txt for more information. """ from ..Qt import QtCore from .GraphicsView import GraphicsView from ..graphicsItems import MultiPlotItem as MultiPlotItem __all__ = ['MultiPlotWidget'] class MultiPlotWidget(GraphicsView): """Widget implementing a graphicsView with a single MultiPlotItem inside.""" def __init__(self, parent=None): self.minPlotHeight = 50 self.mPlotItem = MultiPlotItem.MultiPlotItem() GraphicsView.__init__(self, parent) self.enableMouse(False) self.setCentralItem(self.mPlotItem) ## Explicitly wrap methods from mPlotItem #for m in ['setData']: #setattr(self, m, getattr(self.mPlotItem, m)) self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) def __getattr__(self, attr): ## implicitly wrap methods from plotItem if hasattr(self.mPlotItem, attr): m = getattr(self.mPlotItem, attr) if hasattr(m, '__call__'): return m raise AttributeError(attr) def setMinimumPlotHeight(self, min): """Set the minimum height for each sub-plot displayed. If the total height of all plots is greater than the height of the widget, then a scroll bar will appear to provide access to the entire set of plots. Added in version 0.9.9 """ self.minPlotHeight = min self.resizeEvent(None) def widgetGroupInterface(self): return (None, MultiPlotWidget.saveState, MultiPlotWidget.restoreState) def saveState(self): return {} #return self.plotItem.saveState() def restoreState(self, state): pass #return self.plotItem.restoreState(state) def close(self): self.mPlotItem.close() self.mPlotItem = None self.setParent(None) GraphicsView.close(self) def setRange(self, *args, **kwds): GraphicsView.setRange(self, *args, **kwds) if self.centralWidget is not None: r = self.range minHeight = len(self.mPlotItem.plots) * self.minPlotHeight if r.height() < minHeight: r.setHeight(minHeight) r.setWidth(r.width() - self.verticalScrollBar().width()) self.centralWidget.setGeometry(r) def resizeEvent(self, ev): if self.closed: return if self.autoPixelRange: self.range = QtCore.QRectF(0, 0, self.size().width(), self.size().height()) MultiPlotWidget.setRange(self, self.range, padding=0, disableAutoPixel=False) ## we do this because some subclasses like to redefine setRange in an incompatible way. self.updateMatrix()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/RawImageWidget.py
.py
5,579
144
from ..Qt import QtCore, QtGui try: from ..Qt import QtOpenGL from OpenGL.GL import * HAVE_OPENGL = True except Exception: # Would prefer `except ImportError` here, but some versions of pyopengl generate # AttributeError upon import HAVE_OPENGL = False from .. import functions as fn import numpy as np class RawImageWidget(QtGui.QWidget): """ Widget optimized for very fast video display. Generally using an ImageItem inside GraphicsView is fast enough. On some systems this may provide faster video. See the VideoSpeedTest example for benchmarking. """ def __init__(self, parent=None, scaled=False): """ Setting scaled=True will cause the entire image to be displayed within the boundaries of the widget. This also greatly reduces the speed at which it will draw frames. """ QtGui.QWidget.__init__(self, parent=None) self.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding)) self.scaled = scaled self.opts = None self.image = None def setImage(self, img, *args, **kargs): """ img must be ndarray of shape (x,y), (x,y,3), or (x,y,4). Extra arguments are sent to functions.makeARGB """ self.opts = (img, args, kargs) self.image = None self.update() def paintEvent(self, ev): if self.opts is None: return if self.image is None: argb, alpha = fn.makeARGB(self.opts[0], *self.opts[1], **self.opts[2]) self.image = fn.makeQImage(argb, alpha) self.opts = () #if self.pixmap is None: #self.pixmap = QtGui.QPixmap.fromImage(self.image) p = QtGui.QPainter(self) if self.scaled: rect = self.rect() ar = rect.width() / float(rect.height()) imar = self.image.width() / float(self.image.height()) if ar > imar: rect.setWidth(int(rect.width() * imar/ar)) else: rect.setHeight(int(rect.height() * ar/imar)) p.drawImage(rect, self.image) else: p.drawImage(QtCore.QPointF(), self.image) #p.drawPixmap(self.rect(), self.pixmap) p.end() if HAVE_OPENGL: class RawImageGLWidget(QtOpenGL.QGLWidget): """ Similar to RawImageWidget, but uses a GL widget to do all drawing. Perfomance varies between platforms; see examples/VideoSpeedTest for benchmarking. """ def __init__(self, parent=None, scaled=False): QtOpenGL.QGLWidget.__init__(self, parent=None) self.scaled = scaled self.image = None self.uploaded = False self.smooth = False self.opts = None def setImage(self, img, *args, **kargs): """ img must be ndarray of shape (x,y), (x,y,3), or (x,y,4). Extra arguments are sent to functions.makeARGB """ self.opts = (img, args, kargs) self.image = None self.uploaded = False self.update() def initializeGL(self): self.texture = glGenTextures(1) def uploadTexture(self): glEnable(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D, self.texture) if self.smooth: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) else: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER) #glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER) shape = self.image.shape ### Test texture dimensions first #glTexImage2D(GL_PROXY_TEXTURE_2D, 0, GL_RGBA, shape[0], shape[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, None) #if glGetTexLevelParameteriv(GL_PROXY_TEXTURE_2D, 0, GL_TEXTURE_WIDTH) == 0: #raise Exception("OpenGL failed to create 2D texture (%dx%d); too large for this hardware." % shape[:2]) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, shape[0], shape[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, self.image.transpose((1,0,2))) glDisable(GL_TEXTURE_2D) def paintGL(self): if self.image is None: if self.opts is None: return img, args, kwds = self.opts kwds['useRGBA'] = True self.image, alpha = fn.makeARGB(img, *args, **kwds) if not self.uploaded: self.uploadTexture() glViewport(0, 0, self.width() * self.devicePixelRatio(), self.height() * self.devicePixelRatio()) glEnable(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D, self.texture) glColor4f(1,1,1,1) glBegin(GL_QUADS) glTexCoord2f(0,0) glVertex3f(-1,-1,0) glTexCoord2f(1,0) glVertex3f(1, -1, 0) glTexCoord2f(1,1) glVertex3f(1, 1, 0) glTexCoord2f(0,1) glVertex3f(-1, 1, 0) glEnd() glDisable(GL_TEXTURE_3D)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/tests/test_histogramlutwidget.py
.py
883
45
""" HistogramLUTWidget test: Tests the creation of a HistogramLUTWidget. """ import pyqtgraph as pg from pyqtgraph.Qt import QtGui import numpy as np def testHistogramLUTWidget(): pg.mkQApp() win = QtGui.QMainWindow() win.show() cw = QtGui.QWidget() win.setCentralWidget(cw) l = QtGui.QGridLayout() cw.setLayout(l) l.setSpacing(0) v = pg.GraphicsView() vb = pg.ViewBox() vb.setAspectLocked() v.setCentralItem(vb) l.addWidget(v, 0, 0, 3, 1) w = pg.HistogramLUTWidget(background='w') l.addWidget(w, 0, 1) data = pg.gaussianFilter(np.random.normal(size=(256, 256, 3)), (20, 20, 0)) for i in range(32): for j in range(32): data[i*8, j*8] += .1 img = pg.ImageItem(data) vb.addItem(img) vb.autoRange() w.setImageItem(img) QtGui.QApplication.processEvents()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/tests/test_spinbox.py
.py
1,552
42
import pyqtgraph as pg pg.mkQApp() def test_spinbox_formatting(): sb = pg.SpinBox() assert sb.opts['decimals'] == 6 assert sb.opts['int'] is False # table of test conditions: # value, text, options conds = [ (0, '0', dict(suffix='', siPrefix=False, dec=False, int=False)), (100, '100', dict()), (1000000, '1e+06', dict()), (1000, '1e+03', dict(decimals=2)), (1000000, '1e+06', dict(int=True, decimals=6)), (12345678955, '12345678955', dict(int=True, decimals=100)), (1.45e-9, '1.45e-09 A', dict(int=False, decimals=6, suffix='A', siPrefix=False)), (1.45e-9, '1.45 nA', dict(int=False, decimals=6, suffix='A', siPrefix=True)), (1.45, '1.45 PSI', dict(int=False, decimals=6, suffix='PSI', siPrefix=True)), (1.45e-3, '1.45 mPSI', dict(int=False, decimals=6, suffix='PSI', siPrefix=True)), (-2500.3427, '$-2500.34', dict(int=False, format='${value:0.02f}')), ] for (value, text, opts) in conds: sb.setOpts(**opts) sb.setValue(value) assert sb.value() == value assert pg.asUnicode(sb.text()) == text # test setting value if not opts.get('int', False): suf = sb.opts['suffix'] sb.lineEdit().setText('0.1' + suf) sb.editingFinishedEvent() assert sb.value() == 0.1 if suf != '': sb.lineEdit().setText('0.1 m' + suf) sb.editingFinishedEvent() assert sb.value() == 0.1e-3
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/tests/test_tablewidget.py
.py
3,967
129
import pyqtgraph as pg import numpy as np from pyqtgraph.pgcollections import OrderedDict app = pg.mkQApp() listOfTuples = [('text_%d' % i, i, i/9.) for i in range(12)] listOfLists = [list(row) for row in listOfTuples] plainArray = np.array(listOfLists, dtype=object) recordArray = np.array(listOfTuples, dtype=[('string', object), ('integer', int), ('floating', float)]) dictOfLists = OrderedDict([(name, list(recordArray[name])) for name in recordArray.dtype.names]) listOfDicts = [OrderedDict([(name, rec[name]) for name in recordArray.dtype.names]) for rec in recordArray] transposed = [[row[col] for row in listOfTuples] for col in range(len(listOfTuples[0]))] def assertTableData(table, data): assert len(data) == table.rowCount() rows = list(range(table.rowCount())) columns = list(range(table.columnCount())) for r in rows: assert len(data[r]) == table.columnCount() row = [] for c in columns: item = table.item(r, c) if item is not None: row.append(item.value) else: row.append(None) assert row == list(data[r]) 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)) if __name__ == '__main__': w = pg.TableWidget(editable=True) w.setData(listOfTuples) w.resize(600, 600) w.show()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/widgets/tests/test_combobox.py
.py
1,103
44
import pyqtgraph as pg pg.mkQApp() def test_combobox(): cb = pg.ComboBox() items = {'a': 1, 'b': 2, 'c': 3} cb.setItems(items) cb.setValue(2) assert str(cb.currentText()) == 'b' assert cb.value() == 2 # Clear item list; value should be None cb.clear() assert cb.value() == None # Reset item list; value should be set automatically cb.setItems(items) assert cb.value() == 2 # Clear item list; repopulate with same names and new values items = {'a': 4, 'b': 5, 'c': 6} cb.clear() cb.setItems(items) assert cb.value() == 5 # Set list instead of dict cb.setItems(list(items.keys())) assert str(cb.currentText()) == 'b' cb.setValue('c') assert cb.value() == str(cb.currentText()) assert cb.value() == 'c' cb.setItemValue('c', 7) assert cb.value() == 7 if __name__ == '__main__': cb = pg.ComboBox() cb.show() cb.setItems({'': None, 'a': 1, 'b': 2, 'c': 3}) def fn(ind): print("New value: %s" % cb.value()) cb.currentIndexChanged.connect(fn)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/opengl/MeshData.py
.py
22,204
507
import numpy as np from ..Qt import QtGui from .. import functions as fn from ..python2_3 import xrange class MeshData(object): """ Class for storing and operating on 3D mesh data. May contain: - list of vertex locations - list of edges - list of triangles - colors per vertex, edge, or tri - normals per vertex or tri This class handles conversion between the standard [list of vertexes, list of faces] format (suitable for use with glDrawElements) and 'indexed' [list of vertexes] format (suitable for use with glDrawArrays). It will automatically compute face normal vectors as well as averaged vertex normal vectors. The class attempts to be as efficient as possible in caching conversion results and avoiding unnecessary conversions. """ def __init__(self, vertexes=None, faces=None, edges=None, vertexColors=None, faceColors=None): """ ============== ===================================================== **Arguments:** vertexes (Nv, 3) array of vertex coordinates. If faces is not specified, then this will instead be interpreted as (Nf, 3, 3) array of coordinates. faces (Nf, 3) array of indexes into the vertex array. edges [not available yet] vertexColors (Nv, 4) array of vertex colors. If faces is not specified, then this will instead be interpreted as (Nf, 3, 4) array of colors. faceColors (Nf, 4) array of face colors. ============== ===================================================== All arguments are optional. """ self._vertexes = None # (Nv,3) array of vertex coordinates self._vertexesIndexedByFaces = None # (Nf, 3, 3) array of vertex coordinates self._vertexesIndexedByEdges = None # (Ne, 2, 3) array of vertex coordinates ## mappings between vertexes, faces, and edges self._faces = None # Nx3 array of indexes into self._vertexes specifying three vertexes for each face self._edges = None # Nx2 array of indexes into self._vertexes specifying two vertexes per edge self._vertexFaces = None ## maps vertex ID to a list of face IDs (inverse mapping of _faces) self._vertexEdges = None ## maps vertex ID to a list of edge IDs (inverse mapping of _edges) ## Per-vertex data self._vertexNormals = None # (Nv, 3) array of normals, one per vertex self._vertexNormalsIndexedByFaces = None # (Nf, 3, 3) array of normals self._vertexColors = None # (Nv, 3) array of colors self._vertexColorsIndexedByFaces = None # (Nf, 3, 4) array of colors self._vertexColorsIndexedByEdges = None # (Nf, 2, 4) array of colors ## Per-face data self._faceNormals = None # (Nf, 3) array of face normals self._faceNormalsIndexedByFaces = None # (Nf, 3, 3) array of face normals self._faceColors = None # (Nf, 4) array of face colors self._faceColorsIndexedByFaces = None # (Nf, 3, 4) array of face colors self._faceColorsIndexedByEdges = None # (Ne, 2, 4) array of face colors ## Per-edge data self._edgeColors = None # (Ne, 4) array of edge colors self._edgeColorsIndexedByEdges = None # (Ne, 2, 4) array of edge colors #self._meshColor = (1, 1, 1, 0.1) # default color to use if no face/edge/vertex colors are given if vertexes is not None: if faces is None: self.setVertexes(vertexes, indexed='faces') if vertexColors is not None: self.setVertexColors(vertexColors, indexed='faces') if faceColors is not None: self.setFaceColors(faceColors, indexed='faces') else: self.setVertexes(vertexes) self.setFaces(faces) if vertexColors is not None: self.setVertexColors(vertexColors) if faceColors is not None: self.setFaceColors(faceColors) def faces(self): """Return an array (Nf, 3) of vertex indexes, three per triangular face in the mesh. If faces have not been computed for this mesh, the function returns None. """ return self._faces def edges(self): """Return an array (Nf, 3) of vertex indexes, two per edge in the mesh.""" if self._edges is None: self._computeEdges() return self._edges def setFaces(self, faces): """Set the (Nf, 3) array of faces. Each rown in the array contains three indexes into the vertex array, specifying the three corners of a triangular face.""" self._faces = faces self._edges = None self._vertexFaces = None self._vertexesIndexedByFaces = None self.resetNormals() self._vertexColorsIndexedByFaces = None self._faceColorsIndexedByFaces = None def vertexes(self, indexed=None): """Return an array (N,3) of the positions of vertexes in the mesh. By default, each unique vertex appears only once in the array. If indexed is 'faces', then the array will instead contain three vertexes per face in the mesh (and a single vertex may appear more than once in the array).""" if indexed is None: if self._vertexes is None and self._vertexesIndexedByFaces is not None: self._computeUnindexedVertexes() return self._vertexes elif indexed == 'faces': if self._vertexesIndexedByFaces is None and self._vertexes is not None: self._vertexesIndexedByFaces = self._vertexes[self.faces()] return self._vertexesIndexedByFaces else: raise Exception("Invalid indexing mode. Accepts: None, 'faces'") def setVertexes(self, verts=None, indexed=None, resetNormals=True): """ Set the array (Nv, 3) of vertex coordinates. If indexed=='faces', then the data must have shape (Nf, 3, 3) and is assumed to be already indexed as a list of faces. This will cause any pre-existing normal vectors to be cleared unless resetNormals=False. """ if indexed is None: if verts is not None: self._vertexes = verts self._vertexesIndexedByFaces = None elif indexed=='faces': self._vertexes = None if verts is not None: self._vertexesIndexedByFaces = verts else: raise Exception("Invalid indexing mode. Accepts: None, 'faces'") if resetNormals: self.resetNormals() def resetNormals(self): self._vertexNormals = None self._vertexNormalsIndexedByFaces = None self._faceNormals = None self._faceNormalsIndexedByFaces = None def hasFaceIndexedData(self): """Return True if this object already has vertex positions indexed by face""" return self._vertexesIndexedByFaces is not None def hasEdgeIndexedData(self): return self._vertexesIndexedByEdges is not None def hasVertexColor(self): """Return True if this data set has vertex color information""" for v in (self._vertexColors, self._vertexColorsIndexedByFaces, self._vertexColorsIndexedByEdges): if v is not None: return True return False def hasFaceColor(self): """Return True if this data set has face color information""" for v in (self._faceColors, self._faceColorsIndexedByFaces, self._faceColorsIndexedByEdges): if v is not None: return True return False def faceNormals(self, indexed=None): """ Return an array (Nf, 3) of normal vectors for each face. If indexed='faces', then instead return an indexed array (Nf, 3, 3) (this is just the same array with each vector copied three times). """ if self._faceNormals is None: v = self.vertexes(indexed='faces') self._faceNormals = np.cross(v[:,1]-v[:,0], v[:,2]-v[:,0]) if indexed is None: return self._faceNormals elif indexed == 'faces': if self._faceNormalsIndexedByFaces is None: norms = np.empty((self._faceNormals.shape[0], 3, 3)) norms[:] = self._faceNormals[:,np.newaxis,:] self._faceNormalsIndexedByFaces = norms return self._faceNormalsIndexedByFaces else: raise Exception("Invalid indexing mode. Accepts: None, 'faces'") def vertexNormals(self, indexed=None): """ Return an array of normal vectors. By default, the array will be (N, 3) with one entry per unique vertex in the mesh. If indexed is 'faces', then the array will contain three normal vectors per face (and some vertexes may be repeated). """ if self._vertexNormals is None: faceNorms = self.faceNormals() vertFaces = self.vertexFaces() self._vertexNormals = np.empty(self._vertexes.shape, dtype=float) for vindex in xrange(self._vertexes.shape[0]): faces = vertFaces[vindex] if len(faces) == 0: self._vertexNormals[vindex] = (0,0,0) continue norms = faceNorms[faces] ## get all face normals norm = norms.sum(axis=0) ## sum normals norm /= (norm**2).sum()**0.5 ## and re-normalize self._vertexNormals[vindex] = norm if indexed is None: return self._vertexNormals elif indexed == 'faces': return self._vertexNormals[self.faces()] else: raise Exception("Invalid indexing mode. Accepts: None, 'faces'") def vertexColors(self, indexed=None): """ Return an array (Nv, 4) of vertex colors. If indexed=='faces', then instead return an indexed array (Nf, 3, 4). """ if indexed is None: return self._vertexColors elif indexed == 'faces': if self._vertexColorsIndexedByFaces is None: self._vertexColorsIndexedByFaces = self._vertexColors[self.faces()] return self._vertexColorsIndexedByFaces else: raise Exception("Invalid indexing mode. Accepts: None, 'faces'") def setVertexColors(self, colors, indexed=None): """ Set the vertex color array (Nv, 4). If indexed=='faces', then the array will be interpreted as indexed and should have shape (Nf, 3, 4) """ if indexed is None: self._vertexColors = colors self._vertexColorsIndexedByFaces = None elif indexed == 'faces': self._vertexColors = None self._vertexColorsIndexedByFaces = colors else: raise Exception("Invalid indexing mode. Accepts: None, 'faces'") def faceColors(self, indexed=None): """ Return an array (Nf, 4) of face colors. If indexed=='faces', then instead return an indexed array (Nf, 3, 4) (note this is just the same array with each color repeated three times). """ if indexed is None: return self._faceColors elif indexed == 'faces': if self._faceColorsIndexedByFaces is None and self._faceColors is not None: Nf = self._faceColors.shape[0] self._faceColorsIndexedByFaces = np.empty((Nf, 3, 4), dtype=self._faceColors.dtype) self._faceColorsIndexedByFaces[:] = self._faceColors.reshape(Nf, 1, 4) return self._faceColorsIndexedByFaces else: raise Exception("Invalid indexing mode. Accepts: None, 'faces'") def setFaceColors(self, colors, indexed=None): """ Set the face color array (Nf, 4). If indexed=='faces', then the array will be interpreted as indexed and should have shape (Nf, 3, 4) """ if indexed is None: self._faceColors = colors self._faceColorsIndexedByFaces = None elif indexed == 'faces': self._faceColors = None self._faceColorsIndexedByFaces = colors else: raise Exception("Invalid indexing mode. Accepts: None, 'faces'") def faceCount(self): """ Return the number of faces in the mesh. """ if self._faces is not None: return self._faces.shape[0] elif self._vertexesIndexedByFaces is not None: return self._vertexesIndexedByFaces.shape[0] def edgeColors(self): return self._edgeColors #def _setIndexedFaces(self, faces, vertexColors=None, faceColors=None): #self._vertexesIndexedByFaces = faces #self._vertexColorsIndexedByFaces = vertexColors #self._faceColorsIndexedByFaces = faceColors def _computeUnindexedVertexes(self): ## Given (Nv, 3, 3) array of vertexes-indexed-by-face, convert backward to unindexed vertexes ## This is done by collapsing into a list of 'unique' vertexes (difference < 1e-14) ## I think generally this should be discouraged.. faces = self._vertexesIndexedByFaces verts = {} ## used to remember the index of each vertex position self._faces = np.empty(faces.shape[:2], dtype=np.uint) self._vertexes = [] self._vertexFaces = [] self._faceNormals = None self._vertexNormals = None for i in xrange(faces.shape[0]): face = faces[i] inds = [] for j in range(face.shape[0]): pt = face[j] pt2 = tuple([round(x*1e14) for x in pt]) ## quantize to be sure that nearly-identical points will be merged index = verts.get(pt2, None) if index is None: #self._vertexes.append(QtGui.QVector3D(*pt)) self._vertexes.append(pt) self._vertexFaces.append([]) index = len(self._vertexes)-1 verts[pt2] = index self._vertexFaces[index].append(i) # keep track of which vertexes belong to which faces self._faces[i,j] = index self._vertexes = np.array(self._vertexes, dtype=float) #def _setUnindexedFaces(self, faces, vertexes, vertexColors=None, faceColors=None): #self._vertexes = vertexes #[QtGui.QVector3D(*v) for v in vertexes] #self._faces = faces.astype(np.uint) #self._edges = None #self._vertexFaces = None #self._faceNormals = None #self._vertexNormals = None #self._vertexColors = vertexColors #self._faceColors = faceColors def vertexFaces(self): """ Return list mapping each vertex index to a list of face indexes that use the vertex. """ if self._vertexFaces is None: self._vertexFaces = [[] for i in xrange(len(self.vertexes()))] for i in xrange(self._faces.shape[0]): face = self._faces[i] for ind in face: self._vertexFaces[ind].append(i) return self._vertexFaces #def reverseNormals(self): #""" #Reverses the direction of all normal vectors. #""" #pass #def generateEdgesFromFaces(self): #""" #Generate a set of edges by listing all the edges of faces and removing any duplicates. #Useful for displaying wireframe meshes. #""" #pass def _computeEdges(self): if not self.hasFaceIndexedData(): ## generate self._edges from self._faces nf = len(self._faces) edges = np.empty(nf*3, dtype=[('i', np.uint, 2)]) edges['i'][0:nf] = self._faces[:,:2] edges['i'][nf:2*nf] = self._faces[:,1:3] edges['i'][-nf:,0] = self._faces[:,2] edges['i'][-nf:,1] = self._faces[:,0] # sort per-edge mask = edges['i'][:,0] > edges['i'][:,1] edges['i'][mask] = edges['i'][mask][:,::-1] # remove duplicate entries self._edges = np.unique(edges)['i'] #print self._edges elif self._vertexesIndexedByFaces is not None: verts = self._vertexesIndexedByFaces edges = np.empty((verts.shape[0], 3, 2), dtype=np.uint) nf = verts.shape[0] edges[:,0,0] = np.arange(nf) * 3 edges[:,0,1] = edges[:,0,0] + 1 edges[:,1,0] = edges[:,0,1] edges[:,1,1] = edges[:,1,0] + 1 edges[:,2,0] = edges[:,1,1] edges[:,2,1] = edges[:,0,0] self._edges = edges else: raise Exception("MeshData cannot generate edges--no faces in this data.") def save(self): """Serialize this mesh to a string appropriate for disk storage""" import pickle if self._faces is not None: names = ['_vertexes', '_faces'] else: names = ['_vertexesIndexedByFaces'] if self._vertexColors is not None: names.append('_vertexColors') elif self._vertexColorsIndexedByFaces is not None: names.append('_vertexColorsIndexedByFaces') if self._faceColors is not None: names.append('_faceColors') elif self._faceColorsIndexedByFaces is not None: names.append('_faceColorsIndexedByFaces') state = dict([(n,getattr(self, n)) for n in names]) return pickle.dumps(state) def restore(self, state): """Restore the state of a mesh previously saved using save()""" import pickle state = pickle.loads(state) for k in state: if isinstance(state[k], list): if isinstance(state[k][0], QtGui.QVector3D): state[k] = [[v.x(), v.y(), v.z()] for v in state[k]] state[k] = np.array(state[k]) setattr(self, k, state[k]) @staticmethod def sphere(rows, cols, radius=1.0, offset=True): """ Return a MeshData instance with vertexes and faces computed for a spherical surface. """ verts = np.empty((rows+1, cols, 3), dtype=float) ## compute vertexes phi = (np.arange(rows+1) * np.pi / rows).reshape(rows+1, 1) s = radius * np.sin(phi) verts[...,2] = radius * np.cos(phi) th = ((np.arange(cols) * 2 * np.pi / cols).reshape(1, cols)) if offset: th = th + ((np.pi / cols) * np.arange(rows+1).reshape(rows+1,1)) ## rotate each row by 1/2 column verts[...,0] = s * np.cos(th) verts[...,1] = s * np.sin(th) verts = verts.reshape((rows+1)*cols, 3)[cols-1:-(cols-1)] ## remove redundant vertexes from top and bottom ## compute faces faces = np.empty((rows*cols*2, 3), dtype=np.uint) rowtemplate1 = ((np.arange(cols).reshape(cols, 1) + np.array([[0, 1, 0]])) % cols) + np.array([[0, 0, cols]]) rowtemplate2 = ((np.arange(cols).reshape(cols, 1) + np.array([[0, 1, 1]])) % cols) + np.array([[cols, 0, cols]]) for row in range(rows): start = row * cols * 2 faces[start:start+cols] = rowtemplate1 + row * cols faces[start+cols:start+(cols*2)] = rowtemplate2 + row * cols faces = faces[cols:-cols] ## cut off zero-area triangles at top and bottom ## adjust for redundant vertexes that were removed from top and bottom vmin = cols-1 faces[faces<vmin] = vmin faces -= vmin vmax = verts.shape[0]-1 faces[faces>vmax] = vmax return MeshData(vertexes=verts, faces=faces) @staticmethod def cylinder(rows, cols, radius=[1.0, 1.0], length=1.0, offset=False): """ Return a MeshData instance with vertexes and faces computed for a cylindrical surface. The cylinder may be tapered with different radii at each end (truncated cone) """ verts = np.empty((rows+1, cols, 3), dtype=float) if isinstance(radius, int): radius = [radius, radius] # convert to list ## compute vertexes th = np.linspace(2 * np.pi, (2 * np.pi)/cols, cols).reshape(1, cols) r = np.linspace(radius[0],radius[1],num=rows+1, endpoint=True).reshape(rows+1, 1) # radius as a function of z verts[...,2] = np.linspace(0, length, num=rows+1, endpoint=True).reshape(rows+1, 1) # z if offset: th = th + ((np.pi / cols) * np.arange(rows+1).reshape(rows+1,1)) ## rotate each row by 1/2 column verts[...,0] = r * np.cos(th) # x = r cos(th) verts[...,1] = r * np.sin(th) # y = r sin(th) verts = verts.reshape((rows+1)*cols, 3) # just reshape: no redundant vertices... ## compute faces faces = np.empty((rows*cols*2, 3), dtype=np.uint) rowtemplate1 = ((np.arange(cols).reshape(cols, 1) + np.array([[0, 1, 0]])) % cols) + np.array([[0, 0, cols]]) rowtemplate2 = ((np.arange(cols).reshape(cols, 1) + np.array([[0, 1, 1]])) % cols) + np.array([[cols, 0, cols]]) for row in range(rows): start = row * cols * 2 faces[start:start+cols] = rowtemplate1 + row * cols faces[start+cols:start+(cols*2)] = rowtemplate2 + row * cols return MeshData(vertexes=verts, faces=faces)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/opengl/__init__.py
.py
1,614
23
from .GLViewWidget import GLViewWidget ## dynamic imports cause too many problems. #from .. import importAll #importAll('items', globals(), locals()) from .items.GLGridItem import * from .items.GLBarGraphItem import * from .items.GLScatterPlotItem import * from .items.GLMeshItem import * from .items.GLLinePlotItem import * from .items.GLAxisItem import * from .items.GLImageItem import * from .items.GLSurfacePlotItem import * from .items.GLBoxItem import * from .items.GLVolumeItem import * from .MeshData import MeshData ## for backward compatibility: #MeshData.MeshData = MeshData ## breaks autodoc. from . import shaders
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/opengl/GLViewWidget.py
.py
20,770
518
from ..Qt import QtCore, QtGui, QtOpenGL, QT_LIB from OpenGL.GL import * import OpenGL.GL.framebufferobjects as glfbo import numpy as np from .. import Vector from .. import functions as fn ##Vector = QtGui.QVector3D ShareWidget = None class GLViewWidget(QtOpenGL.QGLWidget): """ Basic widget for displaying 3D data - Rotation/scale controls - Axis/grid display - Export options High-DPI displays: Qt5 should automatically detect the correct resolution. For Qt4, specify the ``devicePixelRatio`` argument when initializing the widget (usually this value is 1-2). """ def __init__(self, parent=None, devicePixelRatio=None): global ShareWidget if ShareWidget is None: ## create a dummy widget to allow sharing objects (textures, shaders, etc) between views ShareWidget = QtOpenGL.QGLWidget() QtOpenGL.QGLWidget.__init__(self, parent, ShareWidget) self.setFocusPolicy(QtCore.Qt.ClickFocus) self.opts = { 'center': Vector(0,0,0), ## will always appear at the center of the widget 'distance': 10.0, ## distance of camera from center 'fov': 60, ## horizontal field of view in degrees 'elevation': 30, ## camera's angle of elevation in degrees 'azimuth': 45, ## camera's azimuthal angle in degrees ## (rotation around z-axis 0 points along x-axis) 'viewport': None, ## glViewport params; None == whole widget 'devicePixelRatio': devicePixelRatio, } self.setBackgroundColor('k') self.items = [] self.noRepeatKeys = [QtCore.Qt.Key_Right, QtCore.Qt.Key_Left, QtCore.Qt.Key_Up, QtCore.Qt.Key_Down, QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown] self.keysPressed = {} self.keyTimer = QtCore.QTimer() self.keyTimer.timeout.connect(self.evalKeyState) self.makeCurrent() def addItem(self, item): self.items.append(item) if hasattr(item, 'initializeGL'): self.makeCurrent() try: item.initializeGL() except: self.checkOpenGLVersion('Error while adding item %s to GLViewWidget.' % str(item)) item._setView(self) #print "set view", item, self, item.view() self.update() def removeItem(self, item): self.items.remove(item) item._setView(None) self.update() def initializeGL(self): self.resizeGL(self.width(), self.height()) def setBackgroundColor(self, *args, **kwds): """ Set the background color of the widget. Accepts the same arguments as pg.mkColor() and pg.glColor(). """ self.opts['bgcolor'] = fn.glColor(*args, **kwds) self.update() def getViewport(self): vp = self.opts['viewport'] dpr = self.devicePixelRatio() if vp is None: return (0, 0, int(self.width() * dpr), int(self.height() * dpr)) else: return tuple([int(x * dpr) for x in vp]) def devicePixelRatio(self): dpr = self.opts['devicePixelRatio'] if dpr is not None: return dpr if hasattr(QtOpenGL.QGLWidget, 'devicePixelRatio'): return QtOpenGL.QGLWidget.devicePixelRatio(self) else: return 1.0 def resizeGL(self, w, h): pass #glViewport(*self.getViewport()) #self.update() def setProjection(self, region=None): m = self.projectionMatrix(region) glMatrixMode(GL_PROJECTION) glLoadIdentity() a = np.array(m.copyDataTo()).reshape((4,4)) glMultMatrixf(a.transpose()) def projectionMatrix(self, region=None): if region is None: dpr = self.devicePixelRatio() region = (0, 0, self.width() * dpr, self.height() * dpr) x0, y0, w, h = self.getViewport() dist = self.opts['distance'] fov = self.opts['fov'] nearClip = dist * 0.001 farClip = dist * 1000. r = nearClip * np.tan(fov * 0.5 * np.pi / 180.) t = r * h / w ## Note that X0 and width in these equations must be the values used in viewport left = r * ((region[0]-x0) * (2.0/w) - 1) right = r * ((region[0]+region[2]-x0) * (2.0/w) - 1) bottom = t * ((region[1]-y0) * (2.0/h) - 1) top = t * ((region[1]+region[3]-y0) * (2.0/h) - 1) tr = QtGui.QMatrix4x4() tr.frustum(left, right, bottom, top, nearClip, farClip) return tr def setModelview(self): glMatrixMode(GL_MODELVIEW) glLoadIdentity() m = self.viewMatrix() a = np.array(m.copyDataTo()).reshape((4,4)) glMultMatrixf(a.transpose()) def viewMatrix(self): tr = QtGui.QMatrix4x4() tr.translate( 0.0, 0.0, -self.opts['distance']) tr.rotate(self.opts['elevation']-90, 1, 0, 0) tr.rotate(self.opts['azimuth']+90, 0, 0, -1) center = self.opts['center'] tr.translate(-center.x(), -center.y(), -center.z()) return tr def itemsAt(self, region=None): """ Return a list of the items displayed in the region (x, y, w, h) relative to the widget. """ region = (region[0], self.height()-(region[1]+region[3]), region[2], region[3]) #buf = np.zeros(100000, dtype=np.uint) buf = glSelectBuffer(100000) try: glRenderMode(GL_SELECT) glInitNames() glPushName(0) self._itemNames = {} self.paintGL(region=region, useItemNames=True) finally: hits = glRenderMode(GL_RENDER) items = [(h.near, h.names[0]) for h in hits] items.sort(key=lambda i: i[0]) return [self._itemNames[i[1]] for i in items] def paintGL(self, region=None, viewport=None, useItemNames=False): """ viewport specifies the arguments to glViewport. If None, then we use self.opts['viewport'] region specifies the sub-region of self.opts['viewport'] that should be rendered. Note that we may use viewport != self.opts['viewport'] when exporting. """ if viewport is None: glViewport(*self.getViewport()) else: glViewport(*viewport) self.setProjection(region=region) self.setModelview() bgcolor = self.opts['bgcolor'] glClearColor(*bgcolor) glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT ) self.drawItemTree(useItemNames=useItemNames) def drawItemTree(self, item=None, useItemNames=False): if item is None: items = [x for x in self.items if x.parentItem() is None] else: items = item.childItems() items.append(item) items.sort(key=lambda a: a.depthValue()) for i in items: if not i.visible(): continue if i is item: try: glPushAttrib(GL_ALL_ATTRIB_BITS) if useItemNames: glLoadName(i._id) self._itemNames[i._id] = i i.paint() except: from .. import debug debug.printExc() msg = "Error while drawing item %s." % str(item) ver = glGetString(GL_VERSION) if ver is not None: ver = ver.split()[0] if int(ver.split(b'.')[0]) < 2: print(msg + " The original exception is printed above; however, pyqtgraph requires OpenGL version 2.0 or greater for many of its 3D features and your OpenGL version is %s. Installing updated display drivers may resolve this issue." % ver) else: print(msg) finally: glPopAttrib() else: glMatrixMode(GL_MODELVIEW) glPushMatrix() try: tr = i.transform() a = np.array(tr.copyDataTo()).reshape((4,4)) glMultMatrixf(a.transpose()) self.drawItemTree(i, useItemNames=useItemNames) finally: glMatrixMode(GL_MODELVIEW) glPopMatrix() def setCameraPosition(self, pos=None, distance=None, elevation=None, azimuth=None): if pos is not None: self.opts['center'] = pos if distance is not None: self.opts['distance'] = distance if elevation is not None: self.opts['elevation'] = elevation if azimuth is not None: self.opts['azimuth'] = azimuth self.update() def cameraPosition(self): """Return current position of camera based on center, dist, elevation, and azimuth""" center = self.opts['center'] dist = self.opts['distance'] elev = self.opts['elevation'] * np.pi/180. azim = self.opts['azimuth'] * np.pi/180. pos = Vector( center.x() + dist * np.cos(elev) * np.cos(azim), center.y() + dist * np.cos(elev) * np.sin(azim), center.z() + dist * np.sin(elev) ) return pos def orbit(self, azim, elev): """Orbits the camera around the center position. *azim* and *elev* are given in degrees.""" self.opts['azimuth'] += azim self.opts['elevation'] = np.clip(self.opts['elevation'] + elev, -90, 90) self.update() def pan(self, dx, dy, dz, relative='global'): """ Moves the center (look-at) position while holding the camera in place. ============== ======================================================= **Arguments:** *dx* Distance to pan in x direction *dy* Distance to pan in y direction *dx* Distance to pan in z direction *relative* String that determines the direction of dx,dy,dz. If "global", then the global coordinate system is used. If "view", then the z axis is aligned with the view direction, and x and y axes are inthe plane of the view: +x points right, +y points up. If "view-upright", then x is in the global xy plane and points to the right side of the view, y is in the global xy plane and orthogonal to x, and z points in the global z direction. ============== ======================================================= Distances are scaled roughly such that a value of 1.0 moves by one pixel on screen. Prior to version 0.11, *relative* was expected to be either True (x-aligned) or False (global). These values are deprecated but still recognized. """ # for backward compatibility: relative = {True: "view-upright", False: "global"}.get(relative, relative) if relative == 'global': self.opts['center'] += QtGui.QVector3D(dx, dy, dz) elif relative == 'view-upright': cPos = self.cameraPosition() cVec = self.opts['center'] - cPos dist = cVec.length() ## distance from camera to center xDist = dist * 2. * np.tan(0.5 * self.opts['fov'] * np.pi / 180.) ## approx. width of view at distance of center point xScale = xDist / self.width() zVec = QtGui.QVector3D(0,0,1) xVec = QtGui.QVector3D.crossProduct(zVec, cVec).normalized() yVec = QtGui.QVector3D.crossProduct(xVec, zVec).normalized() self.opts['center'] = self.opts['center'] + xVec * xScale * dx + yVec * xScale * dy + zVec * xScale * dz elif relative == 'view': # pan in plane of camera elev = np.radians(self.opts['elevation']) azim = np.radians(self.opts['azimuth']) fov = np.radians(self.opts['fov']) dist = (self.opts['center'] - self.cameraPosition()).length() fov_factor = np.tan(fov / 2) * 2 scale_factor = dist * fov_factor / self.width() z = scale_factor * np.cos(elev) * dy x = scale_factor * (np.sin(azim) * dx - np.sin(elev) * np.cos(azim) * dy) y = scale_factor * (np.cos(azim) * dx + np.sin(elev) * np.sin(azim) * dy) self.opts['center'] += QtGui.QVector3D(x, -y, z) else: raise ValueError("relative argument must be global, view, or view-upright") self.update() def pixelSize(self, pos): """ Return the approximate size of a screen pixel at the location pos Pos may be a Vector or an (N,3) array of locations """ cam = self.cameraPosition() if isinstance(pos, np.ndarray): cam = np.array(cam).reshape((1,)*(pos.ndim-1)+(3,)) dist = ((pos-cam)**2).sum(axis=-1)**0.5 else: dist = (pos-cam).length() xDist = dist * 2. * np.tan(0.5 * self.opts['fov'] * np.pi / 180.) return xDist / self.width() def mousePressEvent(self, ev): self.mousePos = ev.pos() def mouseMoveEvent(self, ev): diff = ev.pos() - self.mousePos self.mousePos = ev.pos() if ev.buttons() == QtCore.Qt.LeftButton: if (ev.modifiers() & QtCore.Qt.ControlModifier): self.pan(diff.x(), diff.y(), 0, relative='view') else: self.orbit(-diff.x(), diff.y()) elif ev.buttons() == QtCore.Qt.MidButton: if (ev.modifiers() & QtCore.Qt.ControlModifier): self.pan(diff.x(), 0, diff.y(), relative='view-upright') else: self.pan(diff.x(), diff.y(), 0, relative='view-upright') def mouseReleaseEvent(self, ev): pass # Example item selection code: #region = (ev.pos().x()-5, ev.pos().y()-5, 10, 10) #print(self.itemsAt(region)) ## debugging code: draw the picking region #glViewport(*self.getViewport()) #glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT ) #region = (region[0], self.height()-(region[1]+region[3]), region[2], region[3]) #self.paintGL(region=region) #self.swapBuffers() def wheelEvent(self, ev): delta = 0 if QT_LIB in ['PyQt4', 'PySide']: delta = ev.delta() else: delta = ev.angleDelta().x() if delta == 0: delta = ev.angleDelta().y() if (ev.modifiers() & QtCore.Qt.ControlModifier): self.opts['fov'] *= 0.999**delta else: self.opts['distance'] *= 0.999**delta self.update() def keyPressEvent(self, ev): if ev.key() in self.noRepeatKeys: ev.accept() if ev.isAutoRepeat(): return self.keysPressed[ev.key()] = 1 self.evalKeyState() def keyReleaseEvent(self, ev): if ev.key() in self.noRepeatKeys: ev.accept() if ev.isAutoRepeat(): return try: del self.keysPressed[ev.key()] except: self.keysPressed = {} self.evalKeyState() def evalKeyState(self): speed = 2.0 if len(self.keysPressed) > 0: for key in self.keysPressed: if key == QtCore.Qt.Key_Right: self.orbit(azim=-speed, elev=0) elif key == QtCore.Qt.Key_Left: self.orbit(azim=speed, elev=0) elif key == QtCore.Qt.Key_Up: self.orbit(azim=0, elev=-speed) elif key == QtCore.Qt.Key_Down: self.orbit(azim=0, elev=speed) elif key == QtCore.Qt.Key_PageUp: pass elif key == QtCore.Qt.Key_PageDown: pass self.keyTimer.start(16) else: self.keyTimer.stop() def checkOpenGLVersion(self, msg): ## Only to be called from within exception handler. ver = glGetString(GL_VERSION).split()[0] if int(ver.split(b'.')[0]) < 2: from .. import debug debug.printExc() raise Exception(msg + " The original exception is printed above; however, pyqtgraph requires OpenGL version 2.0 or greater for many of its 3D features and your OpenGL version is %s. Installing updated display drivers may resolve this issue." % ver) else: raise def readQImage(self): """ Read the current buffer pixels out as a QImage. """ w = self.width() h = self.height() self.repaint() pixels = np.empty((h, w, 4), dtype=np.ubyte) pixels[:] = 128 pixels[...,0] = 50 pixels[...,3] = 255 glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels) # swap B,R channels for Qt tmp = pixels[...,0].copy() pixels[...,0] = pixels[...,2] pixels[...,2] = tmp pixels = pixels[::-1] # flip vertical img = fn.makeQImage(pixels, transpose=False) return img def renderToArray(self, size, format=GL_BGRA, type=GL_UNSIGNED_BYTE, textureSize=1024, padding=256): w,h = map(int, size) self.makeCurrent() tex = None fb = None try: output = np.empty((w, h, 4), dtype=np.ubyte) fb = glfbo.glGenFramebuffers(1) glfbo.glBindFramebuffer(glfbo.GL_FRAMEBUFFER, fb ) glEnable(GL_TEXTURE_2D) tex = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, tex) texwidth = textureSize data = np.zeros((texwidth,texwidth,4), dtype=np.ubyte) ## Test texture dimensions first glTexImage2D(GL_PROXY_TEXTURE_2D, 0, GL_RGBA, texwidth, texwidth, 0, GL_RGBA, GL_UNSIGNED_BYTE, None) if glGetTexLevelParameteriv(GL_PROXY_TEXTURE_2D, 0, GL_TEXTURE_WIDTH) == 0: raise Exception("OpenGL failed to create 2D texture (%dx%d); too large for this hardware." % shape[:2]) ## create teture glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texwidth, texwidth, 0, GL_RGBA, GL_UNSIGNED_BYTE, data.transpose((1,0,2))) self.opts['viewport'] = (0, 0, w, h) # viewport is the complete image; this ensures that paintGL(region=...) # is interpreted correctly. p2 = 2 * padding for x in range(-padding, w-padding, texwidth-p2): for y in range(-padding, h-padding, texwidth-p2): x2 = min(x+texwidth, w+padding) y2 = min(y+texwidth, h+padding) w2 = x2-x h2 = y2-y ## render to texture glfbo.glFramebufferTexture2D(glfbo.GL_FRAMEBUFFER, glfbo.GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex, 0) self.paintGL(region=(x, h-y-h2, w2, h2), viewport=(0, 0, w2, h2)) # only render sub-region glBindTexture(GL_TEXTURE_2D, tex) # fixes issue #366 ## read texture back to array data = glGetTexImage(GL_TEXTURE_2D, 0, format, type) data = np.fromstring(data, dtype=np.ubyte).reshape(texwidth,texwidth,4).transpose(1,0,2)[:, ::-1] output[x+padding:x2-padding, y+padding:y2-padding] = data[padding:w2-padding, -(h2-padding):-padding] finally: self.opts['viewport'] = None glfbo.glBindFramebuffer(glfbo.GL_FRAMEBUFFER, 0) glBindTexture(GL_TEXTURE_2D, 0) if tex is not None: glDeleteTextures([tex]) if fb is not None: glfbo.glDeleteFramebuffers([fb]) return output
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/opengl/shaders.py
.py
16,009
403
try: from OpenGL import NullFunctionError except ImportError: from OpenGL.error import NullFunctionError from OpenGL.GL import * from OpenGL.GL import shaders import re ## For centralizing and managing vertex/fragment shader programs. def initShaders(): global Shaders Shaders = [ ShaderProgram(None, []), ## increases fragment alpha as the normal turns orthogonal to the view ## this is useful for viewing shells that enclose a volume (such as isosurfaces) ShaderProgram('balloon', [ VertexShader(""" varying vec3 normal; void main() { // compute here for use in fragment shader normal = normalize(gl_NormalMatrix * gl_Normal); gl_FrontColor = gl_Color; gl_BackColor = gl_Color; gl_Position = ftransform(); } """), FragmentShader(""" varying vec3 normal; void main() { vec4 color = gl_Color; color.w = min(color.w + 2.0 * color.w * pow(normal.x*normal.x + normal.y*normal.y, 5.0), 1.0); gl_FragColor = color; } """) ]), ## colors fragments based on face normals relative to view ## This means that the colors will change depending on how the view is rotated ShaderProgram('viewNormalColor', [ VertexShader(""" varying vec3 normal; void main() { // compute here for use in fragment shader normal = normalize(gl_NormalMatrix * gl_Normal); gl_FrontColor = gl_Color; gl_BackColor = gl_Color; gl_Position = ftransform(); } """), FragmentShader(""" varying vec3 normal; void main() { vec4 color = gl_Color; color.x = (normal.x + 1.0) * 0.5; color.y = (normal.y + 1.0) * 0.5; color.z = (normal.z + 1.0) * 0.5; gl_FragColor = color; } """) ]), ## colors fragments based on absolute face normals. ShaderProgram('normalColor', [ VertexShader(""" varying vec3 normal; void main() { // compute here for use in fragment shader normal = normalize(gl_Normal); gl_FrontColor = gl_Color; gl_BackColor = gl_Color; gl_Position = ftransform(); } """), FragmentShader(""" varying vec3 normal; void main() { vec4 color = gl_Color; color.x = (normal.x + 1.0) * 0.5; color.y = (normal.y + 1.0) * 0.5; color.z = (normal.z + 1.0) * 0.5; gl_FragColor = color; } """) ]), ## very simple simulation of lighting. ## The light source position is always relative to the camera. ShaderProgram('shaded', [ VertexShader(""" varying vec3 normal; void main() { // compute here for use in fragment shader normal = normalize(gl_NormalMatrix * gl_Normal); gl_FrontColor = gl_Color; gl_BackColor = gl_Color; gl_Position = ftransform(); } """), FragmentShader(""" varying vec3 normal; void main() { float p = dot(normal, normalize(vec3(1.0, -1.0, -1.0))); p = p < 0. ? 0. : p * 0.8; vec4 color = gl_Color; color.x = color.x * (0.2 + p); color.y = color.y * (0.2 + p); color.z = color.z * (0.2 + p); gl_FragColor = color; } """) ]), ## colors get brighter near edges of object ShaderProgram('edgeHilight', [ VertexShader(""" varying vec3 normal; void main() { // compute here for use in fragment shader normal = normalize(gl_NormalMatrix * gl_Normal); gl_FrontColor = gl_Color; gl_BackColor = gl_Color; gl_Position = ftransform(); } """), FragmentShader(""" varying vec3 normal; void main() { vec4 color = gl_Color; float s = pow(normal.x*normal.x + normal.y*normal.y, 2.0); color.x = color.x + s * (1.0-color.x); color.y = color.y + s * (1.0-color.y); color.z = color.z + s * (1.0-color.z); gl_FragColor = color; } """) ]), ## colors fragments by z-value. ## This is useful for coloring surface plots by height. ## This shader uses a uniform called "colorMap" to determine how to map the colors: ## red = pow(colorMap[0]*(z + colorMap[1]), colorMap[2]) ## green = pow(colorMap[3]*(z + colorMap[4]), colorMap[5]) ## blue = pow(colorMap[6]*(z + colorMap[7]), colorMap[8]) ## (set the values like this: shader['uniformMap'] = array([...]) ShaderProgram('heightColor', [ VertexShader(""" varying vec4 pos; void main() { gl_FrontColor = gl_Color; gl_BackColor = gl_Color; pos = gl_Vertex; gl_Position = ftransform(); } """), FragmentShader(""" uniform float colorMap[9]; varying vec4 pos; //out vec4 gl_FragColor; // only needed for later glsl versions //in vec4 gl_Color; void main() { vec4 color = gl_Color; color.x = colorMap[0] * (pos.z + colorMap[1]); if (colorMap[2] != 1.0) color.x = pow(color.x, colorMap[2]); color.x = color.x < 0. ? 0. : (color.x > 1. ? 1. : color.x); color.y = colorMap[3] * (pos.z + colorMap[4]); if (colorMap[5] != 1.0) color.y = pow(color.y, colorMap[5]); color.y = color.y < 0. ? 0. : (color.y > 1. ? 1. : color.y); color.z = colorMap[6] * (pos.z + colorMap[7]); if (colorMap[8] != 1.0) color.z = pow(color.z, colorMap[8]); color.z = color.z < 0. ? 0. : (color.z > 1. ? 1. : color.z); color.w = 1.0; gl_FragColor = color; } """), ], uniforms={'colorMap': [1, 1, 1, 1, 0.5, 1, 1, 0, 1]}), ShaderProgram('pointSprite', [ ## allows specifying point size using normal.x ## See: ## ## http://stackoverflow.com/questions/9609423/applying-part-of-a-texture-sprite-sheet-texture-map-to-a-point-sprite-in-ios ## http://stackoverflow.com/questions/3497068/textured-points-in-opengl-es-2-0 ## ## VertexShader(""" void main() { gl_FrontColor=gl_Color; gl_PointSize = gl_Normal.x; gl_Position = ftransform(); } """), #FragmentShader(""" ##version 120 #uniform sampler2D texture; #void main ( ) #{ #gl_FragColor = texture2D(texture, gl_PointCoord) * gl_Color; #} #""") ]), ] CompiledShaderPrograms = {} def getShaderProgram(name): return ShaderProgram.names[name] class Shader(object): def __init__(self, shaderType, code): self.shaderType = shaderType self.code = code self.compiled = None def shader(self): if self.compiled is None: try: self.compiled = shaders.compileShader(self.code, self.shaderType) except NullFunctionError: raise Exception("This OpenGL implementation does not support shader programs; many OpenGL features in pyqtgraph will not work.") except RuntimeError as exc: ## Format compile errors a bit more nicely if len(exc.args) == 3: err, code, typ = exc.args if not err.startswith('Shader compile failure'): raise code = code[0].decode('utf_8').split('\n') err, c, msgs = err.partition(':') err = err + '\n' msgs = re.sub('b\'','',msgs) msgs = re.sub('\'$','',msgs) msgs = re.sub('\\\\n','\n',msgs) msgs = msgs.split('\n') errNums = [()] * len(code) for i, msg in enumerate(msgs): msg = msg.strip() if msg == '': continue m = re.match(r'(\d+\:)?\d+\((\d+)\)', msg) if m is not None: line = int(m.groups()[1]) errNums[line-1] = errNums[line-1] + (str(i+1),) #code[line-1] = '%d\t%s' % (i+1, code[line-1]) err = err + "%d %s\n" % (i+1, msg) errNums = [','.join(n) for n in errNums] maxlen = max(map(len, errNums)) code = [errNums[i] + " "*(maxlen-len(errNums[i])) + line for i, line in enumerate(code)] err = err + '\n'.join(code) raise Exception(err) else: raise return self.compiled class VertexShader(Shader): def __init__(self, code): Shader.__init__(self, GL_VERTEX_SHADER, code) class FragmentShader(Shader): def __init__(self, code): Shader.__init__(self, GL_FRAGMENT_SHADER, code) class ShaderProgram(object): names = {} def __init__(self, name, shaders, uniforms=None): self.name = name ShaderProgram.names[name] = self self.shaders = shaders self.prog = None self.blockData = {} self.uniformData = {} ## parse extra options from the shader definition if uniforms is not None: for k,v in uniforms.items(): self[k] = v def setBlockData(self, blockName, data): if data is None: del self.blockData[blockName] else: self.blockData[blockName] = data def setUniformData(self, uniformName, data): if data is None: del self.uniformData[uniformName] else: self.uniformData[uniformName] = data def __setitem__(self, item, val): self.setUniformData(item, val) def __delitem__(self, item): self.setUniformData(item, None) def program(self): if self.prog is None: try: compiled = [s.shader() for s in self.shaders] ## compile all shaders self.prog = shaders.compileProgram(*compiled) ## compile program except: self.prog = -1 raise return self.prog def __enter__(self): if len(self.shaders) > 0 and self.program() != -1: glUseProgram(self.program()) try: ## load uniform values into program for uniformName, data in self.uniformData.items(): loc = self.uniform(uniformName) if loc == -1: raise Exception('Could not find uniform variable "%s"' % uniformName) glUniform1fv(loc, len(data), data) ### bind buffer data to program blocks #if len(self.blockData) > 0: #bindPoint = 1 #for blockName, data in self.blockData.items(): ### Program should have a uniform block declared: ### ### layout (std140) uniform blockName { ### vec4 diffuse; ### }; ### pick any-old binding point. (there are a limited number of these per-program #bindPoint = 1 ### get the block index for a uniform variable in the shader #blockIndex = glGetUniformBlockIndex(self.program(), blockName) ### give the shader block a binding point #glUniformBlockBinding(self.program(), blockIndex, bindPoint) ### create a buffer #buf = glGenBuffers(1) #glBindBuffer(GL_UNIFORM_BUFFER, buf) #glBufferData(GL_UNIFORM_BUFFER, size, data, GL_DYNAMIC_DRAW) ### also possible to use glBufferSubData to fill parts of the buffer ### bind buffer to the same binding point #glBindBufferBase(GL_UNIFORM_BUFFER, bindPoint, buf) except: glUseProgram(0) raise def __exit__(self, *args): if len(self.shaders) > 0: glUseProgram(0) def uniform(self, name): """Return the location integer for a uniform variable in this program""" return glGetUniformLocation(self.program(), name.encode('utf_8')) #def uniformBlockInfo(self, blockName): #blockIndex = glGetUniformBlockIndex(self.program(), blockName) #count = glGetActiveUniformBlockiv(self.program(), blockIndex, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS) #indices = [] #for i in range(count): #indices.append(glGetActiveUniformBlockiv(self.program(), blockIndex, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES)) class HeightColorShader(ShaderProgram): def __enter__(self): ## Program should have a uniform block declared: ## ## layout (std140) uniform blockName { ## vec4 diffuse; ## vec4 ambient; ## }; ## pick any-old binding point. (there are a limited number of these per-program bindPoint = 1 ## get the block index for a uniform variable in the shader blockIndex = glGetUniformBlockIndex(self.program(), "blockName") ## give the shader block a binding point glUniformBlockBinding(self.program(), blockIndex, bindPoint) ## create a buffer buf = glGenBuffers(1) glBindBuffer(GL_UNIFORM_BUFFER, buf) glBufferData(GL_UNIFORM_BUFFER, size, data, GL_DYNAMIC_DRAW) ## also possible to use glBufferSubData to fill parts of the buffer ## bind buffer to the same binding point glBindBufferBase(GL_UNIFORM_BUFFER, bindPoint, buf) initShaders()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/opengl/glInfo.py
.py
555
17
from ..Qt import QtCore, QtGui, QtOpenGL from OpenGL.GL import * app = QtGui.QApplication([]) class GLTest(QtOpenGL.QGLWidget): def __init__(self): QtOpenGL.QGLWidget.__init__(self) self.makeCurrent() print("GL version:" + glGetString(GL_VERSION).decode("utf-8")) print("MAX_TEXTURE_SIZE: %d" % glGetIntegerv(GL_MAX_TEXTURE_SIZE)) print("MAX_3D_TEXTURE_SIZE: %d" % glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE)) print("Extensions: " + glGetString(GL_EXTENSIONS).decode("utf-8").replace(" ", "\n")) GLTest()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/opengl/GLGraphicsItem.py
.py
10,090
300
from OpenGL.GL import * from OpenGL import GL from ..Qt import QtGui, QtCore from .. import Transform3D from ..python2_3 import basestring GLOptions = { 'opaque': { GL_DEPTH_TEST: True, GL_BLEND: False, GL_ALPHA_TEST: False, GL_CULL_FACE: False, }, 'translucent': { GL_DEPTH_TEST: True, GL_BLEND: True, GL_ALPHA_TEST: False, GL_CULL_FACE: False, 'glBlendFunc': (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA), }, 'additive': { GL_DEPTH_TEST: False, GL_BLEND: True, GL_ALPHA_TEST: False, GL_CULL_FACE: False, 'glBlendFunc': (GL_SRC_ALPHA, GL_ONE), }, } class GLGraphicsItem(QtCore.QObject): _nextId = 0 def __init__(self, parentItem=None): QtCore.QObject.__init__(self) self._id = GLGraphicsItem._nextId GLGraphicsItem._nextId += 1 self.__parent = None self.__view = None self.__children = set() self.__transform = Transform3D() self.__visible = True self.setParentItem(parentItem) self.setDepthValue(0) self.__glOpts = {} def setParentItem(self, item): """Set this item's parent in the scenegraph hierarchy.""" if self.__parent is not None: self.__parent.__children.remove(self) if item is not None: item.__children.add(self) self.__parent = item if self.__parent is not None and self.view() is not self.__parent.view(): if self.view() is not None: self.view().removeItem(self) self.__parent.view().addItem(self) def setGLOptions(self, opts): """ Set the OpenGL state options to use immediately before drawing this item. (Note that subclasses must call setupGLState before painting for this to work) The simplest way to invoke this method is to pass in the name of a predefined set of options (see the GLOptions variable): ============= ====================================================== opaque Enables depth testing and disables blending translucent Enables depth testing and blending Elements must be drawn sorted back-to-front for translucency to work correctly. additive Disables depth testing, enables blending. Colors are added together, so sorting is not required. ============= ====================================================== It is also possible to specify any arbitrary settings as a dictionary. This may consist of {'functionName': (args...)} pairs where functionName must be a callable attribute of OpenGL.GL, or {GL_STATE_VAR: bool} pairs which will be interpreted as calls to glEnable or glDisable(GL_STATE_VAR). For example:: { GL_ALPHA_TEST: True, GL_CULL_FACE: False, 'glBlendFunc': (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA), } """ if isinstance(opts, basestring): opts = GLOptions[opts] self.__glOpts = opts.copy() self.update() def updateGLOptions(self, opts): """ Modify the OpenGL state options to use immediately before drawing this item. *opts* must be a dictionary as specified by setGLOptions. Values may also be None, in which case the key will be ignored. """ self.__glOpts.update(opts) def parentItem(self): """Return a this item's parent in the scenegraph hierarchy.""" return self.__parent def childItems(self): """Return a list of this item's children in the scenegraph hierarchy.""" return list(self.__children) def _setView(self, v): self.__view = v def view(self): return self.__view def setDepthValue(self, value): """ Sets the depth value of this item. Default is 0. This controls the order in which items are drawn--those with a greater depth value will be drawn later. Items with negative depth values are drawn before their parent. (This is analogous to QGraphicsItem.zValue) The depthValue does NOT affect the position of the item or the values it imparts to the GL depth buffer. """ self.__depthValue = value def depthValue(self): """Return the depth value of this item. See setDepthValue for more information.""" return self.__depthValue def setTransform(self, tr): """Set the local transform for this object. Must be a :class:`Transform3D <pyqtgraph.Transform3D>` instance. This transform determines how the local coordinate system of the item is mapped to the coordinate system of its parent.""" self.__transform = Transform3D(tr) self.update() def resetTransform(self): """Reset this item's transform to an identity transformation.""" self.__transform.setToIdentity() self.update() def applyTransform(self, tr, local): """ Multiply this object's transform by *tr*. If local is True, then *tr* is multiplied on the right of the current transform:: newTransform = transform * tr If local is False, then *tr* is instead multiplied on the left:: newTransform = tr * transform """ if local: self.setTransform(self.transform() * tr) else: self.setTransform(tr * self.transform()) def transform(self): """Return this item's transform object.""" return self.__transform def viewTransform(self): """Return the transform mapping this item's local coordinate system to the view coordinate system.""" tr = self.__transform p = self while True: p = p.parentItem() if p is None: break tr = p.transform() * tr return Transform3D(tr) def translate(self, dx, dy, dz, local=False): """ Translate the object by (*dx*, *dy*, *dz*) in its parent's coordinate system. If *local* is True, then translation takes place in local coordinates. """ tr = Transform3D() tr.translate(dx, dy, dz) self.applyTransform(tr, local=local) def rotate(self, angle, x, y, z, local=False): """ Rotate the object around the axis specified by (x,y,z). *angle* is in degrees. """ tr = Transform3D() tr.rotate(angle, x, y, z) self.applyTransform(tr, local=local) def scale(self, x, y, z, local=True): """ Scale the object by (*dx*, *dy*, *dz*) in its local coordinate system. If *local* is False, then scale takes place in the parent's coordinates. """ tr = Transform3D() tr.scale(x, y, z) self.applyTransform(tr, local=local) def hide(self): """Hide this item. This is equivalent to setVisible(False).""" self.setVisible(False) def show(self): """Make this item visible if it was previously hidden. This is equivalent to setVisible(True).""" self.setVisible(True) def setVisible(self, vis): """Set the visibility of this item.""" self.__visible = vis self.update() def visible(self): """Return True if the item is currently set to be visible. Note that this does not guarantee that the item actually appears in the view, as it may be obscured or outside of the current view area.""" return self.__visible def initializeGL(self): """ Called after an item is added to a GLViewWidget. The widget's GL context is made current before this method is called. (So this would be an appropriate time to generate lists, upload textures, etc.) """ pass def setupGLState(self): """ This method is responsible for preparing the GL state options needed to render this item (blending, depth testing, etc). The method is called immediately before painting the item. """ for k,v in self.__glOpts.items(): if v is None: continue if isinstance(k, basestring): func = getattr(GL, k) func(*v) else: if v is True: glEnable(k) else: glDisable(k) def paint(self): """ Called by the GLViewWidget to draw this item. It is the responsibility of the item to set up its own modelview matrix, but the caller will take care of pushing/popping. """ self.setupGLState() def update(self): """ Indicates that this item needs to be redrawn, and schedules an update with the view it is displayed in. """ v = self.view() if v is None: return v.update() def mapToParent(self, point): tr = self.transform() if tr is None: return point return tr.map(point) def mapFromParent(self, point): tr = self.transform() if tr is None: return point return tr.inverted()[0].map(point) def mapToView(self, point): tr = self.viewTransform() if tr is None: return point return tr.map(point) def mapFromView(self, point): tr = self.viewTransform() if tr is None: return point return tr.inverted()[0].map(point)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/opengl/items/GLBarGraphItem.py
.py
1,014
27
from .GLMeshItem import GLMeshItem from ..MeshData import MeshData import numpy as np class GLBarGraphItem(GLMeshItem): def __init__(self, pos, size): """ pos is (...,3) array of the bar positions (the corner of each bar) size is (...,3) array of the sizes of each bar """ nCubes = np.prod(pos.shape[:-1]) cubeVerts = np.mgrid[0:2,0:2,0:2].reshape(3,8).transpose().reshape(1,8,3) cubeFaces = np.array([ [0,1,2], [3,2,1], [4,5,6], [7,6,5], [0,1,4], [5,4,1], [2,3,6], [7,6,3], [0,2,4], [6,4,2], [1,3,5], [7,5,3]]).reshape(1,12,3) size = size.reshape((nCubes, 1, 3)) pos = pos.reshape((nCubes, 1, 3)) verts = cubeVerts * size + pos faces = cubeFaces + (np.arange(nCubes) * 8).reshape(nCubes,1,1) md = MeshData(verts.reshape(nCubes*8,3), faces.reshape(nCubes*12,3)) GLMeshItem.__init__(self, meshdata=md, shader='shaded', smooth=False)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/opengl/items/GLVolumeItem.py
.py
7,658
231
from OpenGL.GL import * from .. GLGraphicsItem import GLGraphicsItem from ...Qt import QtGui import numpy as np from ... import debug __all__ = ['GLVolumeItem'] class GLVolumeItem(GLGraphicsItem): """ **Bases:** :class:`GLGraphicsItem <pyqtgraph.opengl.GLGraphicsItem>` Displays volumetric data. """ def __init__(self, data, sliceDensity=1, smooth=True, glOptions='translucent'): """ ============== ======================================================================================= **Arguments:** data Volume data to be rendered. *Must* be 4D numpy array (x, y, z, RGBA) with dtype=ubyte. sliceDensity Density of slices to render through the volume. A value of 1 means one slice per voxel. smooth (bool) If True, the volume slices are rendered with linear interpolation ============== ======================================================================================= """ self.sliceDensity = sliceDensity self.smooth = smooth self.data = None self._needUpload = False self.texture = None GLGraphicsItem.__init__(self) self.setGLOptions(glOptions) self.setData(data) def setData(self, data): self.data = data self._needUpload = True self.update() def _uploadData(self): glEnable(GL_TEXTURE_3D) if self.texture is None: self.texture = glGenTextures(1) glBindTexture(GL_TEXTURE_3D, self.texture) if self.smooth: glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) else: glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER) glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER) glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER) shape = self.data.shape ## Test texture dimensions first glTexImage3D(GL_PROXY_TEXTURE_3D, 0, GL_RGBA, shape[0], shape[1], shape[2], 0, GL_RGBA, GL_UNSIGNED_BYTE, None) if glGetTexLevelParameteriv(GL_PROXY_TEXTURE_3D, 0, GL_TEXTURE_WIDTH) == 0: raise Exception("OpenGL failed to create 3D texture (%dx%dx%d); too large for this hardware." % shape[:3]) glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA, shape[0], shape[1], shape[2], 0, GL_RGBA, GL_UNSIGNED_BYTE, self.data.transpose((2,1,0,3))) glDisable(GL_TEXTURE_3D) self.lists = {} for ax in [0,1,2]: for d in [-1, 1]: l = glGenLists(1) self.lists[(ax,d)] = l glNewList(l, GL_COMPILE) self.drawVolume(ax, d) glEndList() self._needUpload = False def paint(self): if self.data is None: return if self._needUpload: self._uploadData() self.setupGLState() glEnable(GL_TEXTURE_3D) glBindTexture(GL_TEXTURE_3D, self.texture) #glEnable(GL_DEPTH_TEST) #glDisable(GL_CULL_FACE) #glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) #glEnable( GL_BLEND ) #glEnable( GL_ALPHA_TEST ) glColor4f(1,1,1,1) view = self.view() center = QtGui.QVector3D(*[x/2. for x in self.data.shape[:3]]) cam = self.mapFromParent(view.cameraPosition()) - center #print "center", center, "cam", view.cameraPosition(), self.mapFromParent(view.cameraPosition()), "diff", cam cam = np.array([cam.x(), cam.y(), cam.z()]) ax = np.argmax(abs(cam)) d = 1 if cam[ax] > 0 else -1 glCallList(self.lists[(ax,d)]) ## draw axes glDisable(GL_TEXTURE_3D) def drawVolume(self, ax, d): N = 5 imax = [0,1,2] imax.remove(ax) tp = [[0,0,0],[0,0,0],[0,0,0],[0,0,0]] vp = [[0,0,0],[0,0,0],[0,0,0],[0,0,0]] nudge = [0.5/x for x in self.data.shape] tp[0][imax[0]] = 0+nudge[imax[0]] tp[0][imax[1]] = 0+nudge[imax[1]] tp[1][imax[0]] = 1-nudge[imax[0]] tp[1][imax[1]] = 0+nudge[imax[1]] tp[2][imax[0]] = 1-nudge[imax[0]] tp[2][imax[1]] = 1-nudge[imax[1]] tp[3][imax[0]] = 0+nudge[imax[0]] tp[3][imax[1]] = 1-nudge[imax[1]] vp[0][imax[0]] = 0 vp[0][imax[1]] = 0 vp[1][imax[0]] = self.data.shape[imax[0]] vp[1][imax[1]] = 0 vp[2][imax[0]] = self.data.shape[imax[0]] vp[2][imax[1]] = self.data.shape[imax[1]] vp[3][imax[0]] = 0 vp[3][imax[1]] = self.data.shape[imax[1]] slices = self.data.shape[ax] * self.sliceDensity r = list(range(slices)) if d == -1: r = r[::-1] glBegin(GL_QUADS) tzVals = np.linspace(nudge[ax], 1.0-nudge[ax], slices) vzVals = np.linspace(0, self.data.shape[ax], slices) for i in r: z = tzVals[i] w = vzVals[i] tp[0][ax] = z tp[1][ax] = z tp[2][ax] = z tp[3][ax] = z vp[0][ax] = w vp[1][ax] = w vp[2][ax] = w vp[3][ax] = w glTexCoord3f(*tp[0]) glVertex3f(*vp[0]) glTexCoord3f(*tp[1]) glVertex3f(*vp[1]) glTexCoord3f(*tp[2]) glVertex3f(*vp[2]) glTexCoord3f(*tp[3]) glVertex3f(*vp[3]) glEnd() ## Interesting idea: ## remove projection/modelview matrixes, recreate in texture coords. ## it _sorta_ works, but needs tweaking. #mvm = glGetDoublev(GL_MODELVIEW_MATRIX) #pm = glGetDoublev(GL_PROJECTION_MATRIX) #m = QtGui.QMatrix4x4(mvm.flatten()).inverted()[0] #p = QtGui.QMatrix4x4(pm.flatten()).inverted()[0] #glMatrixMode(GL_PROJECTION) #glPushMatrix() #glLoadIdentity() #N=1 #glOrtho(-N,N,-N,N,-100,100) #glMatrixMode(GL_MODELVIEW) #glLoadIdentity() #glMatrixMode(GL_TEXTURE) #glLoadIdentity() #glMultMatrixf(m.copyDataTo()) #view = self.view() #w = view.width() #h = view.height() #dist = view.opts['distance'] #fov = view.opts['fov'] #nearClip = dist * .1 #farClip = dist * 5. #r = nearClip * np.tan(fov) #t = r * h / w #p = QtGui.QMatrix4x4() #p.frustum( -r, r, -t, t, nearClip, farClip) #glMultMatrixf(p.inverted()[0].copyDataTo()) #glBegin(GL_QUADS) #M=1 #for i in range(500): #z = i/500. #w = -i/500. #glTexCoord3f(-M, -M, z) #glVertex3f(-N, -N, w) #glTexCoord3f(M, -M, z) #glVertex3f(N, -N, w) #glTexCoord3f(M, M, z) #glVertex3f(N, N, w) #glTexCoord3f(-M, M, z) #glVertex3f(-N, N, w) #glEnd() #glDisable(GL_TEXTURE_3D) #glMatrixMode(GL_PROJECTION) #glPopMatrix()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/opengl/items/GLAxisItem.py
.py
1,792
65
from OpenGL.GL import * from .. GLGraphicsItem import GLGraphicsItem from ... import QtGui __all__ = ['GLAxisItem'] class GLAxisItem(GLGraphicsItem): """ **Bases:** :class:`GLGraphicsItem <pyqtgraph.opengl.GLGraphicsItem>` Displays three lines indicating origin and orientation of local coordinate system. """ def __init__(self, size=None, antialias=True, glOptions='translucent'): GLGraphicsItem.__init__(self) if size is None: size = QtGui.QVector3D(1,1,1) self.antialias = antialias self.setSize(size=size) self.setGLOptions(glOptions) def setSize(self, x=None, y=None, z=None, size=None): """ Set the size of the axes (in its local coordinate system; this does not affect the transform) Arguments can be x,y,z or size=QVector3D(). """ if size is not None: x = size.x() y = size.y() z = size.z() self.__size = [x,y,z] self.update() def size(self): return self.__size[:] def paint(self): #glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) #glEnable( GL_BLEND ) #glEnable( GL_ALPHA_TEST ) self.setupGLState() if self.antialias: glEnable(GL_LINE_SMOOTH) glHint(GL_LINE_SMOOTH_HINT, GL_NICEST) glBegin( GL_LINES ) x,y,z = self.size() glColor4f(0, 1, 0, .6) # z is green glVertex3f(0, 0, 0) glVertex3f(0, 0, z) glColor4f(1, 1, 0, .6) # y is yellow glVertex3f(0, 0, 0) glVertex3f(0, y, 0) glColor4f(0, 0, 1, .6) # x is blue glVertex3f(0, 0, 0) glVertex3f(x, 0, 0) glEnd()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/opengl/items/GLScatterPlotItem.py
.py
7,570
189
from OpenGL.GL import * from OpenGL.arrays import vbo from .. GLGraphicsItem import GLGraphicsItem from .. import shaders from ... import QtGui import numpy as np __all__ = ['GLScatterPlotItem'] class GLScatterPlotItem(GLGraphicsItem): """Draws points at a list of 3D positions.""" def __init__(self, **kwds): GLGraphicsItem.__init__(self) glopts = kwds.pop('glOptions', 'additive') self.setGLOptions(glopts) self.pos = [] self.size = 10 self.color = [1.0,1.0,1.0,0.5] self.pxMode = True #self.vbo = {} ## VBO does not appear to improve performance very much. self.setData(**kwds) self.shader = None def setData(self, **kwds): """ Update the data displayed by this item. All arguments are optional; for example it is allowed to update spot positions while leaving colors unchanged, etc. ==================== ================================================== **Arguments:** pos (N,3) array of floats specifying point locations. color (N,4) array of floats (0.0-1.0) specifying spot colors OR a tuple of floats specifying a single color for all spots. size (N,) array of floats specifying spot sizes or a single value to apply to all spots. pxMode If True, spot sizes are expressed in pixels. Otherwise, they are expressed in item coordinates. ==================== ================================================== """ args = ['pos', 'color', 'size', 'pxMode'] for k in kwds.keys(): if k not in args: raise Exception('Invalid keyword argument: %s (allowed arguments are %s)' % (k, str(args))) args.remove('pxMode') for arg in args: if arg in kwds: setattr(self, arg, kwds[arg]) #self.vbo.pop(arg, None) self.pxMode = kwds.get('pxMode', self.pxMode) self.update() def initializeGL(self): if self.shader is not None: return ## Generate texture for rendering points w = 64 def fn(x,y): r = ((x-(w-1)/2.)**2 + (y-(w-1)/2.)**2) ** 0.5 return 255 * (w/2. - np.clip(r, w/2.-1.0, w/2.)) pData = np.empty((w, w, 4)) pData[:] = 255 pData[:,:,3] = np.fromfunction(fn, pData.shape[:2]) #print pData.shape, pData.min(), pData.max() pData = pData.astype(np.ubyte) if getattr(self, "pointTexture", None) is None: self.pointTexture = glGenTextures(1) glActiveTexture(GL_TEXTURE0) glEnable(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D, self.pointTexture) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, pData.shape[0], pData.shape[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, pData) self.shader = shaders.getShaderProgram('pointSprite') #def getVBO(self, name): #if name not in self.vbo: #self.vbo[name] = vbo.VBO(getattr(self, name).astype('f')) #return self.vbo[name] #def setupGLState(self): #"""Prepare OpenGL state for drawing. This function is called immediately before painting.""" ##glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ## requires z-sorting to render properly. #glBlendFunc(GL_SRC_ALPHA, GL_ONE) #glEnable( GL_BLEND ) #glEnable( GL_ALPHA_TEST ) #glDisable( GL_DEPTH_TEST ) ##glEnable( GL_POINT_SMOOTH ) ##glHint(GL_POINT_SMOOTH_HINT, GL_NICEST) ##glPointParameterfv(GL_POINT_DISTANCE_ATTENUATION, (0, 0, -1e-3)) ##glPointParameterfv(GL_POINT_SIZE_MAX, (65500,)) ##glPointParameterfv(GL_POINT_SIZE_MIN, (0,)) def paint(self): self.setupGLState() glEnable(GL_POINT_SPRITE) glActiveTexture(GL_TEXTURE0) glEnable( GL_TEXTURE_2D ) glBindTexture(GL_TEXTURE_2D, self.pointTexture) glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE) #glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE) ## use texture color exactly #glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ## texture modulates current color glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) glEnable(GL_PROGRAM_POINT_SIZE) with self.shader: #glUniform1i(self.shader.uniform('texture'), 0) ## inform the shader which texture to use glEnableClientState(GL_VERTEX_ARRAY) try: pos = self.pos #if pos.ndim > 2: #pos = pos.reshape((-1, pos.shape[-1])) glVertexPointerf(pos) if isinstance(self.color, np.ndarray): glEnableClientState(GL_COLOR_ARRAY) glColorPointerf(self.color) else: if isinstance(self.color, QtGui.QColor): glColor4f(*fn.glColor(self.color)) else: glColor4f(*self.color) if not self.pxMode or isinstance(self.size, np.ndarray): glEnableClientState(GL_NORMAL_ARRAY) norm = np.empty(pos.shape) if self.pxMode: norm[...,0] = self.size else: gpos = self.mapToView(pos.transpose()).transpose() pxSize = self.view().pixelSize(gpos) norm[...,0] = self.size / pxSize glNormalPointerf(norm) else: glNormal3f(self.size, 0, 0) ## vertex shader uses norm.x to determine point size #glPointSize(self.size) glDrawArrays(GL_POINTS, 0, int(pos.size / pos.shape[-1])) finally: glDisableClientState(GL_NORMAL_ARRAY) glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_COLOR_ARRAY) #posVBO.unbind() ##fixes #145 glDisable( GL_TEXTURE_2D ) #for i in range(len(self.pos)): #pos = self.pos[i] #if isinstance(self.color, np.ndarray): #color = self.color[i] #else: #color = self.color #if isinstance(self.color, QtGui.QColor): #color = fn.glColor(self.color) #if isinstance(self.size, np.ndarray): #size = self.size[i] #else: #size = self.size #pxSize = self.view().pixelSize(QtGui.QVector3D(*pos)) #glPointSize(size / pxSize) #glBegin( GL_POINTS ) #glColor4f(*color) # x is blue ##glNormal3f(size, 0, 0) #glVertex3f(*pos) #glEnd()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/opengl/items/GLLinePlotItem.py
.py
3,704
98
from OpenGL.GL import * from OpenGL.arrays import vbo from .. GLGraphicsItem import GLGraphicsItem from .. import shaders from ... import QtGui from ... import functions as fn import numpy as np __all__ = ['GLLinePlotItem'] class GLLinePlotItem(GLGraphicsItem): """Draws line plots in 3D.""" def __init__(self, **kwds): """All keyword arguments are passed to setData()""" GLGraphicsItem.__init__(self) glopts = kwds.pop('glOptions', 'additive') self.setGLOptions(glopts) self.pos = None self.mode = 'line_strip' self.width = 1. self.color = (1.0,1.0,1.0,1.0) self.setData(**kwds) def setData(self, **kwds): """ Update the data displayed by this item. All arguments are optional; for example it is allowed to update vertex positions while leaving colors unchanged, etc. ==================== ================================================== **Arguments:** ------------------------------------------------------------------------ pos (N,3) array of floats specifying point locations. color (N,4) array of floats (0.0-1.0) or tuple of floats specifying a single color for the entire item. width float specifying line width antialias enables smooth line drawing mode 'lines': Each pair of vertexes draws a single line segment. 'line_strip': All vertexes are drawn as a continuous set of line segments. ==================== ================================================== """ args = ['pos', 'color', 'width', 'mode', 'antialias'] for k in kwds.keys(): if k not in args: raise Exception('Invalid keyword argument: %s (allowed arguments are %s)' % (k, str(args))) self.antialias = False for arg in args: if arg in kwds: setattr(self, arg, kwds[arg]) #self.vbo.pop(arg, None) self.update() def initializeGL(self): pass def paint(self): if self.pos is None: return self.setupGLState() glEnableClientState(GL_VERTEX_ARRAY) try: glVertexPointerf(self.pos) if isinstance(self.color, np.ndarray): glEnableClientState(GL_COLOR_ARRAY) glColorPointerf(self.color) else: if isinstance(self.color, (str, QtGui.QColor)): glColor4f(*fn.glColor(self.color)) else: glColor4f(*self.color) glLineWidth(self.width) if self.antialias: glEnable(GL_LINE_SMOOTH) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glHint(GL_LINE_SMOOTH_HINT, GL_NICEST) if self.mode == 'line_strip': glDrawArrays(GL_LINE_STRIP, 0, int(self.pos.size / self.pos.shape[-1])) elif self.mode == 'lines': glDrawArrays(GL_LINES, 0, int(self.pos.size / self.pos.shape[-1])) else: raise Exception("Unknown line mode '%s'. (must be 'lines' or 'line_strip')" % self.mode) finally: glDisableClientState(GL_COLOR_ARRAY) glDisableClientState(GL_VERTEX_ARRAY)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/opengl/items/__init__.py
.py
0
0
null
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/opengl/items/GLMeshItem.py
.py
8,617
228
from OpenGL.GL import * from .. GLGraphicsItem import GLGraphicsItem from .. MeshData import MeshData from ...Qt import QtGui from .. import shaders from ... import functions as fn import numpy as np __all__ = ['GLMeshItem'] class GLMeshItem(GLGraphicsItem): """ **Bases:** :class:`GLGraphicsItem <pyqtgraph.opengl.GLGraphicsItem>` Displays a 3D triangle mesh. """ def __init__(self, **kwds): """ ============== ===================================================== **Arguments:** meshdata MeshData object from which to determine geometry for this item. color Default face color used if no vertex or face colors are specified. edgeColor Default edge color to use if no edge colors are specified in the mesh data. drawEdges If True, a wireframe mesh will be drawn. (default=False) drawFaces If True, mesh faces are drawn. (default=True) shader Name of shader program to use when drawing faces. (None for no shader) smooth If True, normal vectors are computed for each vertex and interpolated within each face. computeNormals If False, then computation of normal vectors is disabled. This can provide a performance boost for meshes that do not make use of normals. ============== ===================================================== """ self.opts = { 'meshdata': None, 'color': (1., 1., 1., 1.), 'drawEdges': False, 'drawFaces': True, 'edgeColor': (0.5, 0.5, 0.5, 1.0), 'shader': None, 'smooth': True, 'computeNormals': True, } GLGraphicsItem.__init__(self) glopts = kwds.pop('glOptions', 'opaque') self.setGLOptions(glopts) shader = kwds.pop('shader', None) self.setShader(shader) self.setMeshData(**kwds) ## storage for data compiled from MeshData object self.vertexes = None self.normals = None self.colors = None self.faces = None def setShader(self, shader): """Set the shader used when rendering faces in the mesh. (see the GL shaders example)""" self.opts['shader'] = shader self.update() def shader(self): shader = self.opts['shader'] if isinstance(shader, shaders.ShaderProgram): return shader else: return shaders.getShaderProgram(shader) def setColor(self, c): """Set the default color to use when no vertex or face colors are specified.""" self.opts['color'] = c self.update() def setMeshData(self, **kwds): """ Set mesh data for this item. This can be invoked two ways: 1. Specify *meshdata* argument with a new MeshData object 2. Specify keyword arguments to be passed to MeshData(..) to create a new instance. """ md = kwds.get('meshdata', None) if md is None: opts = {} for k in ['vertexes', 'faces', 'edges', 'vertexColors', 'faceColors']: try: opts[k] = kwds.pop(k) except KeyError: pass md = MeshData(**opts) self.opts['meshdata'] = md self.opts.update(kwds) self.meshDataChanged() self.update() def meshDataChanged(self): """ This method must be called to inform the item that the MeshData object has been altered. """ self.vertexes = None self.faces = None self.normals = None self.colors = None self.edges = None self.edgeColors = None self.update() def parseMeshData(self): ## interpret vertex / normal data before drawing ## This can: ## - automatically generate normals if they were not specified ## - pull vertexes/noormals/faces from MeshData if that was specified if self.vertexes is not None and self.normals is not None: return #if self.opts['normals'] is None: #if self.opts['meshdata'] is None: #self.opts['meshdata'] = MeshData(vertexes=self.opts['vertexes'], faces=self.opts['faces']) if self.opts['meshdata'] is not None: md = self.opts['meshdata'] if self.opts['smooth'] and not md.hasFaceIndexedData(): self.vertexes = md.vertexes() if self.opts['computeNormals']: self.normals = md.vertexNormals() self.faces = md.faces() if md.hasVertexColor(): self.colors = md.vertexColors() if md.hasFaceColor(): self.colors = md.faceColors() else: self.vertexes = md.vertexes(indexed='faces') if self.opts['computeNormals']: if self.opts['smooth']: self.normals = md.vertexNormals(indexed='faces') else: self.normals = md.faceNormals(indexed='faces') self.faces = None if md.hasVertexColor(): self.colors = md.vertexColors(indexed='faces') elif md.hasFaceColor(): self.colors = md.faceColors(indexed='faces') if self.opts['drawEdges']: if not md.hasFaceIndexedData(): self.edges = md.edges() self.edgeVerts = md.vertexes() else: self.edges = md.edges() self.edgeVerts = md.vertexes(indexed='faces') return def paint(self): self.setupGLState() self.parseMeshData() if self.opts['drawFaces']: with self.shader(): verts = self.vertexes norms = self.normals color = self.colors faces = self.faces if verts is None: return glEnableClientState(GL_VERTEX_ARRAY) try: glVertexPointerf(verts) if self.colors is None: color = self.opts['color'] if isinstance(color, QtGui.QColor): glColor4f(*fn.glColor(color)) else: glColor4f(*color) else: glEnableClientState(GL_COLOR_ARRAY) glColorPointerf(color) if norms is not None: glEnableClientState(GL_NORMAL_ARRAY) glNormalPointerf(norms) if faces is None: glDrawArrays(GL_TRIANGLES, 0, np.product(verts.shape[:-1])) else: faces = faces.astype(np.uint).flatten() glDrawElements(GL_TRIANGLES, faces.shape[0], GL_UNSIGNED_INT, faces) finally: glDisableClientState(GL_NORMAL_ARRAY) glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_COLOR_ARRAY) if self.opts['drawEdges']: verts = self.edgeVerts edges = self.edges glEnableClientState(GL_VERTEX_ARRAY) try: glVertexPointerf(verts) if self.edgeColors is None: color = self.opts['edgeColor'] if isinstance(color, QtGui.QColor): glColor4f(*fn.glColor(color)) else: glColor4f(*color) else: glEnableClientState(GL_COLOR_ARRAY) glColorPointerf(color) edges = edges.flatten() glDrawElements(GL_LINES, edges.shape[0], GL_UNSIGNED_INT, edges) finally: glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_COLOR_ARRAY)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/opengl/items/GLGridItem.py
.py
2,614
89
import numpy as np from OpenGL.GL import * from .. GLGraphicsItem import GLGraphicsItem from ... import QtGui from ... import functions as fn __all__ = ['GLGridItem'] class GLGridItem(GLGraphicsItem): """ **Bases:** :class:`GLGraphicsItem <pyqtgraph.opengl.GLGraphicsItem>` Displays a wire-frame grid. """ def __init__(self, size=None, color=(255, 255, 255, 76.5), antialias=True, glOptions='translucent'): GLGraphicsItem.__init__(self) self.setGLOptions(glOptions) self.antialias = antialias if size is None: size = QtGui.QVector3D(20,20,1) self.setSize(size=size) self.setSpacing(1, 1, 1) self.setColor(color) def setSize(self, x=None, y=None, z=None, size=None): """ Set the size of the axes (in its local coordinate system; this does not affect the transform) Arguments can be x,y,z or size=QVector3D(). """ if size is not None: x = size.x() y = size.y() z = size.z() self.__size = [x,y,z] self.update() def size(self): return self.__size[:] def setSpacing(self, x=None, y=None, z=None, spacing=None): """ Set the spacing between grid lines. Arguments can be x,y,z or spacing=QVector3D(). """ if spacing is not None: x = spacing.x() y = spacing.y() z = spacing.z() self.__spacing = [x,y,z] self.update() def spacing(self): return self.__spacing[:] def setColor(self, color): """Set the color of the grid. Arguments are the same as those accepted by functions.mkColor()""" self.__color = fn.Color(color) self.update() def color(self): return self.__color def paint(self): self.setupGLState() if self.antialias: glEnable(GL_LINE_SMOOTH) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glHint(GL_LINE_SMOOTH_HINT, GL_NICEST) glBegin( GL_LINES ) x,y,z = self.size() xs,ys,zs = self.spacing() xvals = np.arange(-x/2., x/2. + xs*0.001, xs) yvals = np.arange(-y/2., y/2. + ys*0.001, ys) glColor4f(*self.color().glColor()) for x in xvals: glVertex3f(x, yvals[0], 0) glVertex3f(x, yvals[-1], 0) for y in yvals: glVertex3f(xvals[0], y, 0) glVertex3f(xvals[-1], y, 0) glEnd()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/opengl/items/GLImageItem.py
.py
3,748
103
from OpenGL.GL import * from .. GLGraphicsItem import GLGraphicsItem from ...Qt import QtGui import numpy as np __all__ = ['GLImageItem'] class GLImageItem(GLGraphicsItem): """ **Bases:** :class:`GLGraphicsItem <pyqtgraph.opengl.GLGraphicsItem>` Displays image data as a textured quad. """ def __init__(self, data, smooth=False, glOptions='translucent'): """ ============== ======================================================================================= **Arguments:** data Volume data to be rendered. *Must* be 3D numpy array (x, y, RGBA) with dtype=ubyte. (See functions.makeRGBA) smooth (bool) If True, the volume slices are rendered with linear interpolation ============== ======================================================================================= """ self.smooth = smooth self._needUpdate = False GLGraphicsItem.__init__(self) self.setData(data) self.setGLOptions(glOptions) self.texture = None def initializeGL(self): if self.texture is not None: return glEnable(GL_TEXTURE_2D) self.texture = glGenTextures(1) def setData(self, data): self.data = data self._needUpdate = True self.update() def _updateTexture(self): glBindTexture(GL_TEXTURE_2D, self.texture) if self.smooth: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) else: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER) #glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER) shape = self.data.shape ## Test texture dimensions first glTexImage2D(GL_PROXY_TEXTURE_2D, 0, GL_RGBA, shape[0], shape[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, None) if glGetTexLevelParameteriv(GL_PROXY_TEXTURE_2D, 0, GL_TEXTURE_WIDTH) == 0: raise Exception("OpenGL failed to create 2D texture (%dx%d); too large for this hardware." % shape[:2]) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, shape[0], shape[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, self.data.transpose((1,0,2))) glDisable(GL_TEXTURE_2D) #self.lists = {} #for ax in [0,1,2]: #for d in [-1, 1]: #l = glGenLists(1) #self.lists[(ax,d)] = l #glNewList(l, GL_COMPILE) #self.drawVolume(ax, d) #glEndList() def paint(self): if self._needUpdate: self._updateTexture() glEnable(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D, self.texture) self.setupGLState() #glEnable(GL_DEPTH_TEST) ##glDisable(GL_CULL_FACE) #glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) #glEnable( GL_BLEND ) #glEnable( GL_ALPHA_TEST ) glColor4f(1,1,1,1) glBegin(GL_QUADS) glTexCoord2f(0,0) glVertex3f(0,0,0) glTexCoord2f(1,0) glVertex3f(self.data.shape[0], 0, 0) glTexCoord2f(1,1) glVertex3f(self.data.shape[0], self.data.shape[1], 0) glTexCoord2f(0,1) glVertex3f(0, self.data.shape[1], 0) glEnd() glDisable(GL_TEXTURE_3D)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/opengl/items/GLBoxItem.py
.py
2,470
88
from OpenGL.GL import * from .. GLGraphicsItem import GLGraphicsItem from ...Qt import QtGui from ... import functions as fn __all__ = ['GLBoxItem'] class GLBoxItem(GLGraphicsItem): """ **Bases:** :class:`GLGraphicsItem <pyqtgraph.opengl.GLGraphicsItem>` Displays a wire-frame box. """ def __init__(self, size=None, color=None, glOptions='translucent'): GLGraphicsItem.__init__(self) if size is None: size = QtGui.QVector3D(1,1,1) self.setSize(size=size) if color is None: color = (255,255,255,80) self.setColor(color) self.setGLOptions(glOptions) def setSize(self, x=None, y=None, z=None, size=None): """ Set the size of the box (in its local coordinate system; this does not affect the transform) Arguments can be x,y,z or size=QVector3D(). """ if size is not None: x = size.x() y = size.y() z = size.z() self.__size = [x,y,z] self.update() def size(self): return self.__size[:] def setColor(self, *args): """Set the color of the box. Arguments are the same as those accepted by functions.mkColor()""" self.__color = fn.Color(*args) def color(self): return self.__color def paint(self): #glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) #glEnable( GL_BLEND ) #glEnable( GL_ALPHA_TEST ) ##glAlphaFunc( GL_ALWAYS,0.5 ) #glEnable( GL_POINT_SMOOTH ) #glDisable( GL_DEPTH_TEST ) self.setupGLState() glBegin( GL_LINES ) glColor4f(*self.color().glColor()) x,y,z = self.size() glVertex3f(0, 0, 0) glVertex3f(0, 0, z) glVertex3f(x, 0, 0) glVertex3f(x, 0, z) glVertex3f(0, y, 0) glVertex3f(0, y, z) glVertex3f(x, y, 0) glVertex3f(x, y, z) glVertex3f(0, 0, 0) glVertex3f(0, y, 0) glVertex3f(x, 0, 0) glVertex3f(x, y, 0) glVertex3f(0, 0, z) glVertex3f(0, y, z) glVertex3f(x, 0, z) glVertex3f(x, y, z) glVertex3f(0, 0, 0) glVertex3f(x, 0, 0) glVertex3f(0, y, 0) glVertex3f(x, y, 0) glVertex3f(0, 0, z) glVertex3f(x, 0, z) glVertex3f(0, y, z) glVertex3f(x, y, z) glEnd()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/opengl/items/GLSurfacePlotItem.py
.py
5,204
139
from OpenGL.GL import * from .GLMeshItem import GLMeshItem from .. MeshData import MeshData from ...Qt import QtGui import numpy as np __all__ = ['GLSurfacePlotItem'] class GLSurfacePlotItem(GLMeshItem): """ **Bases:** :class:`GLMeshItem <pyqtgraph.opengl.GLMeshItem>` Displays a surface plot on a regular x,y grid """ def __init__(self, x=None, y=None, z=None, colors=None, **kwds): """ The x, y, z, and colors arguments are passed to setData(). All other keyword arguments are passed to GLMeshItem.__init__(). """ self._x = None self._y = None self._z = None self._color = None self._vertexes = None self._meshdata = MeshData() GLMeshItem.__init__(self, meshdata=self._meshdata, **kwds) self.setData(x, y, z, colors) def setData(self, x=None, y=None, z=None, colors=None): """ Update the data in this surface plot. ============== ===================================================================== **Arguments:** x,y 1D arrays of values specifying the x,y positions of vertexes in the grid. If these are omitted, then the values will be assumed to be integers. z 2D array of height values for each grid vertex. colors (width, height, 4) array of vertex colors. ============== ===================================================================== All arguments are optional. Note that if vertex positions are updated, the normal vectors for each triangle must be recomputed. This is somewhat expensive if the surface was initialized with smooth=False and very expensive if smooth=True. For faster performance, initialize with computeNormals=False and use per-vertex colors or a normal-independent shader program. """ if x is not None: if self._x is None or len(x) != len(self._x): self._vertexes = None self._x = x if y is not None: if self._y is None or len(y) != len(self._y): self._vertexes = None self._y = y if z is not None: #if self._x is None: #self._x = np.arange(z.shape[0]) #self._vertexes = None #if self._y is None: #self._y = np.arange(z.shape[1]) #self._vertexes = None if self._x is not None and z.shape[0] != len(self._x): raise Exception('Z values must have shape (len(x), len(y))') if self._y is not None and z.shape[1] != len(self._y): raise Exception('Z values must have shape (len(x), len(y))') self._z = z if self._vertexes is not None and self._z.shape != self._vertexes.shape[:2]: self._vertexes = None if colors is not None: self._colors = colors self._meshdata.setVertexColors(colors) if self._z is None: return updateMesh = False newVertexes = False ## Generate vertex and face array if self._vertexes is None: newVertexes = True self._vertexes = np.empty((self._z.shape[0], self._z.shape[1], 3), dtype=float) self.generateFaces() self._meshdata.setFaces(self._faces) updateMesh = True ## Copy x, y, z data into vertex array if newVertexes or x is not None: if x is None: if self._x is None: x = np.arange(self._z.shape[0]) else: x = self._x self._vertexes[:, :, 0] = x.reshape(len(x), 1) updateMesh = True if newVertexes or y is not None: if y is None: if self._y is None: y = np.arange(self._z.shape[1]) else: y = self._y self._vertexes[:, :, 1] = y.reshape(1, len(y)) updateMesh = True if newVertexes or z is not None: self._vertexes[...,2] = self._z updateMesh = True ## Update MeshData if updateMesh: self._meshdata.setVertexes(self._vertexes.reshape(self._vertexes.shape[0]*self._vertexes.shape[1], 3)) self.meshDataChanged() def generateFaces(self): cols = self._z.shape[1]-1 rows = self._z.shape[0]-1 faces = np.empty((cols*rows*2, 3), dtype=np.uint) rowtemplate1 = np.arange(cols).reshape(cols, 1) + np.array([[0, 1, cols+1]]) rowtemplate2 = np.arange(cols).reshape(cols, 1) + np.array([[cols+1, 1, cols+2]]) for row in range(rows): start = row * cols * 2 faces[start:start+cols] = rowtemplate1 + row * (cols+1) faces[start+cols:start+(cols*2)] = rowtemplate2 + row * (cols+1) self._faces = faces
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/GraphItem.py
.py
5,577
148
from .. import functions as fn from .GraphicsObject import GraphicsObject from .ScatterPlotItem import ScatterPlotItem from ..Qt import QtGui, QtCore import numpy as np from .. import getConfigOption __all__ = ['GraphItem'] class GraphItem(GraphicsObject): """A GraphItem displays graph information as a set of nodes connected by lines (as in 'graph theory', not 'graphics'). Useful for drawing networks, trees, etc. """ def __init__(self, **kwds): GraphicsObject.__init__(self) self.scatter = ScatterPlotItem() self.scatter.setParentItem(self) self.adjacency = None self.pos = None self.picture = None self.pen = 'default' self.setData(**kwds) def setData(self, **kwds): """ Change the data displayed by the graph. ============== ======================================================================= **Arguments:** pos (N,2) array of the positions of each node in the graph. adj (M,2) array of connection data. Each row contains indexes of two nodes that are connected. pen The pen to use when drawing lines between connected nodes. May be one of: * QPen * a single argument to pass to pg.mkPen * a record array of length M with fields (red, green, blue, alpha, width). Note that using this option may have a significant performance cost. * None (to disable connection drawing) * 'default' to use the default foreground color. symbolPen The pen(s) used for drawing nodes. symbolBrush The brush(es) used for drawing nodes. ``**opts`` All other keyword arguments are given to :func:`ScatterPlotItem.setData() <pyqtgraph.ScatterPlotItem.setData>` to affect the appearance of nodes (symbol, size, brush, etc.) ============== ======================================================================= """ if 'adj' in kwds: self.adjacency = kwds.pop('adj') if self.adjacency.dtype.kind not in 'iu': raise Exception("adjacency array must have int or unsigned type.") self._update() if 'pos' in kwds: self.pos = kwds['pos'] self._update() if 'pen' in kwds: self.setPen(kwds.pop('pen')) self._update() if 'symbolPen' in kwds: kwds['pen'] = kwds.pop('symbolPen') if 'symbolBrush' in kwds: kwds['brush'] = kwds.pop('symbolBrush') self.scatter.setData(**kwds) self.informViewBoundsChanged() def _update(self): self.picture = None self.prepareGeometryChange() self.update() def setPen(self, *args, **kwargs): """ Set the pen used to draw graph lines. May be: * None to disable line drawing * Record array with fields (red, green, blue, alpha, width) * Any set of arguments and keyword arguments accepted by :func:`mkPen <pyqtgraph.mkPen>`. * 'default' to use the default foreground color. """ if len(args) == 1 and len(kwargs) == 0: self.pen = args[0] else: self.pen = fn.mkPen(*args, **kwargs) self.picture = None self.update() def generatePicture(self): self.picture = QtGui.QPicture() if self.pen is None or self.pos is None or self.adjacency is None: return p = QtGui.QPainter(self.picture) try: pts = self.pos[self.adjacency] pen = self.pen if isinstance(pen, np.ndarray): lastPen = None for i in range(pts.shape[0]): pen = self.pen[i] if np.any(pen != lastPen): lastPen = pen if pen.dtype.fields is None: p.setPen(fn.mkPen(color=(pen[0], pen[1], pen[2], pen[3]), width=1)) else: p.setPen(fn.mkPen(color=(pen['red'], pen['green'], pen['blue'], pen['alpha']), width=pen['width'])) p.drawLine(QtCore.QPointF(*pts[i][0]), QtCore.QPointF(*pts[i][1])) else: if pen == 'default': pen = getConfigOption('foreground') p.setPen(fn.mkPen(pen)) pts = pts.reshape((pts.shape[0]*pts.shape[1], pts.shape[2])) path = fn.arrayToQPath(x=pts[:,0], y=pts[:,1], connect='pairs') p.drawPath(path) finally: p.end() def paint(self, p, *args): if self.picture == None: self.generatePicture() if getConfigOption('antialias') is True: p.setRenderHint(p.Antialiasing) self.picture.play(p) def boundingRect(self): return self.scatter.boundingRect() def dataBounds(self, *args, **kwds): return self.scatter.dataBounds(*args, **kwds) def pixelPadding(self): return self.scatter.pixelPadding()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/AxisItem.py
.py
44,747
1,133
# -*- coding: utf-8 -*- from ..Qt import QtGui, QtCore from ..python2_3 import asUnicode import numpy as np from ..Point import Point from .. import debug as debug import weakref from .. import functions as fn from .. import getConfigOption from .GraphicsWidget import GraphicsWidget __all__ = ['AxisItem'] class AxisItem(GraphicsWidget): """ GraphicsItem showing a single plot axis with ticks, values, and label. Can be configured to fit on any side of a plot, and can automatically synchronize its displayed scale with ViewBox items. Ticks can be extended to draw a grid. If maxTickLength is negative, ticks point into the plot. """ def __init__(self, orientation, pen=None, textPen=None, linkView=None, parent=None, maxTickLength=-5, showValues=True, text='', units='', unitPrefix='', **args): """ ============== =============================================================== **Arguments:** orientation one of 'left', 'right', 'top', or 'bottom' maxTickLength (px) maximum length of ticks to draw. Negative values draw into the plot, positive values draw outward. linkView (ViewBox) causes the range of values displayed in the axis to be linked to the visible range of a ViewBox. showValues (bool) Whether to display values adjacent to ticks pen (QPen) Pen used when drawing ticks. textPen (QPen) Pen used when drawing tick labels. text The text (excluding units) to display on the label for this axis. units The units for this axis. Units should generally be given without any scaling prefix (eg, 'V' instead of 'mV'). The scaling prefix will be automatically prepended based on the range of data displayed. args All extra keyword arguments become CSS style options for the <span> tag which will surround the axis label and units. ============== =============================================================== """ GraphicsWidget.__init__(self, parent) self.label = QtGui.QGraphicsTextItem(self) self.picture = None self.orientation = orientation if orientation not in ['left', 'right', 'top', 'bottom']: raise Exception("Orientation argument must be one of 'left', 'right', 'top', or 'bottom'.") if orientation in ['left', 'right']: self.label.rotate(-90) self.style = { 'tickTextOffset': [5, 2], ## (horizontal, vertical) spacing between text and axis 'tickTextWidth': 30, ## space reserved for tick text 'tickTextHeight': 18, 'autoExpandTextSpace': True, ## automatically expand text space if needed 'tickFont': None, 'stopAxisAtTick': (False, False), ## whether axis is drawn to edge of box or to last tick 'textFillLimits': [ ## how much of the axis to fill up with tick text, maximally. (0, 0.8), ## never fill more than 80% of the axis (2, 0.6), ## If we already have 2 ticks with text, fill no more than 60% of the axis (4, 0.4), ## If we already have 4 ticks with text, fill no more than 40% of the axis (6, 0.2), ## If we already have 6 ticks with text, fill no more than 20% of the axis ], 'showValues': showValues, 'tickLength': maxTickLength, 'maxTickLevel': 2, 'maxTextLevel': 2, } self.textWidth = 30 ## Keeps track of maximum width / height of tick text self.textHeight = 18 # If the user specifies a width / height, remember that setting # indefinitely. self.fixedWidth = None self.fixedHeight = None self.labelText = text self.labelUnits = units self.labelUnitPrefix = unitPrefix self.labelStyle = args self.logMode = False self._tickLevels = None ## used to override the automatic ticking system with explicit ticks self._tickSpacing = None # used to override default tickSpacing method self.scale = 1.0 self.autoSIPrefix = True self.autoSIPrefixScale = 1.0 self.showLabel(False) self.setRange(0, 1) if pen is None: self.setPen() else: self.setPen(pen) if textPen is None: self.setTextPen() else: self.setTextPen(pen) self._linkedView = None if linkView is not None: self.linkToView(linkView) self.grid = False #self.setCacheMode(self.DeviceCoordinateCache) def setStyle(self, **kwds): """ Set various style options. =================== ======================================================= Keyword Arguments: tickLength (int) The maximum length of ticks in pixels. Positive values point toward the text; negative values point away. tickTextOffset (int) reserved spacing between text and axis in px tickTextWidth (int) Horizontal space reserved for tick text in px tickTextHeight (int) Vertical space reserved for tick text in px autoExpandTextSpace (bool) Automatically expand text space if the tick strings become too long. tickFont (QFont or None) Determines the font used for tick values. Use None for the default font. stopAxisAtTick (tuple: (bool min, bool max)) If True, the axis line is drawn only as far as the last tick. Otherwise, the line is drawn to the edge of the AxisItem boundary. textFillLimits (list of (tick #, % fill) tuples). This structure determines how the AxisItem decides how many ticks should have text appear next to them. Each tuple in the list specifies what fraction of the axis length may be occupied by text, given the number of ticks that already have text displayed. For example:: [(0, 0.8), # Never fill more than 80% of the axis (2, 0.6), # If we already have 2 ticks with text, # fill no more than 60% of the axis (4, 0.4), # If we already have 4 ticks with text, # fill no more than 40% of the axis (6, 0.2)] # If we already have 6 ticks with text, # fill no more than 20% of the axis showValues (bool) indicates whether text is displayed adjacent to ticks. =================== ======================================================= Added in version 0.9.9 """ for kwd,value in kwds.items(): if kwd not in self.style: raise NameError("%s is not a valid style argument." % kwd) if kwd in ('tickLength', 'tickTextOffset', 'tickTextWidth', 'tickTextHeight'): if not isinstance(value, int): raise ValueError("Argument '%s' must be int" % kwd) if kwd == 'tickTextOffset': if self.orientation in ('left', 'right'): self.style['tickTextOffset'][0] = value else: self.style['tickTextOffset'][1] = value elif kwd == 'stopAxisAtTick': try: assert len(value) == 2 and isinstance(value[0], bool) and isinstance(value[1], bool) except: raise ValueError("Argument 'stopAxisAtTick' must have type (bool, bool)") self.style[kwd] = value else: self.style[kwd] = value self.picture = None self._adjustSize() self.update() def close(self): self.scene().removeItem(self.label) self.label = None self.scene().removeItem(self) def setGrid(self, grid): """Set the alpha value (0-255) for the grid, or False to disable. When grid lines are enabled, the axis tick lines are extended to cover the extent of the linked ViewBox, if any. """ self.grid = grid self.picture = None self.prepareGeometryChange() self.update() def setLogMode(self, log): """ If *log* is True, then ticks are displayed on a logarithmic scale and values are adjusted accordingly. (This is usually accessed by changing the log mode of a :func:`PlotItem <pyqtgraph.PlotItem.setLogMode>`) """ self.logMode = log self.picture = None self.update() def setTickFont(self, font): """ (QFont or None) Determines the font used for tick values. Use None for the default font. """ self.style['tickFont'] = font self.picture = None self.prepareGeometryChange() ## Need to re-allocate space depending on font size? self.update() def resizeEvent(self, ev=None): #s = self.size() ## Set the position of the label nudge = 5 br = self.label.boundingRect() p = QtCore.QPointF(0, 0) if self.orientation == 'left': p.setY(int(self.size().height()/2 + br.width()/2)) p.setX(-nudge) elif self.orientation == 'right': p.setY(int(self.size().height()/2 + br.width()/2)) p.setX(int(self.size().width()-br.height()+nudge)) elif self.orientation == 'top': p.setY(-nudge) p.setX(int(self.size().width()/2. - br.width()/2.)) elif self.orientation == 'bottom': p.setX(int(self.size().width()/2. - br.width()/2.)) p.setY(int(self.size().height()-br.height()+nudge)) self.label.setPos(p) self.picture = None def showLabel(self, show=True): """Show/hide the label text for this axis.""" #self.drawLabel = show self.label.setVisible(show) if self.orientation in ['left', 'right']: self._updateWidth() else: self._updateHeight() if self.autoSIPrefix: self.updateAutoSIPrefix() def setLabel(self, text=None, units=None, unitPrefix=None, **args): """Set the text displayed adjacent to the axis. ============== ============================================================= **Arguments:** text The text (excluding units) to display on the label for this axis. units The units for this axis. Units should generally be given without any scaling prefix (eg, 'V' instead of 'mV'). The scaling prefix will be automatically prepended based on the range of data displayed. args All extra keyword arguments become CSS style options for the <span> tag which will surround the axis label and units. ============== ============================================================= The final text generated for the label will look like:: <span style="...options...">{text} (prefix{units})</span> Each extra keyword argument will become a CSS option in the above template. For example, you can set the font size and color of the label:: labelStyle = {'color': '#FFF', 'font-size': '14pt'} axis.setLabel('label text', units='V', **labelStyle) """ show_label = False if text is not None: self.labelText = text show_label = True if units is not None: self.labelUnits = units show_label = True if show_label: self.showLabel() if unitPrefix is not None: self.labelUnitPrefix = unitPrefix if len(args) > 0: self.labelStyle = args self.label.setHtml(self.labelString()) self._adjustSize() self.picture = None self.update() def labelString(self): if self.labelUnits == '': if not self.autoSIPrefix or self.autoSIPrefixScale == 1.0: units = '' else: units = asUnicode('(x%g)') % (1.0/self.autoSIPrefixScale) else: #print repr(self.labelUnitPrefix), repr(self.labelUnits) units = asUnicode('(%s%s)') % (asUnicode(self.labelUnitPrefix), asUnicode(self.labelUnits)) s = asUnicode('%s %s') % (asUnicode(self.labelText), asUnicode(units)) style = ';'.join(['%s: %s' % (k, self.labelStyle[k]) for k in self.labelStyle]) return asUnicode("<span style='%s'>%s</span>") % (style, asUnicode(s)) def _updateMaxTextSize(self, x): ## Informs that the maximum tick size orthogonal to the axis has ## changed; we use this to decide whether the item needs to be resized ## to accomodate. if self.orientation in ['left', 'right']: mx = max(self.textWidth, x) if mx > self.textWidth or mx < self.textWidth-10: self.textWidth = mx if self.style['autoExpandTextSpace'] is True: self._updateWidth() #return True ## size has changed else: mx = max(self.textHeight, x) if mx > self.textHeight or mx < self.textHeight-10: self.textHeight = mx if self.style['autoExpandTextSpace'] is True: self._updateHeight() #return True ## size has changed def _adjustSize(self): if self.orientation in ['left', 'right']: self._updateWidth() else: self._updateHeight() def setHeight(self, h=None): """Set the height of this axis reserved for ticks and tick labels. The height of the axis label is automatically added. If *height* is None, then the value will be determined automatically based on the size of the tick text.""" self.fixedHeight = h self._updateHeight() def _updateHeight(self): if not self.isVisible(): h = 0 else: if self.fixedHeight is None: if not self.style['showValues']: h = 0 elif self.style['autoExpandTextSpace'] is True: h = self.textHeight else: h = self.style['tickTextHeight'] h += self.style['tickTextOffset'][1] if self.style['showValues'] else 0 h += max(0, self.style['tickLength']) if self.label.isVisible(): h += self.label.boundingRect().height() * 0.8 else: h = self.fixedHeight self.setMaximumHeight(h) self.setMinimumHeight(h) self.picture = None def setWidth(self, w=None): """Set the width of this axis reserved for ticks and tick labels. The width of the axis label is automatically added. If *width* is None, then the value will be determined automatically based on the size of the tick text.""" self.fixedWidth = w self._updateWidth() def _updateWidth(self): if not self.isVisible(): w = 0 else: if self.fixedWidth is None: if not self.style['showValues']: w = 0 elif self.style['autoExpandTextSpace'] is True: w = self.textWidth else: w = self.style['tickTextWidth'] w += self.style['tickTextOffset'][0] if self.style['showValues'] else 0 w += max(0, self.style['tickLength']) if self.label.isVisible(): w += self.label.boundingRect().height() * 0.8 ## bounding rect is usually an overestimate else: w = self.fixedWidth self.setMaximumWidth(w) self.setMinimumWidth(w) self.picture = None def pen(self): if self._pen is None: return fn.mkPen(getConfigOption('foreground')) return fn.mkPen(self._pen) def setPen(self, *args, **kwargs): """ Set the pen used for drawing text, axes, ticks, and grid lines. If no arguments are given, the default foreground color will be used (see :func:`setConfigOption <pyqtgraph.setConfigOption>`). """ self.picture = None if args or kwargs: self._pen = fn.mkPen(*args, **kwargs) else: self._pen = fn.mkPen(getConfigOption('foreground')) self.labelStyle['color'] = '#' + fn.colorStr(self._pen.color())[:6] self.setLabel() self.update() def textPen(self): if self._textPen is None: return fn.mkPen(getConfigOption('foreground')) return fn.mkPen(self._textPen) def setTextPen(self, *args, **kwargs): """ Set the pen used for drawing text. If no arguments are given, the default foreground color will be used. """ self.picture = None if args or kwargs: self._textPen = fn.mkPen(*args, **kwargs) else: self._textPen = fn.mkPen(getConfigOption('foreground')) self.labelStyle['color'] = '#' + fn.colorStr(self._textPen.color())[:6] self.setLabel() self.update() def setScale(self, scale=None): """ Set the value scaling for this axis. Setting this value causes the axis to draw ticks and tick labels as if the view coordinate system were scaled. By default, the axis scaling is 1.0. """ # Deprecated usage, kept for backward compatibility if scale is None: scale = 1.0 self.enableAutoSIPrefix(True) if scale != self.scale: self.scale = scale self.setLabel() self.picture = None self.update() def enableAutoSIPrefix(self, enable=True): """ Enable (or disable) automatic SI prefix scaling on this axis. When enabled, this feature automatically determines the best SI prefix to prepend to the label units, while ensuring that axis values are scaled accordingly. For example, if the axis spans values from -0.1 to 0.1 and has units set to 'V' then the axis would display values -100 to 100 and the units would appear as 'mV' This feature is enabled by default, and is only available when a suffix (unit string) is provided to display on the label. """ self.autoSIPrefix = enable self.updateAutoSIPrefix() def updateAutoSIPrefix(self): if self.label.isVisible(): if self.logMode: _range = 10**np.array(self.range) else: _range = self.range (scale, prefix) = fn.siScale(max(abs(_range[0]*self.scale), abs(_range[1]*self.scale))) if self.labelUnits == '' and prefix in ['k', 'm']: ## If we are not showing units, wait until 1e6 before scaling. scale = 1.0 prefix = '' self.autoSIPrefixScale = scale self.setLabel(unitPrefix=prefix) else: self.autoSIPrefixScale = 1.0 self.picture = None self.update() def setRange(self, mn, mx): """Set the range of values displayed by the axis. Usually this is handled automatically by linking the axis to a ViewBox with :func:`linkToView <pyqtgraph.AxisItem.linkToView>`""" if any(np.isinf((mn, mx))) or any(np.isnan((mn, mx))): raise Exception("Not setting range to [%s, %s]" % (str(mn), str(mx))) self.range = [mn, mx] if self.autoSIPrefix: self.updateAutoSIPrefix() self.picture = None self.update() def linkedView(self): """Return the ViewBox this axis is linked to""" if self._linkedView is None: return None else: return self._linkedView() def linkToView(self, view): """Link this axis to a ViewBox, causing its displayed range to match the visible range of the view.""" self.unlinkFromView() self._linkedView = weakref.ref(view) if self.orientation in ['right', 'left']: view.sigYRangeChanged.connect(self.linkedViewChanged) else: view.sigXRangeChanged.connect(self.linkedViewChanged) view.sigResized.connect(self.linkedViewChanged) def unlinkFromView(self): """Unlink this axis from a ViewBox.""" oldView = self.linkedView() self._linkedView = None if self.orientation in ['right', 'left']: if oldView is not None: oldView.sigYRangeChanged.disconnect(self.linkedViewChanged) else: if oldView is not None: oldView.sigXRangeChanged.disconnect(self.linkedViewChanged) if oldView is not None: oldView.sigResized.disconnect(self.linkedViewChanged) def linkedViewChanged(self, view, newRange=None): if self.orientation in ['right', 'left']: if newRange is None: newRange = view.viewRange()[1] if view.yInverted(): self.setRange(*newRange[::-1]) else: self.setRange(*newRange) else: if newRange is None: newRange = view.viewRange()[0] if view.xInverted(): self.setRange(*newRange[::-1]) else: self.setRange(*newRange) def boundingRect(self): linkedView = self.linkedView() if linkedView is None or self.grid is False: rect = self.mapRectFromParent(self.geometry()) ## extend rect if ticks go in negative direction ## also extend to account for text that flows past the edges tl = self.style['tickLength'] if self.orientation == 'left': rect = rect.adjusted(0, -15, -min(0,tl), 15) elif self.orientation == 'right': rect = rect.adjusted(min(0,tl), -15, 0, 15) elif self.orientation == 'top': rect = rect.adjusted(-15, 0, 15, -min(0,tl)) elif self.orientation == 'bottom': rect = rect.adjusted(-15, min(0,tl), 15, 0) return rect else: return self.mapRectFromParent(self.geometry()) | linkedView.mapRectToItem(self, linkedView.boundingRect()) def paint(self, p, opt, widget): profiler = debug.Profiler() if self.picture is None: try: picture = QtGui.QPicture() painter = QtGui.QPainter(picture) specs = self.generateDrawSpecs(painter) profiler('generate specs') if specs is not None: self.drawPicture(painter, *specs) profiler('draw picture') finally: painter.end() self.picture = picture #p.setRenderHint(p.Antialiasing, False) ## Sometimes we get a segfault here ??? #p.setRenderHint(p.TextAntialiasing, True) self.picture.play(p) def setTicks(self, ticks): """Explicitly determine which ticks to display. This overrides the behavior specified by tickSpacing(), tickValues(), and tickStrings() The format for *ticks* looks like:: [ [ (majorTickValue1, majorTickString1), (majorTickValue2, majorTickString2), ... ], [ (minorTickValue1, minorTickString1), (minorTickValue2, minorTickString2), ... ], ... ] If *ticks* is None, then the default tick system will be used instead. """ self._tickLevels = ticks self.picture = None self.update() def setTickSpacing(self, major=None, minor=None, levels=None): """ Explicitly determine the spacing of major and minor ticks. This overrides the default behavior of the tickSpacing method, and disables the effect of setTicks(). Arguments may be either *major* and *minor*, or *levels* which is a list of (spacing, offset) tuples for each tick level desired. If no arguments are given, then the default behavior of tickSpacing is enabled. Examples:: # two levels, all offsets = 0 axis.setTickSpacing(5, 1) # three levels, all offsets = 0 axis.setTickSpacing([(3, 0), (1, 0), (0.25, 0)]) # reset to default axis.setTickSpacing() """ if levels is None: if major is None: levels = None else: levels = [(major, 0), (minor, 0)] self._tickSpacing = levels self.picture = None self.update() def tickSpacing(self, minVal, maxVal, size): """Return values describing the desired spacing and offset of ticks. This method is called whenever the axis needs to be redrawn and is a good method to override in subclasses that require control over tick locations. The return value must be a list of tuples, one for each set of ticks:: [ (major tick spacing, offset), (minor tick spacing, offset), (sub-minor tick spacing, offset), ... ] """ # First check for override tick spacing if self._tickSpacing is not None: return self._tickSpacing dif = abs(maxVal - minVal) if dif == 0: return [] ## decide optimal minor tick spacing in pixels (this is just aesthetics) optimalTickCount = max(2., np.log(size)) ## optimal minor tick spacing optimalSpacing = dif / optimalTickCount ## the largest power-of-10 spacing which is smaller than optimal p10unit = 10 ** np.floor(np.log10(optimalSpacing)) ## Determine major/minor tick spacings which flank the optimal spacing. intervals = np.array([1., 2., 10., 20., 100.]) * p10unit minorIndex = 0 while intervals[minorIndex+1] <= optimalSpacing: minorIndex += 1 levels = [ (intervals[minorIndex+2], 0), (intervals[minorIndex+1], 0), #(intervals[minorIndex], 0) ## Pretty, but eats up CPU ] if self.style['maxTickLevel'] >= 2: ## decide whether to include the last level of ticks minSpacing = min(size / 20., 30.) maxTickCount = size / minSpacing if dif / intervals[minorIndex] <= maxTickCount: levels.append((intervals[minorIndex], 0)) return levels ##### This does not work -- switching between 2/5 confuses the automatic text-level-selection ### Determine major/minor tick spacings which flank the optimal spacing. #intervals = np.array([1., 2., 5., 10., 20., 50., 100.]) * p10unit #minorIndex = 0 #while intervals[minorIndex+1] <= optimalSpacing: #minorIndex += 1 ### make sure we never see 5 and 2 at the same time #intIndexes = [ #[0,1,3], #[0,2,3], #[2,3,4], #[3,4,6], #[3,5,6], #][minorIndex] #return [ #(intervals[intIndexes[2]], 0), #(intervals[intIndexes[1]], 0), #(intervals[intIndexes[0]], 0) #] def tickValues(self, minVal, maxVal, size): """ Return the values and spacing of ticks to draw:: [ (spacing, [major ticks]), (spacing, [minor ticks]), ... ] By default, this method calls tickSpacing to determine the correct tick locations. This is a good method to override in subclasses. """ minVal, maxVal = sorted((minVal, maxVal)) minVal *= self.scale maxVal *= self.scale #size *= self.scale ticks = [] tickLevels = self.tickSpacing(minVal, maxVal, size) allValues = np.array([]) for i in range(len(tickLevels)): spacing, offset = tickLevels[i] ## determine starting tick start = (np.ceil((minVal-offset) / spacing) * spacing) + offset ## determine number of ticks num = int((maxVal-start) / spacing) + 1 values = (np.arange(num) * spacing + start) / self.scale ## remove any ticks that were present in higher levels ## we assume here that if the difference between a tick value and a previously seen tick value ## is less than spacing/100, then they are 'equal' and we can ignore the new tick. values = list(filter(lambda x: all(np.abs(allValues-x) > spacing/self.scale*0.01), values)) allValues = np.concatenate([allValues, values]) ticks.append((spacing/self.scale, values)) if self.logMode: return self.logTickValues(minVal, maxVal, size, ticks) #nticks = [] #for t in ticks: #nvals = [] #for v in t[1]: #nvals.append(v/self.scale) #nticks.append((t[0]/self.scale,nvals)) #ticks = nticks return ticks def logTickValues(self, minVal, maxVal, size, stdTicks): ## start with the tick spacing given by tickValues(). ## Any level whose spacing is < 1 needs to be converted to log scale ticks = [] for (spacing, t) in stdTicks: if spacing >= 1.0: ticks.append((spacing, t)) if len(ticks) < 3: v1 = int(np.floor(minVal)) v2 = int(np.ceil(maxVal)) #major = list(range(v1+1, v2)) minor = [] for v in range(v1, v2): minor.extend(v + np.log10(np.arange(1, 10))) minor = [x for x in minor if x>minVal and x<maxVal] ticks.append((None, minor)) return ticks def tickStrings(self, values, scale, spacing): """Return the strings that should be placed next to ticks. This method is called when redrawing the axis and is a good method to override in subclasses. The method is called with a list of tick values, a scaling factor (see below), and the spacing between ticks (this is required since, in some instances, there may be only one tick and thus no other way to determine the tick spacing) The scale argument is used when the axis label is displaying units which may have an SI scaling prefix. When determining the text to display, use value*scale to correctly account for this prefix. For example, if the axis label's units are set to 'V', then a tick value of 0.001 might be accompanied by a scale value of 1000. This indicates that the label is displaying 'mV', and thus the tick should display 0.001 * 1000 = 1. """ if self.logMode: return self.logTickStrings(values, scale, spacing) places = max(0, np.ceil(-np.log10(spacing*scale))) strings = [] for v in values: vs = v * scale if abs(vs) < .001 or abs(vs) >= 10000: vstr = "%g" % vs else: vstr = ("%%0.%df" % places) % vs strings.append(vstr) return strings def logTickStrings(self, values, scale, spacing): return ["%0.1g"%x for x in 10 ** np.array(values).astype(float) * np.array(scale)] def generateDrawSpecs(self, p): """ Calls tickValues() and tickStrings() to determine where and how ticks should be drawn, then generates from this a set of drawing commands to be interpreted by drawPicture(). """ profiler = debug.Profiler() #bounds = self.boundingRect() bounds = self.mapRectFromParent(self.geometry()) linkedView = self.linkedView() if linkedView is None or self.grid is False: tickBounds = bounds else: tickBounds = linkedView.mapRectToItem(self, linkedView.boundingRect()) if self.orientation == 'left': span = (bounds.topRight(), bounds.bottomRight()) tickStart = tickBounds.right() tickStop = bounds.right() tickDir = -1 axis = 0 elif self.orientation == 'right': span = (bounds.topLeft(), bounds.bottomLeft()) tickStart = tickBounds.left() tickStop = bounds.left() tickDir = 1 axis = 0 elif self.orientation == 'top': span = (bounds.bottomLeft(), bounds.bottomRight()) tickStart = tickBounds.bottom() tickStop = bounds.bottom() tickDir = -1 axis = 1 elif self.orientation == 'bottom': span = (bounds.topLeft(), bounds.topRight()) tickStart = tickBounds.top() tickStop = bounds.top() tickDir = 1 axis = 1 #print tickStart, tickStop, span ## determine size of this item in pixels points = list(map(self.mapToDevice, span)) if None in points: return lengthInPixels = Point(points[1] - points[0]).length() if lengthInPixels == 0: return # Determine major / minor / subminor axis ticks if self._tickLevels is None: tickLevels = self.tickValues(self.range[0], self.range[1], lengthInPixels) tickStrings = None else: ## parse self.tickLevels into the formats returned by tickLevels() and tickStrings() tickLevels = [] tickStrings = [] for level in self._tickLevels: values = [] strings = [] tickLevels.append((None, values)) tickStrings.append(strings) for val, strn in level: values.append(val) strings.append(strn) ## determine mapping between tick values and local coordinates dif = self.range[1] - self.range[0] if dif == 0: xScale = 1 offset = 0 else: if axis == 0: xScale = -bounds.height() / dif offset = self.range[0] * xScale - bounds.height() else: xScale = bounds.width() / dif offset = self.range[0] * xScale xRange = [x * xScale - offset for x in self.range] xMin = min(xRange) xMax = max(xRange) profiler('init') tickPositions = [] # remembers positions of previously drawn ticks ## compute coordinates to draw ticks ## draw three different intervals, long ticks first tickSpecs = [] for i in range(len(tickLevels)): tickPositions.append([]) ticks = tickLevels[i][1] ## length of tick tickLength = self.style['tickLength'] / ((i*0.5)+1.0) lineAlpha = 255 / (i+1) if self.grid is not False: lineAlpha *= self.grid/255. * np.clip((0.05 * lengthInPixels / (len(ticks)+1)), 0., 1.) for v in ticks: ## determine actual position to draw this tick x = (v * xScale) - offset if x < xMin or x > xMax: ## last check to make sure no out-of-bounds ticks are drawn tickPositions[i].append(None) continue tickPositions[i].append(x) p1 = [x, x] p2 = [x, x] p1[axis] = tickStart p2[axis] = tickStop if self.grid is False: p2[axis] += tickLength*tickDir tickPen = self.pen() color = tickPen.color() color.setAlpha(int(lineAlpha)) tickPen.setColor(color) tickSpecs.append((tickPen, Point(p1), Point(p2))) profiler('compute ticks') if self.style['stopAxisAtTick'][0] is True: minTickPosition = min(map(min, tickPositions)) if axis == 0: stop = max(span[0].y(), minTickPosition) span[0].setY(stop) else: stop = max(span[0].x(), minTickPosition) span[0].setX(stop) if self.style['stopAxisAtTick'][1] is True: maxTickPosition = max(map(max, tickPositions)) if axis == 0: stop = min(span[1].y(), maxTickPosition) span[1].setY(stop) else: stop = min(span[1].x(), maxTickPosition) span[1].setX(stop) axisSpec = (self.pen(), span[0], span[1]) textOffset = self.style['tickTextOffset'][axis] ## spacing between axis and text #if self.style['autoExpandTextSpace'] is True: #textWidth = self.textWidth #textHeight = self.textHeight #else: #textWidth = self.style['tickTextWidth'] ## space allocated for horizontal text #textHeight = self.style['tickTextHeight'] ## space allocated for horizontal text textSize2 = 0 textRects = [] textSpecs = [] ## list of draw # If values are hidden, return early if not self.style['showValues']: return (axisSpec, tickSpecs, textSpecs) for i in range(min(len(tickLevels), self.style['maxTextLevel']+1)): ## Get the list of strings to display for this level if tickStrings is None: spacing, values = tickLevels[i] strings = self.tickStrings(values, self.autoSIPrefixScale * self.scale, spacing) else: strings = tickStrings[i] if len(strings) == 0: continue ## ignore strings belonging to ticks that were previously ignored for j in range(len(strings)): if tickPositions[i][j] is None: strings[j] = None ## Measure density of text; decide whether to draw this level rects = [] for s in strings: if s is None: rects.append(None) else: br = p.boundingRect(QtCore.QRectF(0, 0, 100, 100), QtCore.Qt.AlignCenter, asUnicode(s)) ## boundingRect is usually just a bit too large ## (but this probably depends on per-font metrics?) br.setHeight(br.height() * 0.8) rects.append(br) textRects.append(rects[-1]) if len(textRects) > 0: ## measure all text, make sure there's enough room if axis == 0: textSize = np.sum([r.height() for r in textRects]) textSize2 = np.max([r.width() for r in textRects]) else: textSize = np.sum([r.width() for r in textRects]) textSize2 = np.max([r.height() for r in textRects]) else: textSize = 0 textSize2 = 0 if i > 0: ## always draw top level ## If the strings are too crowded, stop drawing text now. ## We use three different crowding limits based on the number ## of texts drawn so far. textFillRatio = float(textSize) / lengthInPixels finished = False for nTexts, limit in self.style['textFillLimits']: if len(textSpecs) >= nTexts and textFillRatio >= limit: finished = True break if finished: break #spacing, values = tickLevels[best] #strings = self.tickStrings(values, self.scale, spacing) # Determine exactly where tick text should be drawn for j in range(len(strings)): vstr = strings[j] if vstr is None: ## this tick was ignored because it is out of bounds continue vstr = asUnicode(vstr) x = tickPositions[i][j] #textRect = p.boundingRect(QtCore.QRectF(0, 0, 100, 100), QtCore.Qt.AlignCenter, vstr) textRect = rects[j] height = textRect.height() width = textRect.width() #self.textHeight = height offset = max(0,self.style['tickLength']) + textOffset if self.orientation == 'left': textFlags = QtCore.Qt.TextDontClip|QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter rect = QtCore.QRectF(tickStop-offset-width, x-(height/2), width, height) elif self.orientation == 'right': textFlags = QtCore.Qt.TextDontClip|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter rect = QtCore.QRectF(tickStop+offset, x-(height/2), width, height) elif self.orientation == 'top': textFlags = QtCore.Qt.TextDontClip|QtCore.Qt.AlignCenter|QtCore.Qt.AlignBottom rect = QtCore.QRectF(x-width/2., tickStop-offset-height, width, height) elif self.orientation == 'bottom': textFlags = QtCore.Qt.TextDontClip|QtCore.Qt.AlignCenter|QtCore.Qt.AlignTop rect = QtCore.QRectF(x-width/2., tickStop+offset, width, height) #p.setPen(self.pen()) #p.drawText(rect, textFlags, vstr) textSpecs.append((rect, textFlags, vstr)) profiler('compute text') ## update max text size if needed. self._updateMaxTextSize(textSize2) return (axisSpec, tickSpecs, textSpecs) def drawPicture(self, p, axisSpec, tickSpecs, textSpecs): profiler = debug.Profiler() p.setRenderHint(p.Antialiasing, False) p.setRenderHint(p.TextAntialiasing, True) ## draw long line along axis pen, p1, p2 = axisSpec p.setPen(pen) p.drawLine(p1, p2) p.translate(0.5,0) ## resolves some damn pixel ambiguity ## draw ticks for pen, p1, p2 in tickSpecs: p.setPen(pen) p.drawLine(p1, p2) profiler('draw ticks') # Draw all text if self.style['tickFont'] is not None: p.setFont(self.style['tickFont']) p.setPen(self.textPen()) for rect, flags, text in textSpecs: p.drawText(rect, int(flags), text) profiler('draw text') def show(self): GraphicsWidget.show(self) if self.orientation in ['left', 'right']: self._updateWidth() else: self._updateHeight() def hide(self): GraphicsWidget.hide(self) if self.orientation in ['left', 'right']: self._updateWidth() else: self._updateHeight() def wheelEvent(self, ev): if self.linkedView() is None: return if self.orientation in ['left', 'right']: self.linkedView().wheelEvent(ev, axis=1) else: self.linkedView().wheelEvent(ev, axis=0) ev.accept() def mouseDragEvent(self, event): if self.linkedView() is None: return if self.orientation in ['left', 'right']: return self.linkedView().mouseDragEvent(event, axis=1) else: return self.linkedView().mouseDragEvent(event, axis=0) def mouseClickEvent(self, event): if self.linkedView() is None: return return self.linkedView().mouseClickEvent(event)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/GraphicsObject.py
.py
1,744
40
from ..Qt import QtGui, QtCore, QT_LIB if QT_LIB in ['PyQt4', 'PyQt5']: import sip from .GraphicsItem import GraphicsItem __all__ = ['GraphicsObject'] class GraphicsObject(GraphicsItem, QtGui.QGraphicsObject): """ **Bases:** :class:`GraphicsItem <pyqtgraph.graphicsItems.GraphicsItem>`, :class:`QtGui.QGraphicsObject` Extension of QGraphicsObject with some useful methods (provided by :class:`GraphicsItem <pyqtgraph.graphicsItems.GraphicsItem>`) """ _qtBaseClass = QtGui.QGraphicsObject def __init__(self, *args): self.__inform_view_on_changes = True QtGui.QGraphicsObject.__init__(self, *args) self.setFlag(self.ItemSendsGeometryChanges) GraphicsItem.__init__(self) def itemChange(self, change, value): ret = QtGui.QGraphicsObject.itemChange(self, change, value) if change in [self.ItemParentHasChanged, self.ItemSceneHasChanged]: self.parentChanged() try: inform_view_on_change = self.__inform_view_on_changes except AttributeError: # It's possible that the attribute was already collected when the itemChange happened # (if it was triggered during the gc of the object). pass else: if inform_view_on_change and change in [self.ItemPositionHasChanged, self.ItemTransformHasChanged]: self.informViewBoundsChanged() ## workaround for pyqt bug: ## http://www.riverbankcomputing.com/pipermail/pyqt/2012-August/031818.html if QT_LIB in ['PyQt4', 'PyQt5'] and change == self.ItemParentChange and isinstance(ret, QtGui.QGraphicsItem): ret = sip.cast(ret, QtGui.QGraphicsItem) return ret
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/LabelItem.py
.py
5,146
143
from ..Qt import QtGui, QtCore from .. import functions as fn from .GraphicsWidget import GraphicsWidget from .GraphicsWidgetAnchor import GraphicsWidgetAnchor from .. import getConfigOption __all__ = ['LabelItem'] class LabelItem(GraphicsWidget, GraphicsWidgetAnchor): """ GraphicsWidget displaying text. Used mainly as axis labels, titles, etc. Note: To display text inside a scaled view (ViewBox, PlotWidget, etc) use TextItem """ def __init__(self, text=' ', parent=None, angle=0, **args): GraphicsWidget.__init__(self, parent) GraphicsWidgetAnchor.__init__(self) self.item = QtGui.QGraphicsTextItem(self) self.opts = { 'color': None, 'justify': 'center' } self.opts.update(args) self._sizeHint = {} self.setText(text) self.setAngle(angle) def setAttr(self, attr, value): """Set default text properties. See setText() for accepted parameters.""" self.opts[attr] = value def setText(self, text, **args): """Set the text and text properties in the label. Accepts optional arguments for auto-generating a CSS style string: ==================== ============================== **Style Arguments:** color (str) example: 'CCFF00' size (str) example: '8pt' bold (bool) italic (bool) ==================== ============================== """ self.text = text opts = self.opts for k in args: opts[k] = args[k] optlist = [] color = self.opts['color'] if color is None: color = getConfigOption('foreground') color = fn.mkColor(color) optlist.append('color: #' + fn.colorStr(color)[:6]) if 'size' in opts: optlist.append('font-size: ' + opts['size']) if 'bold' in opts and opts['bold'] in [True, False]: optlist.append('font-weight: ' + {True:'bold', False:'normal'}[opts['bold']]) if 'italic' in opts and opts['italic'] in [True, False]: optlist.append('font-style: ' + {True:'italic', False:'normal'}[opts['italic']]) full = "<span style='%s'>%s</span>" % ('; '.join(optlist), text) #print full self.item.setHtml(full) self.updateMin() self.resizeEvent(None) self.updateGeometry() def resizeEvent(self, ev): #c1 = self.boundingRect().center() #c2 = self.item.mapToParent(self.item.boundingRect().center()) # + self.item.pos() #dif = c1 - c2 #self.item.moveBy(dif.x(), dif.y()) #print c1, c2, dif, self.item.pos() self.item.setPos(0,0) bounds = self.itemRect() left = self.mapFromItem(self.item, QtCore.QPointF(0,0)) - self.mapFromItem(self.item, QtCore.QPointF(1,0)) rect = self.rect() if self.opts['justify'] == 'left': if left.x() != 0: bounds.moveLeft(rect.left()) if left.y() < 0: bounds.moveTop(rect.top()) elif left.y() > 0: bounds.moveBottom(rect.bottom()) elif self.opts['justify'] == 'center': bounds.moveCenter(rect.center()) #bounds = self.itemRect() #self.item.setPos(self.width()/2. - bounds.width()/2., 0) elif self.opts['justify'] == 'right': if left.x() != 0: bounds.moveRight(rect.right()) if left.y() < 0: bounds.moveBottom(rect.bottom()) elif left.y() > 0: bounds.moveTop(rect.top()) #bounds = self.itemRect() #self.item.setPos(self.width() - bounds.width(), 0) self.item.setPos(bounds.topLeft() - self.itemRect().topLeft()) self.updateMin() def setAngle(self, angle): self.angle = angle self.item.resetTransform() self.item.rotate(angle) self.updateMin() def updateMin(self): bounds = self.itemRect() self.setMinimumWidth(bounds.width()) self.setMinimumHeight(bounds.height()) self._sizeHint = { QtCore.Qt.MinimumSize: (bounds.width(), bounds.height()), QtCore.Qt.PreferredSize: (bounds.width(), bounds.height()), QtCore.Qt.MaximumSize: (-1, -1), #bounds.width()*2, bounds.height()*2), QtCore.Qt.MinimumDescent: (0, 0) ##?? what is this? } self.updateGeometry() def sizeHint(self, hint, constraint): if hint not in self._sizeHint: return QtCore.QSizeF(0, 0) return QtCore.QSizeF(*self._sizeHint[hint]) def itemRect(self): return self.item.mapRectToParent(self.item.boundingRect()) #def paint(self, p, *args): #p.setPen(fn.mkPen('r')) #p.drawRect(self.rect()) #p.setPen(fn.mkPen('g')) #p.drawRect(self.itemRect())
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/GraphicsWidgetAnchor.py
.py
4,080
110
from ..Qt import QtGui, QtCore from ..Point import Point class GraphicsWidgetAnchor(object): """ Class used to allow GraphicsWidgets to anchor to a specific position on their parent. The item will be automatically repositioned if the parent is resized. This is used, for example, to anchor a LegendItem to a corner of its parent PlotItem. """ def __init__(self): self.__parent = None self.__parentAnchor = None self.__itemAnchor = None self.__offset = (0,0) if hasattr(self, 'geometryChanged'): self.geometryChanged.connect(self.__geometryChanged) def anchor(self, itemPos, parentPos, offset=(0,0)): """ Anchors the item at its local itemPos to the item's parent at parentPos. Both positions are expressed in values relative to the size of the item or parent; a value of 0 indicates left or top edge, while 1 indicates right or bottom edge. Optionally, offset may be specified to introduce an absolute offset. Example: anchor a box such that its upper-right corner is fixed 10px left and 10px down from its parent's upper-right corner:: box.anchor(itemPos=(1,0), parentPos=(1,0), offset=(-10,10)) """ parent = self.parentItem() if parent is None: raise Exception("Cannot anchor; parent is not set.") if self.__parent is not parent: if self.__parent is not None: self.__parent.geometryChanged.disconnect(self.__geometryChanged) self.__parent = parent parent.geometryChanged.connect(self.__geometryChanged) self.__itemAnchor = itemPos self.__parentAnchor = parentPos self.__offset = offset self.__geometryChanged() def autoAnchor(self, pos, relative=True): """ Set the position of this item relative to its parent by automatically choosing appropriate anchor settings. If relative is True, one corner of the item will be anchored to the appropriate location on the parent with no offset. The anchored corner will be whichever is closest to the parent's boundary. If relative is False, one corner of the item will be anchored to the same corner of the parent, with an absolute offset to achieve the correct position. """ pos = Point(pos) br = self.mapRectToParent(self.boundingRect()).translated(pos - self.pos()) pbr = self.parentItem().boundingRect() anchorPos = [0,0] parentPos = Point() itemPos = Point() if abs(br.left() - pbr.left()) < abs(br.right() - pbr.right()): anchorPos[0] = 0 parentPos[0] = pbr.left() itemPos[0] = br.left() else: anchorPos[0] = 1 parentPos[0] = pbr.right() itemPos[0] = br.right() if abs(br.top() - pbr.top()) < abs(br.bottom() - pbr.bottom()): anchorPos[1] = 0 parentPos[1] = pbr.top() itemPos[1] = br.top() else: anchorPos[1] = 1 parentPos[1] = pbr.bottom() itemPos[1] = br.bottom() if relative: relPos = [(itemPos[0]-pbr.left()) / pbr.width(), (itemPos[1]-pbr.top()) / pbr.height()] self.anchor(anchorPos, relPos) else: offset = itemPos - parentPos self.anchor(anchorPos, anchorPos, offset) def __geometryChanged(self): if self.__parent is None: return if self.__itemAnchor is None: return o = self.mapToParent(Point(0,0)) a = self.boundingRect().bottomRight() * Point(self.__itemAnchor) a = self.mapToParent(a) p = self.__parent.boundingRect().bottomRight() * Point(self.__parentAnchor) off = Point(self.__offset) pos = p + (o-a) + off self.setPos(pos)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/GraphicsLayout.py
.py
7,070
192
from ..Qt import QtGui, QtCore from .. import functions as fn from .GraphicsWidget import GraphicsWidget ## Must be imported at the end to avoid cyclic-dependency hell: from .ViewBox import ViewBox from .PlotItem import PlotItem from .LabelItem import LabelItem __all__ = ['GraphicsLayout'] class GraphicsLayout(GraphicsWidget): """ Used for laying out GraphicsWidgets in a grid. This is usually created automatically as part of a :class:`GraphicsWindow <pyqtgraph.GraphicsWindow>` or :class:`GraphicsLayoutWidget <pyqtgraph.GraphicsLayoutWidget>`. """ def __init__(self, parent=None, border=None): GraphicsWidget.__init__(self, parent) if border is True: border = (100,100,100) self.border = border self.layout = QtGui.QGraphicsGridLayout() self.setLayout(self.layout) self.items = {} ## item: [(row, col), (row, col), ...] lists all cells occupied by the item self.rows = {} ## row: {col1: item1, col2: item2, ...} maps cell location to item self.itemBorders = {} ## {item1: QtGui.QGraphicsRectItem, ...} border rects self.currentRow = 0 self.currentCol = 0 self.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)) #def resizeEvent(self, ev): #ret = GraphicsWidget.resizeEvent(self, ev) #print self.pos(), self.mapToDevice(self.rect().topLeft()) #return ret def setBorder(self, *args, **kwds): """ Set the pen used to draw border between cells. See :func:`mkPen <pyqtgraph.mkPen>` for arguments. """ self.border = fn.mkPen(*args, **kwds) for borderRect in self.itemBorders.values(): borderRect.setPen(self.border) def nextRow(self): """Advance to next row for automatic item placement""" self.currentRow += 1 self.currentCol = -1 self.nextColumn() def nextColumn(self): """Advance to next available column (generally only for internal use--called by addItem)""" self.currentCol += 1 while self.getItem(self.currentRow, self.currentCol) is not None: self.currentCol += 1 def nextCol(self, *args, **kargs): """Alias of nextColumn""" return self.nextColumn(*args, **kargs) def addPlot(self, row=None, col=None, rowspan=1, colspan=1, **kargs): """ Create a PlotItem and place it in the next available cell (or in the cell specified) All extra keyword arguments are passed to :func:`PlotItem.__init__ <pyqtgraph.PlotItem.__init__>` Returns the created item. """ plot = PlotItem(**kargs) self.addItem(plot, row, col, rowspan, colspan) return plot def addViewBox(self, row=None, col=None, rowspan=1, colspan=1, **kargs): """ Create a ViewBox and place it in the next available cell (or in the cell specified) All extra keyword arguments are passed to :func:`ViewBox.__init__ <pyqtgraph.ViewBox.__init__>` Returns the created item. """ vb = ViewBox(**kargs) self.addItem(vb, row, col, rowspan, colspan) return vb def addLabel(self, text=' ', row=None, col=None, rowspan=1, colspan=1, **kargs): """ Create a LabelItem with *text* and place it in the next available cell (or in the cell specified) All extra keyword arguments are passed to :func:`LabelItem.__init__ <pyqtgraph.LabelItem.__init__>` Returns the created item. To create a vertical label, use *angle* = -90. """ text = LabelItem(text, **kargs) self.addItem(text, row, col, rowspan, colspan) return text def addLayout(self, row=None, col=None, rowspan=1, colspan=1, **kargs): """ Create an empty GraphicsLayout and place it in the next available cell (or in the cell specified) All extra keyword arguments are passed to :func:`GraphicsLayout.__init__ <pyqtgraph.GraphicsLayout.__init__>` Returns the created item. """ layout = GraphicsLayout(**kargs) self.addItem(layout, row, col, rowspan, colspan) return layout def addItem(self, item, row=None, col=None, rowspan=1, colspan=1): """ Add an item to the layout and place it in the next available cell (or in the cell specified). The item must be an instance of a QGraphicsWidget subclass. """ if row is None: row = self.currentRow if col is None: col = self.currentCol self.items[item] = [] for i in range(rowspan): for j in range(colspan): row2 = row + i col2 = col + j if row2 not in self.rows: self.rows[row2] = {} self.rows[row2][col2] = item self.items[item].append((row2, col2)) borderRect = QtGui.QGraphicsRectItem() borderRect.setParentItem(self) borderRect.setZValue(1e3) borderRect.setPen(fn.mkPen(self.border)) self.itemBorders[item] = borderRect item.geometryChanged.connect(self._updateItemBorder) self.layout.addItem(item, row, col, rowspan, colspan) self.nextColumn() def getItem(self, row, col): """Return the item in (*row*, *col*). If the cell is empty, return None.""" return self.rows.get(row, {}).get(col, None) def boundingRect(self): return self.rect() def itemIndex(self, item): for i in range(self.layout.count()): if self.layout.itemAt(i).graphicsItem() is item: return i raise Exception("Could not determine index of item " + str(item)) def removeItem(self, item): """Remove *item* from the layout.""" ind = self.itemIndex(item) self.layout.removeAt(ind) self.scene().removeItem(item) for r, c in self.items[item]: del self.rows[r][c] del self.items[item] item.geometryChanged.disconnect(self._updateItemBorder) del self.itemBorders[item] self.update() def clear(self): for i in list(self.items.keys()): self.removeItem(i) self.currentRow = 0 self.currentCol = 0 def setContentsMargins(self, *args): # Wrap calls to layout. This should happen automatically, but there # seems to be a Qt bug: # http://stackoverflow.com/questions/27092164/margins-in-pyqtgraphs-graphicslayout self.layout.setContentsMargins(*args) def setSpacing(self, *args): self.layout.setSpacing(*args) def _updateItemBorder(self): if self.border is None: return item = self.sender() if item is None: return r = item.mapRectToParent(item.boundingRect()) self.itemBorders[item].setRect(r)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/TargetItem.py
.py
4,016
126
from ..Qt import QtGui, QtCore import numpy as np from ..Point import Point from .. import functions as fn from .GraphicsObject import GraphicsObject from .TextItem import TextItem class TargetItem(GraphicsObject): """Draws a draggable target symbol (circle plus crosshair). The size of TargetItem will remain fixed on screen even as the view is zoomed. Includes an optional text label. """ sigDragged = QtCore.Signal(object) def __init__(self, movable=True, radii=(5, 10, 10), pen=(255, 255, 0), brush=(0, 0, 255, 100)): GraphicsObject.__init__(self) self._bounds = None self._radii = radii self._picture = None self.movable = movable self.moving = False self.label = None self.labelAngle = 0 self.pen = fn.mkPen(pen) self.brush = fn.mkBrush(brush) def setLabel(self, label): if label is None: if self.label is not None: self.label.scene().removeItem(self.label) self.label = None else: if self.label is None: self.label = TextItem() self.label.setParentItem(self) self.label.setText(label) self._updateLabel() def setLabelAngle(self, angle): self.labelAngle = angle self._updateLabel() def boundingRect(self): if self._picture is None: self._drawPicture() return self._bounds def dataBounds(self, axis, frac=1.0, orthoRange=None): return [0, 0] def viewTransformChanged(self): self._picture = None self.prepareGeometryChange() self._updateLabel() def _updateLabel(self): if self.label is None: return # find an optimal location for text at the given angle angle = self.labelAngle * np.pi / 180. lbr = self.label.boundingRect() center = lbr.center() a = abs(np.sin(angle) * lbr.height()*0.5) b = abs(np.cos(angle) * lbr.width()*0.5) r = max(self._radii) + 2 + max(a, b) pos = self.mapFromScene(self.mapToScene(QtCore.QPointF(0, 0)) + r * QtCore.QPointF(np.cos(angle), -np.sin(angle)) - center) self.label.setPos(pos) def paint(self, p, *args): if self._picture is None: self._drawPicture() self._picture.play(p) def _drawPicture(self): self._picture = QtGui.QPicture() p = QtGui.QPainter(self._picture) p.setRenderHint(p.Antialiasing) # Note: could do this with self.pixelLength, but this is faster. o = self.mapToScene(QtCore.QPointF(0, 0)) px = abs(1.0 / (self.mapToScene(QtCore.QPointF(1, 0)) - o).x()) py = abs(1.0 / (self.mapToScene(QtCore.QPointF(0, 1)) - o).y()) r, w, h = self._radii w = w * px h = h * py rx = r * px ry = r * py rect = QtCore.QRectF(-rx, -ry, rx*2, ry*2) p.setPen(self.pen) p.setBrush(self.brush) p.drawEllipse(rect) p.drawLine(Point(-w, 0), Point(w, 0)) p.drawLine(Point(0, -h), Point(0, h)) p.end() bx = max(w, rx) by = max(h, ry) self._bounds = QtCore.QRectF(-bx, -by, bx*2, by*2) def mouseDragEvent(self, ev): if not self.movable: return if ev.button() == QtCore.Qt.LeftButton: if ev.isStart(): self.moving = True self.cursorOffset = self.pos() - self.mapToParent(ev.buttonDownPos()) self.startPosition = self.pos() ev.accept() if not self.moving: return self.setPos(self.cursorOffset + self.mapToParent(ev.pos())) if ev.isFinish(): self.moving = False self.sigDragged.emit(self) def hoverEvent(self, ev): if self.movable: ev.acceptDrags(QtCore.Qt.LeftButton)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/FillBetweenItem.py
.py
2,944
84
from ..Qt import QtGui from .. import functions as fn from .PlotDataItem import PlotDataItem from .PlotCurveItem import PlotCurveItem class FillBetweenItem(QtGui.QGraphicsPathItem): """ GraphicsItem filling the space between two PlotDataItems. """ def __init__(self, curve1=None, curve2=None, brush=None, pen=None): QtGui.QGraphicsPathItem.__init__(self) self.curves = None if curve1 is not None and curve2 is not None: self.setCurves(curve1, curve2) elif curve1 is not None or curve2 is not None: raise Exception("Must specify two curves to fill between.") if brush is not None: self.setBrush(brush) self.setPen(pen) self.updatePath() def setBrush(self, *args, **kwds): QtGui.QGraphicsPathItem.setBrush(self, fn.mkBrush(*args, **kwds)) def setPen(self, *args, **kwds): QtGui.QGraphicsPathItem.setPen(self, fn.mkPen(*args, **kwds)) def setCurves(self, curve1, curve2): """Set the curves to fill between. Arguments must be instances of PlotDataItem or PlotCurveItem. Added in version 0.9.9 """ if self.curves is not None: for c in self.curves: try: c.sigPlotChanged.disconnect(self.curveChanged) except (TypeError, RuntimeError): pass curves = [curve1, curve2] for c in curves: if not isinstance(c, PlotDataItem) and not isinstance(c, PlotCurveItem): raise TypeError("Curves must be PlotDataItem or PlotCurveItem.") self.curves = curves curve1.sigPlotChanged.connect(self.curveChanged) curve2.sigPlotChanged.connect(self.curveChanged) self.setZValue(min(curve1.zValue(), curve2.zValue())-1) self.curveChanged() def setBrush(self, *args, **kwds): """Change the fill brush. Acceps the same arguments as pg.mkBrush()""" QtGui.QGraphicsPathItem.setBrush(self, fn.mkBrush(*args, **kwds)) def curveChanged(self): self.updatePath() def updatePath(self): if self.curves is None: self.setPath(QtGui.QPainterPath()) return paths = [] for c in self.curves: if isinstance(c, PlotDataItem): paths.append(c.curve.getPath()) elif isinstance(c, PlotCurveItem): paths.append(c.getPath()) path = QtGui.QPainterPath() transform = QtGui.QTransform() ps1 = paths[0].toSubpathPolygons(transform) ps2 = paths[1].toReversed().toSubpathPolygons(transform) ps2.reverse() if len(ps1) == 0 or len(ps2) == 0: self.setPath(QtGui.QPainterPath()) return for p1, p2 in zip(ps1, ps2): path.addPolygon(p1 + p2) self.setPath(path)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/CurvePoint.py
.py
4,677
123
from ..Qt import QtGui, QtCore from . import ArrowItem import numpy as np from ..Point import Point import weakref from .GraphicsObject import GraphicsObject __all__ = ['CurvePoint', 'CurveArrow'] class CurvePoint(GraphicsObject): """A GraphicsItem that sets its location to a point on a PlotCurveItem. Also rotates to be tangent to the curve. The position along the curve is a Qt property, and thus can be easily animated. Note: This class does not display anything; see CurveArrow for an applied example """ def __init__(self, curve, index=0, pos=None, rotate=True): """Position can be set either as an index referring to the sample number or the position 0.0 - 1.0 If *rotate* is True, then the item rotates to match the tangent of the curve. """ GraphicsObject.__init__(self) #QObjectWorkaround.__init__(self) self._rotate = rotate self.curve = weakref.ref(curve) self.setParentItem(curve) self.setProperty('position', 0.0) self.setProperty('index', 0) if hasattr(self, 'ItemHasNoContents'): self.setFlags(self.flags() | self.ItemHasNoContents) if pos is not None: self.setPos(pos) else: self.setIndex(index) def setPos(self, pos): self.setProperty('position', float(pos))## cannot use numpy types here, MUST be python float. def setIndex(self, index): self.setProperty('index', int(index)) ## cannot use numpy types here, MUST be python int. def event(self, ev): if not isinstance(ev, QtCore.QDynamicPropertyChangeEvent) or self.curve() is None: return False if ev.propertyName() == 'index': index = self.property('index') if 'QVariant' in repr(index): index = index.toInt()[0] elif ev.propertyName() == 'position': index = None else: return False (x, y) = self.curve().getData() if index is None: #print ev.propertyName(), self.property('position').toDouble()[0], self.property('position').typeName() pos = self.property('position') if 'QVariant' in repr(pos): ## need to support 2 APIs :( pos = pos.toDouble()[0] index = (len(x)-1) * np.clip(pos, 0.0, 1.0) if index != int(index): ## interpolate floating-point values i1 = int(index) i2 = np.clip(i1+1, 0, len(x)-1) s2 = index-i1 s1 = 1.0-s2 newPos = (x[i1]*s1+x[i2]*s2, y[i1]*s1+y[i2]*s2) else: index = int(index) i1 = np.clip(index-1, 0, len(x)-1) i2 = np.clip(index+1, 0, len(x)-1) newPos = (x[index], y[index]) p1 = self.parentItem().mapToScene(QtCore.QPointF(x[i1], y[i1])) p2 = self.parentItem().mapToScene(QtCore.QPointF(x[i2], y[i2])) ang = np.arctan2(p2.y()-p1.y(), p2.x()-p1.x()) ## returns radians self.resetTransform() if self._rotate: self.rotate(180+ ang * 180 / np.pi) ## takes degrees QtGui.QGraphicsItem.setPos(self, *newPos) return True def boundingRect(self): return QtCore.QRectF() def paint(self, *args): pass def makeAnimation(self, prop='position', start=0.0, end=1.0, duration=10000, loop=1): # In Python 3, a bytes object needs to be used as a property name in # QPropertyAnimation. PyQt stopped automatically encoding a str when a # QByteArray was expected in v5.5 (see qbytearray.sip). if not isinstance(prop, bytes): prop = prop.encode('latin-1') anim = QtCore.QPropertyAnimation(self, prop) anim.setDuration(duration) anim.setStartValue(start) anim.setEndValue(end) anim.setLoopCount(loop) return anim class CurveArrow(CurvePoint): """Provides an arrow that points to any specific sample on a PlotCurveItem. Provides properties that can be animated.""" def __init__(self, curve, index=0, pos=None, **opts): CurvePoint.__init__(self, curve, index=index, pos=pos) if opts.get('pxMode', True): opts['pxMode'] = False self.setFlags(self.flags() | self.ItemIgnoresTransformations) opts['angle'] = 0 self.arrow = ArrowItem.ArrowItem(**opts) self.arrow.setParentItem(self) def setStyle(self, **opts): return self.arrow.setStyle(**opts)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/UIGraphicsItem.py
.py
4,692
125
from ..Qt import QtGui, QtCore, QT_LIB import weakref from .GraphicsObject import GraphicsObject if QT_LIB in ['PyQt4', 'PyQt5']: import sip __all__ = ['UIGraphicsItem'] class UIGraphicsItem(GraphicsObject): """ Base class for graphics items with boundaries relative to a GraphicsView or ViewBox. The purpose of this class is to allow the creation of GraphicsItems which live inside a scalable view, but whose boundaries will always stay fixed relative to the view's boundaries. For example: GridItem, InfiniteLine The view can be specified on initialization or it can be automatically detected when the item is painted. NOTE: Only the item's boundingRect is affected; the item is not transformed in any way. Use viewRangeChanged to respond to changes in the view. """ #sigViewChanged = QtCore.Signal(object) ## emitted whenever the viewport coords have changed def __init__(self, bounds=None, parent=None): """ ============== ============================================================================= **Arguments:** bounds QRectF with coordinates relative to view box. The default is QRectF(0,0,1,1), which means the item will have the same bounds as the view. ============== ============================================================================= """ GraphicsObject.__init__(self, parent) self.setFlag(self.ItemSendsScenePositionChanges) if bounds is None: self._bounds = QtCore.QRectF(0, 0, 1, 1) else: self._bounds = bounds self._boundingRect = None self._updateView() def paint(self, *args): ## check for a new view object every time we paint. #self.updateView() pass def itemChange(self, change, value): ret = GraphicsObject.itemChange(self, change, value) ## workaround for pyqt bug: ## http://www.riverbankcomputing.com/pipermail/pyqt/2012-August/031818.html if QT_LIB in ['PyQt4', 'PyQt5'] and change == self.ItemParentChange and isinstance(ret, QtGui.QGraphicsItem): ret = sip.cast(ret, QtGui.QGraphicsItem) if change == self.ItemScenePositionHasChanged: self.setNewBounds() return ret #def updateView(self): ### called to see whether this item has a new view to connect to ### check for this item's current viewbox or view widget #view = self.getViewBox() #if view is None: ##print " no view" #return #if self._connectedView is not None and view is self._connectedView(): ##print " already have view", view #return ### disconnect from previous view #if self._connectedView is not None: #cv = self._connectedView() #if cv is not None: ##print "disconnect:", self #cv.sigRangeChanged.disconnect(self.viewRangeChanged) ### connect to new view ##print "connect:", self #view.sigRangeChanged.connect(self.viewRangeChanged) #self._connectedView = weakref.ref(view) #self.setNewBounds() def boundingRect(self): if self._boundingRect is None: br = self.viewRect() if br is None: return QtCore.QRectF() else: self._boundingRect = br return QtCore.QRectF(self._boundingRect) def dataBounds(self, axis, frac=1.0, orthoRange=None): """Called by ViewBox for determining the auto-range bounds. By default, UIGraphicsItems are excluded from autoRange.""" return None def viewRangeChanged(self): """Called when the view widget/viewbox is resized/rescaled""" self.setNewBounds() self.update() def setNewBounds(self): """Update the item's bounding rect to match the viewport""" self._boundingRect = None ## invalidate bounding rect, regenerate later if needed. self.prepareGeometryChange() def setPos(self, *args): GraphicsObject.setPos(self, *args) self.setNewBounds() def mouseShape(self): """Return the shape of this item after expanding by 2 pixels""" shape = self.shape() ds = self.mapToDevice(shape) stroker = QtGui.QPainterPathStroker() stroker.setWidh(2) ds2 = stroker.createStroke(ds).united(ds) return self.mapFromDevice(ds2)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/__init__.py
.py
585
22
### just import everything from sub-modules #import os #d = os.path.split(__file__)[0] #files = [] #for f in os.listdir(d): #if os.path.isdir(os.path.join(d, f)): #files.append(f) #elif f[-3:] == '.py' and f != '__init__.py': #files.append(f[:-3]) #for modName in files: #mod = __import__(modName, globals(), locals(), fromlist=['*']) #if hasattr(mod, '__all__'): #names = mod.__all__ #else: #names = [n for n in dir(mod) if n[0] != '_'] #for k in names: ##print modName, k #globals()[k] = getattr(mod, k)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/GraphicsItem.py
.py
23,608
591
from ..Qt import QtGui, QtCore, isQObjectAlive from ..GraphicsScene import GraphicsScene from ..Point import Point from .. import functions as fn import weakref import operator from ..util.lru_cache import LRUCache class GraphicsItem(object): """ **Bases:** :class:`object` Abstract class providing useful methods to GraphicsObject and GraphicsWidget. (This is required because we cannot have multiple inheritance with QObject subclasses.) A note about Qt's GraphicsView framework: The GraphicsView system places a lot of emphasis on the notion that the graphics within the scene should be device independent--you should be able to take the same graphics and display them on screens of different resolutions, printers, export to SVG, etc. This is nice in principle, but causes me a lot of headache in practice. It means that I have to circumvent all the device-independent expectations any time I want to operate in pixel coordinates rather than arbitrary scene coordinates. A lot of the code in GraphicsItem is devoted to this task--keeping track of view widgets and device transforms, computing the size and shape of a pixel in local item coordinates, etc. Note that in item coordinates, a pixel does not have to be square or even rectangular, so just asking how to increase a bounding rect by 2px can be a rather complex task. """ _pixelVectorGlobalCache = LRUCache(100, 70) def __init__(self, register=None): if not hasattr(self, '_qtBaseClass'): for b in self.__class__.__bases__: if issubclass(b, QtGui.QGraphicsItem): self.__class__._qtBaseClass = b break if not hasattr(self, '_qtBaseClass'): raise Exception('Could not determine Qt base class for GraphicsItem: %s' % str(self)) self._pixelVectorCache = [None, None] self._viewWidget = None self._viewBox = None self._connectedView = None self._exportOpts = False ## If False, not currently exporting. Otherwise, contains dict of export options. if register is not None and register: warnings.warn( "'register' argument is deprecated and does nothing", DeprecationWarning, stacklevel=2 ) def getViewWidget(self): """ Return the view widget for this item. If the scene has multiple views, only the first view is returned. The return value is cached; clear the cached value with forgetViewWidget(). If the view has been deleted by Qt, return None. """ if self._viewWidget is None: scene = self.scene() if scene is None: return None views = scene.views() if len(views) < 1: return None self._viewWidget = weakref.ref(self.scene().views()[0]) v = self._viewWidget() if v is not None and not isQObjectAlive(v): return None return v def forgetViewWidget(self): self._viewWidget = None def getViewBox(self): """ Return the first ViewBox or GraphicsView which bounds this item's visible space. If this item is not contained within a ViewBox, then the GraphicsView is returned. If the item is contained inside nested ViewBoxes, then the inner-most ViewBox is returned. The result is cached; clear the cache with forgetViewBox() """ if self._viewBox is None: p = self while True: try: p = p.parentItem() except RuntimeError: ## sometimes happens as items are being removed from a scene and collected. return None if p is None: vb = self.getViewWidget() if vb is None: return None else: self._viewBox = weakref.ref(vb) break if hasattr(p, 'implements') and p.implements('ViewBox'): self._viewBox = weakref.ref(p) break return self._viewBox() ## If we made it this far, _viewBox is definitely not None def forgetViewBox(self): self._viewBox = None def deviceTransform(self, viewportTransform=None): """ Return the transform that converts local item coordinates to device coordinates (usually pixels). Extends deviceTransform to automatically determine the viewportTransform. """ if self._exportOpts is not False and 'painter' in self._exportOpts: ## currently exporting; device transform may be different. scaler = self._exportOpts.get('resolutionScale', 1.0) return self.sceneTransform() * QtGui.QTransform(scaler, 0, 0, scaler, 1, 1) if viewportTransform is None: view = self.getViewWidget() if view is None: return None viewportTransform = view.viewportTransform() dt = self._qtBaseClass.deviceTransform(self, viewportTransform) #xmag = abs(dt.m11())+abs(dt.m12()) #ymag = abs(dt.m21())+abs(dt.m22()) #if xmag * ymag == 0: if dt.determinant() == 0: ## occurs when deviceTransform is invalid because widget has not been displayed return None else: return dt def viewTransform(self): """Return the transform that maps from local coordinates to the item's ViewBox coordinates If there is no ViewBox, return the scene transform. Returns None if the item does not have a view.""" view = self.getViewBox() if view is None: return None if hasattr(view, 'implements') and view.implements('ViewBox'): tr = self.itemTransform(view.innerSceneItem()) if isinstance(tr, tuple): tr = tr[0] ## difference between pyside and pyqt return tr else: return self.sceneTransform() #return self.deviceTransform(view.viewportTransform()) def getBoundingParents(self): """Return a list of parents to this item that have child clipping enabled.""" p = self parents = [] while True: p = p.parentItem() if p is None: break if p.flags() & self.ItemClipsChildrenToShape: parents.append(p) return parents def viewRect(self): """Return the visible bounds of this item's ViewBox or GraphicsWidget, in the local coordinate system of the item.""" view = self.getViewBox() if view is None: return None bounds = self.mapRectFromView(view.viewRect()) if bounds is None: return None bounds = bounds.normalized() ## nah. #for p in self.getBoundingParents(): #bounds &= self.mapRectFromScene(p.sceneBoundingRect()) return bounds def pixelVectors(self, direction=None): """Return vectors in local coordinates representing the width and height of a view pixel. If direction is specified, then return vectors parallel and orthogonal to it. Return (None, None) if pixel size is not yet defined (usually because the item has not yet been displayed) or if pixel size is below floating-point precision limit. """ ## This is an expensive function that gets called very frequently. ## We have two levels of cache to try speeding things up. dt = self.deviceTransform() if dt is None: return None, None ## Ignore translation. If the translation is much larger than the scale ## (such as when looking at unix timestamps), we can get floating-point errors. dt.setMatrix(dt.m11(), dt.m12(), 0, dt.m21(), dt.m22(), 0, 0, 0, 1) ## check local cache if direction is None and dt == self._pixelVectorCache[0]: return tuple(map(Point, self._pixelVectorCache[1])) ## return a *copy* ## check global cache #key = (dt.m11(), dt.m21(), dt.m31(), dt.m12(), dt.m22(), dt.m32(), dt.m31(), dt.m32()) key = (dt.m11(), dt.m21(), dt.m12(), dt.m22()) pv = self._pixelVectorGlobalCache.get(key, None) if direction is None and pv is not None: self._pixelVectorCache = [dt, pv] return tuple(map(Point,pv)) ## return a *copy* if direction is None: direction = QtCore.QPointF(1, 0) if direction.manhattanLength() == 0: raise Exception("Cannot compute pixel length for 0-length vector.") ## attempt to re-scale direction vector to fit within the precision of the coordinate system ## Here's the problem: we need to map the vector 'direction' from the item to the device, via transform 'dt'. ## In some extreme cases, this mapping can fail unless the length of 'direction' is cleverly chosen. ## Example: ## dt = [ 1, 0, 2 ## 0, 2, 1e20 ## 0, 0, 1 ] ## Then we map the origin (0,0) and direction (0,1) and get: ## o' = 2,1e20 ## d' = 2,1e20 <-- should be 1e20+2, but this can't be represented with a 32-bit float ## ## |o' - d'| == 0 <-- this is the problem. ## Perhaps the easiest solution is to exclude the transformation column from dt. Does this cause any other problems? #if direction.x() == 0: #r = abs(dt.m32())/(abs(dt.m12()) + abs(dt.m22())) ##r = 1.0/(abs(dt.m12()) + abs(dt.m22())) #elif direction.y() == 0: #r = abs(dt.m31())/(abs(dt.m11()) + abs(dt.m21())) ##r = 1.0/(abs(dt.m11()) + abs(dt.m21())) #else: #r = ((abs(dt.m32())/(abs(dt.m12()) + abs(dt.m22()))) * (abs(dt.m31())/(abs(dt.m11()) + abs(dt.m21()))))**0.5 #if r == 0: #r = 1. ## shouldn't need to do this; probably means the math above is wrong? #directionr = direction * r directionr = direction ## map direction vector onto device #viewDir = Point(dt.map(directionr) - dt.map(Point(0,0))) #mdirection = dt.map(directionr) dirLine = QtCore.QLineF(QtCore.QPointF(0,0), directionr) viewDir = dt.map(dirLine) if viewDir.length() == 0: return None, None ## pixel size cannot be represented on this scale ## get unit vector and orthogonal vector (length of pixel) #orthoDir = Point(viewDir[1], -viewDir[0]) ## orthogonal to line in pixel-space try: normView = viewDir.unitVector() #normView = viewDir.norm() ## direction of one pixel orthogonal to line normOrtho = normView.normalVector() #normOrtho = orthoDir.norm() except: raise Exception("Invalid direction %s" %directionr) ## map back to item dti = fn.invertQTransform(dt) #pv = Point(dti.map(normView)-dti.map(Point(0,0))), Point(dti.map(normOrtho)-dti.map(Point(0,0))) pv = Point(dti.map(normView).p2()), Point(dti.map(normOrtho).p2()) self._pixelVectorCache[1] = pv self._pixelVectorCache[0] = dt self._pixelVectorGlobalCache[key] = pv return self._pixelVectorCache[1] def pixelLength(self, direction, ortho=False): """Return the length of one pixel in the direction indicated (in local coordinates) If ortho=True, then return the length of one pixel orthogonal to the direction indicated. Return None if pixel size is not yet defined (usually because the item has not yet been displayed). """ normV, orthoV = self.pixelVectors(direction) if normV == None or orthoV == None: return None if ortho: return orthoV.length() return normV.length() def pixelSize(self): ## deprecated v = self.pixelVectors() if v == (None, None): return None, None return (v[0].x()**2+v[0].y()**2)**0.5, (v[1].x()**2+v[1].y()**2)**0.5 def pixelWidth(self): ## deprecated vt = self.deviceTransform() if vt is None: return 0 vt = fn.invertQTransform(vt) return vt.map(QtCore.QLineF(0, 0, 1, 0)).length() def pixelHeight(self): ## deprecated vt = self.deviceTransform() if vt is None: return 0 vt = fn.invertQTransform(vt) return vt.map(QtCore.QLineF(0, 0, 0, 1)).length() #return Point(vt.map(QtCore.QPointF(0, 1))-vt.map(QtCore.QPointF(0, 0))).length() def mapToDevice(self, obj): """ Return *obj* mapped from local coordinates to device coordinates (pixels). If there is no device mapping available, return None. """ vt = self.deviceTransform() if vt is None: return None return vt.map(obj) def mapFromDevice(self, obj): """ Return *obj* mapped from device coordinates (pixels) to local coordinates. If there is no device mapping available, return None. """ vt = self.deviceTransform() if vt is None: return None if isinstance(obj, QtCore.QPoint): obj = QtCore.QPointF(obj) vt = fn.invertQTransform(vt) return vt.map(obj) def mapRectToDevice(self, rect): """ Return *rect* mapped from local coordinates to device coordinates (pixels). If there is no device mapping available, return None. """ vt = self.deviceTransform() if vt is None: return None return vt.mapRect(rect) def mapRectFromDevice(self, rect): """ Return *rect* mapped from device coordinates (pixels) to local coordinates. If there is no device mapping available, return None. """ vt = self.deviceTransform() if vt is None: return None vt = fn.invertQTransform(vt) return vt.mapRect(rect) def mapToView(self, obj): vt = self.viewTransform() if vt is None: return None return vt.map(obj) def mapRectToView(self, obj): vt = self.viewTransform() if vt is None: return None return vt.mapRect(obj) def mapFromView(self, obj): vt = self.viewTransform() if vt is None: return None vt = fn.invertQTransform(vt) return vt.map(obj) def mapRectFromView(self, obj): vt = self.viewTransform() if vt is None: return None vt = fn.invertQTransform(vt) return vt.mapRect(obj) def pos(self): return Point(self._qtBaseClass.pos(self)) def viewPos(self): return self.mapToView(self.mapFromParent(self.pos())) def parentItem(self): ## PyQt bug -- some items are returned incorrectly. return GraphicsScene.translateGraphicsItem(self._qtBaseClass.parentItem(self)) def setParentItem(self, parent): ## Workaround for Qt bug: https://bugreports.qt-project.org/browse/QTBUG-18616 if parent is not None: pscene = parent.scene() if pscene is not None and self.scene() is not pscene: pscene.addItem(self) return self._qtBaseClass.setParentItem(self, parent) def childItems(self): ## PyQt bug -- some child items are returned incorrectly. return list(map(GraphicsScene.translateGraphicsItem, self._qtBaseClass.childItems(self))) def sceneTransform(self): ## Qt bug: do no allow access to sceneTransform() until ## the item has a scene. if self.scene() is None: return self.transform() else: return self._qtBaseClass.sceneTransform(self) def transformAngle(self, relativeItem=None): """Return the rotation produced by this item's transform (this assumes there is no shear in the transform) If relativeItem is given, then the angle is determined relative to that item. """ if relativeItem is None: relativeItem = self.parentItem() tr = self.itemTransform(relativeItem) if isinstance(tr, tuple): ## difference between pyside and pyqt tr = tr[0] #vec = tr.map(Point(1,0)) - tr.map(Point(0,0)) vec = tr.map(QtCore.QLineF(0,0,1,0)) #return Point(vec).angle(Point(1,0)) return vec.angleTo(QtCore.QLineF(vec.p1(), vec.p1()+QtCore.QPointF(1,0))) #def itemChange(self, change, value): #ret = self._qtBaseClass.itemChange(self, change, value) #if change == self.ItemParentHasChanged or change == self.ItemSceneHasChanged: #print "Item scene changed:", self #self.setChildScene(self) ## This is bizarre. #return ret #def setChildScene(self, ch): #scene = self.scene() #for ch2 in ch.childItems(): #if ch2.scene() is not scene: #print "item", ch2, "has different scene:", ch2.scene(), scene #scene.addItem(ch2) #QtGui.QApplication.processEvents() #print " --> ", ch2.scene() #self.setChildScene(ch2) def parentChanged(self): """Called when the item's parent has changed. This method handles connecting / disconnecting from ViewBox signals to make sure viewRangeChanged works properly. It should generally be extended, not overridden.""" self._updateView() def _updateView(self): ## called to see whether this item has a new view to connect to ## NOTE: This is called from GraphicsObject.itemChange or GraphicsWidget.itemChange. if not hasattr(self, '_connectedView'): # Happens when Python is shutting down. return ## It is possible this item has moved to a different ViewBox or widget; ## clear out previously determined references to these. self.forgetViewBox() self.forgetViewWidget() ## check for this item's current viewbox or view widget view = self.getViewBox() #if view is None: ##print " no view" #return oldView = None if self._connectedView is not None: oldView = self._connectedView() if view is oldView: #print " already have view", view return ## disconnect from previous view if oldView is not None: for signal, slot in [('sigRangeChanged', self.viewRangeChanged), ('sigDeviceRangeChanged', self.viewRangeChanged), ('sigTransformChanged', self.viewTransformChanged), ('sigDeviceTransformChanged', self.viewTransformChanged)]: try: getattr(oldView, signal).disconnect(slot) except (TypeError, AttributeError, RuntimeError): # TypeError and RuntimeError are from pyqt and pyside, respectively pass self._connectedView = None ## connect to new view if view is not None: #print "connect:", self, view if hasattr(view, 'sigDeviceRangeChanged'): # connect signals from GraphicsView view.sigDeviceRangeChanged.connect(self.viewRangeChanged) view.sigDeviceTransformChanged.connect(self.viewTransformChanged) else: # connect signals from ViewBox view.sigRangeChanged.connect(self.viewRangeChanged) view.sigTransformChanged.connect(self.viewTransformChanged) self._connectedView = weakref.ref(view) self.viewRangeChanged() self.viewTransformChanged() ## inform children that their view might have changed self._replaceView(oldView) self.viewChanged(view, oldView) def viewChanged(self, view, oldView): """Called when this item's view has changed (ie, the item has been added to or removed from a ViewBox)""" pass def _replaceView(self, oldView, item=None): if item is None: item = self for child in item.childItems(): if isinstance(child, GraphicsItem): if child.getViewBox() is oldView: child._updateView() #self._replaceView(oldView, child) else: self._replaceView(oldView, child) def viewRangeChanged(self): """ Called whenever the view coordinates of the ViewBox containing this item have changed. """ pass def viewTransformChanged(self): """ Called whenever the transformation matrix of the view has changed. (eg, the view range has changed or the view was resized) """ pass #def prepareGeometryChange(self): #self._qtBaseClass.prepareGeometryChange(self) #self.informViewBoundsChanged() def informViewBoundsChanged(self): """ Inform this item's container ViewBox that the bounds of this item have changed. This is used by ViewBox to react if auto-range is enabled. """ view = self.getViewBox() if view is not None and hasattr(view, 'implements') and view.implements('ViewBox'): view.itemBoundsChanged(self) ## inform view so it can update its range if it wants def childrenShape(self): """Return the union of the shapes of all descendants of this item in local coordinates.""" childs = self.allChildItems() shapes = [self.mapFromItem(c, c.shape()) for c in self.allChildItems()] return reduce(operator.add, shapes) def allChildItems(self, root=None): """Return list of the entire item tree descending from this item.""" if root is None: root = self tree = [] for ch in root.childItems(): tree.append(ch) tree.extend(self.allChildItems(ch)) return tree def setExportMode(self, export, opts=None): """ This method is called by exporters to inform items that they are being drawn for export with a specific set of options. Items access these via self._exportOptions. When exporting is complete, _exportOptions is set to False. """ if opts is None: opts = {} if export: self._exportOpts = opts #if 'antialias' not in opts: #self._exportOpts['antialias'] = True else: self._exportOpts = False #def update(self): #self._qtBaseClass.update(self) #print "Update:", self def getContextMenus(self, event): return [self.getMenu()] if hasattr(self, "getMenu") else []
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/VTickGroup.py
.py
3,517
99
if __name__ == '__main__': import os, sys path = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(path, '..', '..')) from ..Qt import QtGui, QtCore from .. import functions as fn import weakref from .UIGraphicsItem import UIGraphicsItem __all__ = ['VTickGroup'] class VTickGroup(UIGraphicsItem): """ **Bases:** :class:`UIGraphicsItem <pyqtgraph.UIGraphicsItem>` Draws a set of tick marks which always occupy the same vertical range of the view, but have x coordinates relative to the data within the view. """ def __init__(self, xvals=None, yrange=None, pen=None): """ ============== =================================================================== **Arguments:** xvals A list of x values (in data coordinates) at which to draw ticks. yrange A list of [low, high] limits for the tick. 0 is the bottom of the view, 1 is the top. [0.8, 1] would draw ticks in the top fifth of the view. pen The pen to use for drawing ticks. Default is grey. Can be specified as any argument valid for :func:`mkPen<pyqtgraph.mkPen>` ============== =================================================================== """ if yrange is None: yrange = [0, 1] if xvals is None: xvals = [] UIGraphicsItem.__init__(self) if pen is None: pen = (200, 200, 200) self.path = QtGui.QGraphicsPathItem() self.ticks = [] self.xvals = [] self.yrange = [0,1] self.setPen(pen) self.setYRange(yrange) self.setXVals(xvals) def setPen(self, *args, **kwargs): """Set the pen to use for drawing ticks. Can be specified as any arguments valid for :func:`mkPen<pyqtgraph.mkPen>`""" self.pen = fn.mkPen(*args, **kwargs) def setXVals(self, vals): """Set the x values for the ticks. ============== ===================================================================== **Arguments:** vals A list of x values (in data/plot coordinates) at which to draw ticks. ============== ===================================================================== """ self.xvals = vals self.rebuildTicks() #self.valid = False def setYRange(self, vals): """Set the y range [low, high] that the ticks are drawn on. 0 is the bottom of the view, 1 is the top.""" self.yrange = vals self.rebuildTicks() def dataBounds(self, *args, **kargs): return None ## item should never affect view autoscaling def yRange(self): return self.yrange def rebuildTicks(self): self.path = QtGui.QPainterPath() yrange = self.yRange() for x in self.xvals: self.path.moveTo(x, 0.) self.path.lineTo(x, 1.) def paint(self, p, *args): UIGraphicsItem.paint(self, p, *args) br = self.boundingRect() h = br.height() br.setY(br.y() + self.yrange[0] * h) br.setHeight((self.yrange[1] - self.yrange[0]) * h) p.translate(0, br.y()) p.scale(1.0, br.height()) p.setPen(self.pen) p.drawPath(self.path)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/BarGraphItem.py
.py
5,188
182
from ..Qt import QtGui, QtCore from .GraphicsObject import GraphicsObject from .. import getConfigOption from .. import functions as fn import numpy as np __all__ = ['BarGraphItem'] class BarGraphItem(GraphicsObject): def __init__(self, **opts): """ Valid keyword options are: x, x0, x1, y, y0, y1, width, height, pen, brush x specifies the x-position of the center of the bar. x0, x1 specify left and right edges of the bar, respectively. width specifies distance from x0 to x1. You may specify any combination: x, width x0, width x1, width x0, x1 Likewise y, y0, y1, and height. If only height is specified, then y0 will be set to 0 Example uses: BarGraphItem(x=range(5), height=[1,5,2,4,3], width=0.5) """ GraphicsObject.__init__(self) self.opts = dict( x=None, y=None, x0=None, y0=None, x1=None, y1=None, name=None, height=None, width=None, pen=None, brush=None, pens=None, brushes=None, ) self._shape = None self.picture = None self.setOpts(**opts) def setOpts(self, **opts): self.opts.update(opts) self.picture = None self._shape = None self.update() self.informViewBoundsChanged() def drawPicture(self): self.picture = QtGui.QPicture() self._shape = QtGui.QPainterPath() p = QtGui.QPainter(self.picture) pen = self.opts['pen'] pens = self.opts['pens'] if pen is None and pens is None: pen = getConfigOption('foreground') brush = self.opts['brush'] brushes = self.opts['brushes'] if brush is None and brushes is None: brush = (128, 128, 128) def asarray(x): if x is None or np.isscalar(x) or isinstance(x, np.ndarray): return x return np.array(x) x = asarray(self.opts.get('x')) x0 = asarray(self.opts.get('x0')) x1 = asarray(self.opts.get('x1')) width = asarray(self.opts.get('width')) if x0 is None: if width is None: raise Exception('must specify either x0 or width') if x1 is not None: x0 = x1 - width elif x is not None: x0 = x - width/2. else: raise Exception('must specify at least one of x, x0, or x1') if width is None: if x1 is None: raise Exception('must specify either x1 or width') width = x1 - x0 y = asarray(self.opts.get('y')) y0 = asarray(self.opts.get('y0')) y1 = asarray(self.opts.get('y1')) height = asarray(self.opts.get('height')) if y0 is None: if height is None: y0 = 0 elif y1 is not None: y0 = y1 - height elif y is not None: y0 = y - height/2. else: y0 = 0 if height is None: if y1 is None: raise Exception('must specify either y1 or height') height = y1 - y0 p.setPen(fn.mkPen(pen)) p.setBrush(fn.mkBrush(brush)) for i in range(len(x0 if not np.isscalar(x0) else y0)): if pens is not None: p.setPen(fn.mkPen(pens[i])) if brushes is not None: p.setBrush(fn.mkBrush(brushes[i])) if np.isscalar(x0): x = x0 else: x = x0[i] if np.isscalar(y0): y = y0 else: y = y0[i] if np.isscalar(width): w = width else: w = width[i] if np.isscalar(height): h = height else: h = height[i] rect = QtCore.QRectF(x, y, w, h) p.drawRect(rect) self._shape.addRect(rect) p.end() self.prepareGeometryChange() def paint(self, p, *args): if self.picture is None: self.drawPicture() self.picture.play(p) def boundingRect(self): if self.picture is None: self.drawPicture() return QtCore.QRectF(self.picture.boundingRect()) def shape(self): if self.picture is None: self.drawPicture() return self._shape def implements(self, interface=None): ints = ['plotData'] if interface is None: return ints return interface in ints def name(self): return self.opts.get('name', None) def getData(self): return self.opts.get('x'), self.opts.get('height')
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/GradientLegend.py
.py
4,278
115
from ..Qt import QtGui, QtCore from .UIGraphicsItem import * from .. import functions as fn __all__ = ['GradientLegend'] class GradientLegend(UIGraphicsItem): """ Draws a color gradient rectangle along with text labels denoting the value at specific points along the gradient. """ def __init__(self, size, offset): self.size = size self.offset = offset UIGraphicsItem.__init__(self) self.setAcceptedMouseButtons(QtCore.Qt.NoButton) self.brush = QtGui.QBrush(QtGui.QColor(200,0,0)) self.pen = QtGui.QPen(QtGui.QColor(0,0,0)) self.labels = {'max': 1, 'min': 0} self.gradient = QtGui.QLinearGradient() self.gradient.setColorAt(0, QtGui.QColor(0,0,0)) self.gradient.setColorAt(1, QtGui.QColor(255,0,0)) def setGradient(self, g): self.gradient = g self.update() def setIntColorScale(self, minVal, maxVal, *args, **kargs): colors = [fn.intColor(i, maxVal-minVal, *args, **kargs) for i in range(minVal, maxVal)] g = QtGui.QLinearGradient() for i in range(len(colors)): x = float(i)/len(colors) g.setColorAt(x, colors[i]) self.setGradient(g) if 'labels' not in kargs: self.setLabels({str(minVal/10.): 0, str(maxVal): 1}) else: self.setLabels({kargs['labels'][0]:0, kargs['labels'][1]:1}) def setLabels(self, l): """Defines labels to appear next to the color scale. Accepts a dict of {text: value} pairs""" self.labels = l self.update() def paint(self, p, opt, widget): UIGraphicsItem.paint(self, p, opt, widget) rect = self.boundingRect() ## Boundaries of visible area in scene coords. unit = self.pixelSize() ## Size of one view pixel in scene coords. if unit[0] is None: return ## determine max width of all labels labelWidth = 0 labelHeight = 0 for k in self.labels: b = p.boundingRect(QtCore.QRectF(0, 0, 0, 0), QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter, str(k)) labelWidth = max(labelWidth, b.width()) labelHeight = max(labelHeight, b.height()) labelWidth *= unit[0] labelHeight *= unit[1] textPadding = 2 # in px if self.offset[0] < 0: x3 = rect.right() + unit[0] * self.offset[0] x2 = x3 - labelWidth - unit[0]*textPadding*2 x1 = x2 - unit[0] * self.size[0] else: x1 = rect.left() + unit[0] * self.offset[0] x2 = x1 + unit[0] * self.size[0] x3 = x2 + labelWidth + unit[0]*textPadding*2 if self.offset[1] < 0: y2 = rect.top() - unit[1] * self.offset[1] y1 = y2 + unit[1] * self.size[1] else: y1 = rect.bottom() - unit[1] * self.offset[1] y2 = y1 - unit[1] * self.size[1] self.b = [x1,x2,x3,y1,y2,labelWidth] ## Draw background p.setPen(self.pen) p.setBrush(QtGui.QBrush(QtGui.QColor(255,255,255,100))) rect = QtCore.QRectF( QtCore.QPointF(x1 - unit[0]*textPadding, y1 + labelHeight/2 + unit[1]*textPadding), QtCore.QPointF(x3, y2 - labelHeight/2 - unit[1]*textPadding) ) p.drawRect(rect) ## Have to scale painter so that text and gradients are correct size. Bleh. p.scale(unit[0], unit[1]) ## Draw color bar self.gradient.setStart(0, y1/unit[1]) self.gradient.setFinalStop(0, y2/unit[1]) p.setBrush(self.gradient) rect = QtCore.QRectF( QtCore.QPointF(x1/unit[0], y1/unit[1]), QtCore.QPointF(x2/unit[0], y2/unit[1]) ) p.drawRect(rect) ## draw labels p.setPen(QtGui.QPen(QtGui.QColor(0,0,0))) tx = x2 + unit[0]*textPadding lh = labelHeight/unit[1] for k in self.labels: y = y1 + self.labels[k] * (y2-y1) p.drawText(QtCore.QRectF(tx/unit[0], y/unit[1] - lh/2.0, 1000, lh), QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter, str(k))
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/ImageItem.py
.py
25,570
662
from __future__ import division from ..Qt import QtGui, QtCore import numpy as np from .. import functions as fn from .. import debug as debug from .GraphicsObject import GraphicsObject from ..Point import Point from .. import getConfigOption try: from collections.abc import Callable except ImportError: # fallback for python < 3.3 from collections import Callable __all__ = ['ImageItem'] class ImageItem(GraphicsObject): """ **Bases:** :class:`GraphicsObject <pyqtgraph.GraphicsObject>` GraphicsObject displaying an image. Optimized for rapid update (ie video display). This item displays either a 2D numpy array (height, width) or a 3D array (height, width, RGBa). This array is optionally scaled (see :func:`setLevels <pyqtgraph.ImageItem.setLevels>`) and/or colored with a lookup table (see :func:`setLookupTable <pyqtgraph.ImageItem.setLookupTable>`) before being displayed. ImageItem is frequently used in conjunction with :class:`HistogramLUTItem <pyqtgraph.HistogramLUTItem>` or :class:`HistogramLUTWidget <pyqtgraph.HistogramLUTWidget>` to provide a GUI for controlling the levels and lookup table used to display the image. """ sigImageChanged = QtCore.Signal() sigRemoveRequested = QtCore.Signal(object) # self; emitted when 'remove' is selected from context menu def __init__(self, image=None, **kargs): """ See :func:`setImage <pyqtgraph.ImageItem.setImage>` for all allowed initialization arguments. """ GraphicsObject.__init__(self) self.menu = None self.image = None ## original image data self.qimage = None ## rendered image for display self.paintMode = None self.levels = None ## [min, max] or [[redMin, redMax], ...] self.lut = None self.autoDownsample = False self.axisOrder = getConfigOption('imageAxisOrder') # In some cases, we use a modified lookup table to handle both rescaling # and LUT more efficiently self._effectiveLut = None self.drawKernel = None self.border = None self.removable = False if image is not None: self.setImage(image, **kargs) else: self.setOpts(**kargs) def setCompositionMode(self, mode): """Change the composition mode of the item (see QPainter::CompositionMode in the Qt documentation). This is useful when overlaying multiple ImageItems. ============================================ ============================================================ **Most common arguments:** QtGui.QPainter.CompositionMode_SourceOver Default; image replaces the background if it is opaque. Otherwise, it uses the alpha channel to blend the image with the background. QtGui.QPainter.CompositionMode_Overlay The image color is mixed with the background color to reflect the lightness or darkness of the background. QtGui.QPainter.CompositionMode_Plus Both the alpha and color of the image and background pixels are added together. QtGui.QPainter.CompositionMode_Multiply The output is the image color multiplied by the background. ============================================ ============================================================ """ self.paintMode = mode self.update() def setBorder(self, b): self.border = fn.mkPen(b) self.update() def width(self): if self.image is None: return None axis = 0 if self.axisOrder == 'col-major' else 1 return self.image.shape[axis] def height(self): if self.image is None: return None axis = 1 if self.axisOrder == 'col-major' else 0 return self.image.shape[axis] def channels(self): if self.image is None: return None return self.image.shape[2] if self.image.ndim == 3 else 1 def boundingRect(self): if self.image is None: return QtCore.QRectF(0., 0., 0., 0.) return QtCore.QRectF(0., 0., float(self.width()), float(self.height())) def setLevels(self, levels, update=True): """ Set image scaling levels. Can be one of: * [blackLevel, whiteLevel] * [[minRed, maxRed], [minGreen, maxGreen], [minBlue, maxBlue]] Only the first format is compatible with lookup tables. See :func:`makeARGB <pyqtgraph.makeARGB>` for more details on how levels are applied. """ if levels is not None: levels = np.asarray(levels) if not fn.eq(levels, self.levels): self.levels = levels self._effectiveLut = None if update: self.updateImage() def getLevels(self): return self.levels #return self.whiteLevel, self.blackLevel def setLookupTable(self, lut, update=True): """ Set the lookup table (numpy array) to use for this image. (see :func:`makeARGB <pyqtgraph.makeARGB>` for more information on how this is used). Optionally, lut can be a callable that accepts the current image as an argument and returns the lookup table to use. Ordinarily, this table is supplied by a :class:`HistogramLUTItem <pyqtgraph.HistogramLUTItem>` or :class:`GradientEditorItem <pyqtgraph.GradientEditorItem>`. """ if lut is not self.lut: self.lut = lut self._effectiveLut = None if update: self.updateImage() def setAutoDownsample(self, ads): """ Set the automatic downsampling mode for this ImageItem. Added in version 0.9.9 """ self.autoDownsample = ads self.qimage = None self.update() def setOpts(self, update=True, **kargs): if 'axisOrder' in kargs: val = kargs['axisOrder'] if val not in ('row-major', 'col-major'): raise ValueError('axisOrder must be either "row-major" or "col-major"') self.axisOrder = val if 'lut' in kargs: self.setLookupTable(kargs['lut'], update=update) if 'levels' in kargs: self.setLevels(kargs['levels'], update=update) #if 'clipLevel' in kargs: #self.setClipLevel(kargs['clipLevel']) if 'opacity' in kargs: self.setOpacity(kargs['opacity']) if 'compositionMode' in kargs: self.setCompositionMode(kargs['compositionMode']) if 'border' in kargs: self.setBorder(kargs['border']) if 'removable' in kargs: self.removable = kargs['removable'] self.menu = None if 'autoDownsample' in kargs: self.setAutoDownsample(kargs['autoDownsample']) if update: self.update() def setRect(self, rect): """Scale and translate the image to fit within rect (must be a QRect or QRectF).""" self.resetTransform() self.translate(rect.left(), rect.top()) self.scale(rect.width() / self.width(), rect.height() / self.height()) def clear(self): self.image = None self.prepareGeometryChange() self.informViewBoundsChanged() self.update() def setImage(self, image=None, autoLevels=None, **kargs): """ Update the image displayed by this item. For more information on how the image is processed before displaying, see :func:`makeARGB <pyqtgraph.makeARGB>` ================= ========================================================================= **Arguments:** image (numpy array) Specifies the image data. May be 2D (width, height) or 3D (width, height, RGBa). The array dtype must be integer or floating point of any bit depth. For 3D arrays, the third dimension must be of length 3 (RGB) or 4 (RGBA). See *notes* below. autoLevels (bool) If True, this forces the image to automatically select levels based on the maximum and minimum values in the data. By default, this argument is true unless the levels argument is given. lut (numpy array) The color lookup table to use when displaying the image. See :func:`setLookupTable <pyqtgraph.ImageItem.setLookupTable>`. levels (min, max) The minimum and maximum values to use when rescaling the image data. By default, this will be set to the minimum and maximum values in the image. If the image array has dtype uint8, no rescaling is necessary. opacity (float 0.0-1.0) compositionMode See :func:`setCompositionMode <pyqtgraph.ImageItem.setCompositionMode>` border Sets the pen used when drawing the image border. Default is None. autoDownsample (bool) If True, the image is automatically downsampled to match the screen resolution. This improves performance for large images and reduces aliasing. If autoDownsample is not specified, then ImageItem will choose whether to downsample the image based on its size. ================= ========================================================================= **Notes:** For backward compatibility, image data is assumed to be in column-major order (column, row). However, most image data is stored in row-major order (row, column) and will need to be transposed before calling setImage():: imageitem.setImage(imagedata.T) This requirement can be changed by calling ``image.setOpts(axisOrder='row-major')`` or by changing the ``imageAxisOrder`` :ref:`global configuration option <apiref_config>`. """ profile = debug.Profiler() gotNewData = False if image is None: if self.image is None: return else: gotNewData = True shapeChanged = (self.image is None or image.shape != self.image.shape) image = image.view(np.ndarray) if self.image is None or image.dtype != self.image.dtype: self._effectiveLut = None self.image = image if self.image.shape[0] > 2**15-1 or self.image.shape[1] > 2**15-1: if 'autoDownsample' not in kargs: kargs['autoDownsample'] = True if shapeChanged: self.prepareGeometryChange() self.informViewBoundsChanged() profile() if autoLevels is None: if 'levels' in kargs: autoLevels = False else: autoLevels = True if autoLevels: img = self.image while img.size > 2**16: img = img[::2, ::2] mn, mx = np.nanmin(img), np.nanmax(img) # mn and mx can still be NaN if the data is all-NaN if mn == mx or np.isnan(mn) or np.isnan(mx): mn = 0 mx = 255 kargs['levels'] = [mn,mx] profile() self.setOpts(update=False, **kargs) profile() self.qimage = None self.update() profile() if gotNewData: self.sigImageChanged.emit() def dataTransform(self): """Return the transform that maps from this image's input array to its local coordinate system. This transform corrects for the transposition that occurs when image data is interpreted in row-major order. """ # Might eventually need to account for downsampling / clipping here tr = QtGui.QTransform() if self.axisOrder == 'row-major': # transpose tr.scale(1, -1) tr.rotate(-90) return tr def inverseDataTransform(self): """Return the transform that maps from this image's local coordinate system to its input array. See dataTransform() for more information. """ tr = QtGui.QTransform() if self.axisOrder == 'row-major': # transpose tr.scale(1, -1) tr.rotate(-90) return tr def mapToData(self, obj): tr = self.inverseDataTransform() return tr.map(obj) def mapFromData(self, obj): tr = self.dataTransform() return tr.map(obj) def quickMinMax(self, targetSize=1e6): """ Estimate the min/max values of the image data by subsampling. """ data = self.image while data.size > targetSize: ax = np.argmax(data.shape) sl = [slice(None)] * data.ndim sl[ax] = slice(None, None, 2) data = data[sl] return np.nanmin(data), np.nanmax(data) def updateImage(self, *args, **kargs): ## used for re-rendering qimage from self.image. ## can we make any assumptions here that speed things up? ## dtype, range, size are all the same? defaults = { 'autoLevels': False, } defaults.update(kargs) return self.setImage(*args, **defaults) def render(self): # Convert data to QImage for display. profile = debug.Profiler() if self.image is None or self.image.size == 0: return # Request a lookup table if this image has only one channel if self.image.ndim == 2 or self.image.shape[2] == 1: if isinstance(self.lut, Callable): lut = self.lut(self.image) else: lut = self.lut else: lut = None if self.autoDownsample: # reduce dimensions of image based on screen resolution o = self.mapToDevice(QtCore.QPointF(0,0)) x = self.mapToDevice(QtCore.QPointF(1,0)) y = self.mapToDevice(QtCore.QPointF(0,1)) # Check if graphics view is too small to render anything if o is None or x is None or y is None: return w = Point(x-o).length() h = Point(y-o).length() if w == 0 or h == 0: self.qimage = None return xds = max(1, int(1.0 / w)) yds = max(1, int(1.0 / h)) axes = [1, 0] if self.axisOrder == 'row-major' else [0, 1] image = fn.downsample(self.image, xds, axis=axes[0]) image = fn.downsample(image, yds, axis=axes[1]) self._lastDownsample = (xds, yds) # Check if downsampling reduced the image size to zero due to inf values. if image.size == 0: return else: image = self.image # if the image data is a small int, then we can combine levels + lut # into a single lut for better performance levels = self.levels if levels is not None and levels.ndim == 1 and image.dtype in (np.ubyte, np.uint16): if self._effectiveLut is None: eflsize = 2**(image.itemsize*8) ind = np.arange(eflsize) minlev, maxlev = levels levdiff = maxlev - minlev levdiff = 1 if levdiff == 0 else levdiff # don't allow division by 0 if lut is None: efflut = fn.rescaleData(ind, scale=255./levdiff, offset=minlev, dtype=np.ubyte) else: lutdtype = np.min_scalar_type(lut.shape[0]-1) efflut = fn.rescaleData(ind, scale=(lut.shape[0]-1)/levdiff, offset=minlev, dtype=lutdtype, clip=(0, lut.shape[0]-1)) efflut = lut[efflut] self._effectiveLut = efflut lut = self._effectiveLut levels = None # Convert single-channel image to 2D array if image.ndim == 3 and image.shape[-1] == 1: image = image[..., 0] # Assume images are in column-major order for backward compatibility # (most images are in row-major order) if self.axisOrder == 'col-major': image = image.transpose((1, 0, 2)[:image.ndim]) argb, alpha = fn.makeARGB(image, lut=lut, levels=levels) self.qimage = fn.makeQImage(argb, alpha, transpose=False) def paint(self, p, *args): profile = debug.Profiler() if self.image is None: return if self.qimage is None: self.render() if self.qimage is None: return profile('render QImage') if self.paintMode is not None: p.setCompositionMode(self.paintMode) profile('set comp mode') shape = self.image.shape[:2] if self.axisOrder == 'col-major' else self.image.shape[:2][::-1] p.drawImage(QtCore.QRectF(0,0,*shape), self.qimage) profile('p.drawImage') if self.border is not None: p.setPen(self.border) p.drawRect(self.boundingRect()) def save(self, fileName, *args): """Save this image to file. Note that this saves the visible image (after scale/color changes), not the original data.""" if self.qimage is None: self.render() self.qimage.save(fileName, *args) def getHistogram(self, bins='auto', step='auto', perChannel=False, targetImageSize=200, targetHistogramSize=500, **kwds): """Returns x and y arrays containing the histogram values for the current image. For an explanation of the return format, see numpy.histogram(). The *step* argument causes pixels to be skipped when computing the histogram to save time. If *step* is 'auto', then a step is chosen such that the analyzed data has dimensions roughly *targetImageSize* for each axis. The *bins* argument and any extra keyword arguments are passed to np.histogram(). If *bins* is 'auto', then a bin number is automatically chosen based on the image characteristics: * Integer images will have approximately *targetHistogramSize* bins, with each bin having an integer width. * All other types will have *targetHistogramSize* bins. If *perChannel* is True, then the histogram is computed once per channel and the output is a list of the results. This method is also used when automatically computing levels. """ if self.image is None or self.image.size == 0: return None, None if step == 'auto': step = (max(1, int(np.ceil(self.image.shape[0] / targetImageSize))), max(1, int(np.ceil(self.image.shape[1] / targetImageSize)))) if np.isscalar(step): step = (step, step) stepData = self.image[::step[0], ::step[1]] if isinstance(bins, str) and bins == 'auto': mn = np.nanmin(stepData) mx = np.nanmax(stepData) if mx == mn: # degenerate image, arange will fail mx += 1 if np.isnan(mn) or np.isnan(mx): # the data are all-nan return None, None if stepData.dtype.kind in "ui": # For integer data, we select the bins carefully to avoid aliasing step = np.ceil((mx-mn) / 500.) bins = np.arange(mn, mx+1.01*step, step, dtype=np.int) else: # for float data, let numpy select the bins. bins = np.linspace(mn, mx, 500) if len(bins) == 0: bins = [mn, mx] kwds['bins'] = bins if perChannel: hist = [] for i in range(stepData.shape[-1]): stepChan = stepData[..., i] stepChan = stepChan[np.isfinite(stepChan)] h = np.histogram(stepChan, **kwds) hist.append((h[1][:-1], h[0])) return hist else: stepData = stepData[np.isfinite(stepData)] hist = np.histogram(stepData, **kwds) return hist[1][:-1], hist[0] def setPxMode(self, b): """ Set whether the item ignores transformations and draws directly to screen pixels. If True, the item will not inherit any scale or rotation transformations from its parent items, but its position will be transformed as usual. (see GraphicsItem::ItemIgnoresTransformations in the Qt documentation) """ self.setFlag(self.ItemIgnoresTransformations, b) def setScaledMode(self): self.setPxMode(False) def getPixmap(self): if self.qimage is None: self.render() if self.qimage is None: return None return QtGui.QPixmap.fromImage(self.qimage) def pixelSize(self): """return scene-size of a single pixel in the image""" br = self.sceneBoundingRect() if self.image is None: return 1,1 return br.width()/self.width(), br.height()/self.height() def viewTransformChanged(self): if self.autoDownsample: self.qimage = None self.update() def mouseDragEvent(self, ev): if ev.button() != QtCore.Qt.LeftButton: ev.ignore() return elif self.drawKernel is not None: ev.accept() self.drawAt(ev.pos(), ev) def mouseClickEvent(self, ev): if ev.button() == QtCore.Qt.RightButton: if self.raiseContextMenu(ev): ev.accept() if self.drawKernel is not None and ev.button() == QtCore.Qt.LeftButton: self.drawAt(ev.pos(), ev) def raiseContextMenu(self, ev): menu = self.getMenu() if menu is None: return False menu = self.scene().addParentContextMenus(self, menu, ev) pos = ev.screenPos() menu.popup(QtCore.QPoint(pos.x(), pos.y())) return True def getMenu(self): if self.menu is None: if not self.removable: return None self.menu = QtGui.QMenu() self.menu.setTitle("Image") remAct = QtGui.QAction("Remove image", self.menu) remAct.triggered.connect(self.removeClicked) self.menu.addAction(remAct) self.menu.remAct = remAct return self.menu def hoverEvent(self, ev): if not ev.isExit() and self.drawKernel is not None and ev.acceptDrags(QtCore.Qt.LeftButton): ev.acceptClicks(QtCore.Qt.LeftButton) ## we don't use the click, but we also don't want anyone else to use it. ev.acceptClicks(QtCore.Qt.RightButton) elif not ev.isExit() and self.removable: ev.acceptClicks(QtCore.Qt.RightButton) ## accept context menu clicks def tabletEvent(self, ev): pass #print(ev.device()) #print(ev.pointerType()) #print(ev.pressure()) def drawAt(self, pos, ev=None): pos = [int(pos.x()), int(pos.y())] dk = self.drawKernel kc = self.drawKernelCenter sx = [0,dk.shape[0]] sy = [0,dk.shape[1]] tx = [pos[0] - kc[0], pos[0] - kc[0]+ dk.shape[0]] ty = [pos[1] - kc[1], pos[1] - kc[1]+ dk.shape[1]] for i in [0,1]: dx1 = -min(0, tx[i]) dx2 = min(0, self.image.shape[0]-tx[i]) tx[i] += dx1+dx2 sx[i] += dx1+dx2 dy1 = -min(0, ty[i]) dy2 = min(0, self.image.shape[1]-ty[i]) ty[i] += dy1+dy2 sy[i] += dy1+dy2 ts = (slice(tx[0],tx[1]), slice(ty[0],ty[1])) ss = (slice(sx[0],sx[1]), slice(sy[0],sy[1])) mask = self.drawMask src = dk if isinstance(self.drawMode, Callable): self.drawMode(dk, self.image, mask, ss, ts, ev) else: src = src[ss] if self.drawMode == 'set': if mask is not None: mask = mask[ss] self.image[ts] = self.image[ts] * (1-mask) + src * mask else: self.image[ts] = src elif self.drawMode == 'add': self.image[ts] += src else: raise Exception("Unknown draw mode '%s'" % self.drawMode) self.updateImage() def setDrawKernel(self, kernel=None, mask=None, center=(0,0), mode='set'): self.drawKernel = kernel self.drawKernelCenter = center self.drawMode = mode self.drawMask = mask def removeClicked(self): ## Send remove event only after we have exited the menu event handler self.removeTimer = QtCore.QTimer() self.removeTimer.timeout.connect(self.emitRemoveRequested) self.removeTimer.start(0) def emitRemoveRequested(self): self.removeTimer.timeout.disconnect(self.emitRemoveRequested) self.sigRemoveRequested.emit(self)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/ScaleBar.py
.py
2,287
72
from ..Qt import QtGui, QtCore from .GraphicsObject import * from .GraphicsWidgetAnchor import * from .TextItem import TextItem import numpy as np from .. import functions as fn from .. import getConfigOption from ..Point import Point __all__ = ['ScaleBar'] class ScaleBar(GraphicsObject, GraphicsWidgetAnchor): """ Displays a rectangular bar to indicate the relative scale of objects on the view. """ def __init__(self, size, width=5, brush=None, pen=None, suffix='m', offset=None): GraphicsObject.__init__(self) GraphicsWidgetAnchor.__init__(self) self.setFlag(self.ItemHasNoContents) self.setAcceptedMouseButtons(QtCore.Qt.NoButton) if brush is None: brush = getConfigOption('foreground') self.brush = fn.mkBrush(brush) self.pen = fn.mkPen(pen) self._width = width self.size = size if offset == None: offset = (0,0) self.offset = offset self.bar = QtGui.QGraphicsRectItem() self.bar.setPen(self.pen) self.bar.setBrush(self.brush) self.bar.setParentItem(self) self.text = TextItem(text=fn.siFormat(size, suffix=suffix), anchor=(0.5,1)) self.text.setParentItem(self) def parentChanged(self): view = self.parentItem() if view is None: return view.sigRangeChanged.connect(self.updateBar) self.updateBar() def updateBar(self): view = self.parentItem() if view is None: return p1 = view.mapFromViewToItem(self, QtCore.QPointF(0,0)) p2 = view.mapFromViewToItem(self, QtCore.QPointF(self.size,0)) w = (p2-p1).x() self.bar.setRect(QtCore.QRectF(-w, 0, w, self._width)) self.text.setPos(-w/2., 0) def boundingRect(self): return QtCore.QRectF() def setParentItem(self, p): ret = GraphicsObject.setParentItem(self, p) if self.offset is not None: offset = Point(self.offset) anchorx = 1 if offset[0] <= 0 else 0 anchory = 1 if offset[1] <= 0 else 0 anchor = (anchorx, anchory) self.anchor(itemPos=anchor, parentPos=anchor, offset=offset) return ret
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/PlotCurveItem.py
.py
24,275
644
# -*- coding: utf-8 -*- from ..Qt import QtGui, QtCore try: from ..Qt import QtOpenGL HAVE_OPENGL = True except: HAVE_OPENGL = False import numpy as np from .GraphicsObject import GraphicsObject from .. import functions as fn from ..Point import Point import struct, sys from .. import getConfigOption from .. import debug __all__ = ['PlotCurveItem'] class PlotCurveItem(GraphicsObject): """ Class representing a single plot curve. Instances of this class are created automatically as part of PlotDataItem; these rarely need to be instantiated directly. Features: - Fast data update - Fill under curve - Mouse interaction ==================== =============================================== **Signals:** sigPlotChanged(self) Emitted when the data being plotted has changed sigClicked(self) Emitted when the curve is clicked ==================== =============================================== """ sigPlotChanged = QtCore.Signal(object) sigClicked = QtCore.Signal(object) def __init__(self, *args, **kargs): """ Forwards all arguments to :func:`setData <pyqtgraph.PlotCurveItem.setData>`. Some extra arguments are accepted as well: ============== ======================================================= **Arguments:** parent The parent GraphicsObject (optional) clickable If True, the item will emit sigClicked when it is clicked on. Defaults to False. ============== ======================================================= """ GraphicsObject.__init__(self, kargs.get('parent', None)) self.clear() ## this is disastrous for performance. #self.setCacheMode(QtGui.QGraphicsItem.DeviceCoordinateCache) self.metaData = {} self.opts = { 'shadowPen': None, 'fillLevel': None, 'fillOutline': False, 'brush': None, 'stepMode': False, 'name': None, 'antialias': getConfigOption('antialias'), 'connect': 'all', 'mouseWidth': 8, # width of shape responding to mouse click 'compositionMode': None, } if 'pen' not in kargs: self.opts['pen'] = fn.mkPen('w') self.setClickable(kargs.get('clickable', False)) self.setData(*args, **kargs) def implements(self, interface=None): ints = ['plotData'] if interface is None: return ints return interface in ints def name(self): return self.opts.get('name', None) def setClickable(self, s, width=None): """Sets whether the item responds to mouse clicks. The *width* argument specifies the width in pixels orthogonal to the curve that will respond to a mouse click. """ self.clickable = s if width is not None: self.opts['mouseWidth'] = width self._mouseShape = None self._boundingRect = None def setCompositionMode(self, mode): """Change the composition mode of the item (see QPainter::CompositionMode in the Qt documentation). This is useful when overlaying multiple items. ============================================ ============================================================ **Most common arguments:** QtGui.QPainter.CompositionMode_SourceOver Default; image replaces the background if it is opaque. Otherwise, it uses the alpha channel to blend the image with the background. QtGui.QPainter.CompositionMode_Overlay The image color is mixed with the background color to reflect the lightness or darkness of the background. QtGui.QPainter.CompositionMode_Plus Both the alpha and color of the image and background pixels are added together. QtGui.QPainter.CompositionMode_Multiply The output is the image color multiplied by the background. ============================================ ============================================================ """ self.opts['compositionMode'] = mode self.update() def getData(self): return self.xData, self.yData def dataBounds(self, ax, frac=1.0, orthoRange=None): ## Need this to run as fast as possible. ## check cache first: cache = self._boundsCache[ax] if cache is not None and cache[0] == (frac, orthoRange): return cache[1] (x, y) = self.getData() if x is None or len(x) == 0: return (None, None) if ax == 0: d = x d2 = y elif ax == 1: d = y d2 = x ## If an orthogonal range is specified, mask the data now if orthoRange is not None: mask = (d2 >= orthoRange[0]) * (d2 <= orthoRange[1]) d = d[mask] #d2 = d2[mask] if len(d) == 0: return (None, None) ## Get min/max (or percentiles) of the requested data range if frac >= 1.0: # include complete data range # first try faster nanmin/max function, then cut out infs if needed. b = (np.nanmin(d), np.nanmax(d)) if any(np.isinf(b)): mask = np.isfinite(d) d = d[mask] if len(d) == 0: return (None, None) b = (d.min(), d.max()) elif frac <= 0.0: raise Exception("Value for parameter 'frac' must be > 0. (got %s)" % str(frac)) else: # include a percentile of data range mask = np.isfinite(d) d = d[mask] b = np.percentile(d, [50 * (1 - frac), 50 * (1 + frac)]) ## adjust for fill level if ax == 1 and self.opts['fillLevel'] not in [None, 'enclosed']: b = (min(b[0], self.opts['fillLevel']), max(b[1], self.opts['fillLevel'])) ## Add pen width only if it is non-cosmetic. pen = self.opts['pen'] spen = self.opts['shadowPen'] if not pen.isCosmetic(): b = (b[0] - pen.widthF()*0.7072, b[1] + pen.widthF()*0.7072) if spen is not None and not spen.isCosmetic() and spen.style() != QtCore.Qt.NoPen: b = (b[0] - spen.widthF()*0.7072, b[1] + spen.widthF()*0.7072) self._boundsCache[ax] = [(frac, orthoRange), b] return b def pixelPadding(self): pen = self.opts['pen'] spen = self.opts['shadowPen'] w = 0 if pen.isCosmetic(): w += pen.widthF()*0.7072 if spen is not None and spen.isCosmetic() and spen.style() != QtCore.Qt.NoPen: w = max(w, spen.widthF()*0.7072) if self.clickable: w = max(w, self.opts['mouseWidth']//2 + 1) return w def boundingRect(self): if self._boundingRect is None: (xmn, xmx) = self.dataBounds(ax=0) (ymn, ymx) = self.dataBounds(ax=1) if xmn is None or ymn is None: return QtCore.QRectF() px = py = 0.0 pxPad = self.pixelPadding() if pxPad > 0: # determine length of pixel in local x, y directions px, py = self.pixelVectors() try: px = 0 if px is None else px.length() except OverflowError: px = 0 try: py = 0 if py is None else py.length() except OverflowError: py = 0 # return bounds expanded by pixel size px *= pxPad py *= pxPad #px += self._maxSpotWidth * 0.5 #py += self._maxSpotWidth * 0.5 self._boundingRect = QtCore.QRectF(xmn-px, ymn-py, (2*px)+xmx-xmn, (2*py)+ymx-ymn) return self._boundingRect def viewTransformChanged(self): self.invalidateBounds() self.prepareGeometryChange() #def boundingRect(self): #if self._boundingRect is None: #(x, y) = self.getData() #if x is None or y is None or len(x) == 0 or len(y) == 0: #return QtCore.QRectF() #if self.opts['shadowPen'] is not None: #lineWidth = (max(self.opts['pen'].width(), self.opts['shadowPen'].width()) + 1) #else: #lineWidth = (self.opts['pen'].width()+1) #pixels = self.pixelVectors() #if pixels == (None, None): #pixels = [Point(0,0), Point(0,0)] #xmin = x.min() #xmax = x.max() #ymin = y.min() #ymax = y.max() #if self.opts['fillLevel'] is not None: #ymin = min(ymin, self.opts['fillLevel']) #ymax = max(ymax, self.opts['fillLevel']) #xmin -= pixels[0].x() * lineWidth #xmax += pixels[0].x() * lineWidth #ymin -= abs(pixels[1].y()) * lineWidth #ymax += abs(pixels[1].y()) * lineWidth #self._boundingRect = QtCore.QRectF(xmin, ymin, xmax-xmin, ymax-ymin) #return self._boundingRect def invalidateBounds(self): self._boundingRect = None self._boundsCache = [None, None] def setPen(self, *args, **kargs): """Set the pen used to draw the curve.""" self.opts['pen'] = fn.mkPen(*args, **kargs) self.invalidateBounds() self.update() def setShadowPen(self, *args, **kargs): """Set the shadow pen used to draw behind the primary pen. This pen must have a larger width than the primary pen to be visible. """ self.opts['shadowPen'] = fn.mkPen(*args, **kargs) self.invalidateBounds() self.update() def setBrush(self, *args, **kargs): """Set the brush used when filling the area under the curve""" self.opts['brush'] = fn.mkBrush(*args, **kargs) self.invalidateBounds() self.update() def setFillLevel(self, level): """Set the level filled to when filling under the curve""" self.opts['fillLevel'] = level self.fillPath = None self.invalidateBounds() self.update() def setData(self, *args, **kargs): """ =============== ======================================================== **Arguments:** x, y (numpy arrays) Data to show pen Pen to use when drawing. Any single argument accepted by :func:`mkPen <pyqtgraph.mkPen>` is allowed. shadowPen Pen for drawing behind the primary pen. Usually this is used to emphasize the curve by providing a high-contrast border. Any single argument accepted by :func:`mkPen <pyqtgraph.mkPen>` is allowed. fillLevel (float or None) Fill the area 'under' the curve to *fillLevel* fillOutline (bool) If True, an outline surrounding the *fillLevel* area is drawn. brush QBrush to use when filling. Any single argument accepted by :func:`mkBrush <pyqtgraph.mkBrush>` is allowed. antialias (bool) Whether to use antialiasing when drawing. This is disabled by default because it decreases performance. stepMode If True, two orthogonal lines are drawn for each sample as steps. This is commonly used when drawing histograms. Note that in this case, len(x) == len(y) + 1 connect Argument specifying how vertexes should be connected by line segments. Default is "all", indicating full connection. "pairs" causes only even-numbered segments to be drawn. "finite" causes segments to be omitted if they are attached to nan or inf values. For any other connectivity, specify an array of boolean values. compositionMode See :func:`setCompositionMode <pyqtgraph.PlotCurveItem.setCompositionMode>`. =============== ======================================================== If non-keyword arguments are used, they will be interpreted as setData(y) for a single argument and setData(x, y) for two arguments. """ self.updateData(*args, **kargs) def updateData(self, *args, **kargs): profiler = debug.Profiler() if 'compositionMode' in kargs: self.setCompositionMode(kargs['compositionMode']) if len(args) == 1: kargs['y'] = args[0] elif len(args) == 2: kargs['x'] = args[0] kargs['y'] = args[1] if 'y' not in kargs or kargs['y'] is None: kargs['y'] = np.array([]) if 'x' not in kargs or kargs['x'] is None: kargs['x'] = np.arange(len(kargs['y'])) for k in ['x', 'y']: data = kargs[k] if isinstance(data, list): data = np.array(data) kargs[k] = data if not isinstance(data, np.ndarray) or data.ndim > 1: raise Exception("Plot data must be 1D ndarray.") if data.dtype.kind == 'c': raise Exception("Can not plot complex data types.") profiler("data checks") #self.setCacheMode(QtGui.QGraphicsItem.NoCache) ## Disabling and re-enabling the cache works around a bug in Qt 4.6 causing the cached results to display incorrectly ## Test this bug with test_PlotWidget and zoom in on the animated plot self.yData = kargs['y'].view(np.ndarray) self.xData = kargs['x'].view(np.ndarray) self.invalidateBounds() self.prepareGeometryChange() self.informViewBoundsChanged() profiler('copy') if 'stepMode' in kargs: self.opts['stepMode'] = kargs['stepMode'] if self.opts['stepMode'] is True: if len(self.xData) != len(self.yData)+1: ## allow difference of 1 for step mode plots raise Exception("len(X) must be len(Y)+1 since stepMode=True (got %s and %s)" % (self.xData.shape, self.yData.shape)) else: if self.xData.shape != self.yData.shape: ## allow difference of 1 for step mode plots raise Exception("X and Y arrays must be the same shape--got %s and %s." % (self.xData.shape, self.yData.shape)) self.path = None self.fillPath = None self._mouseShape = None #self.xDisp = self.yDisp = None if 'name' in kargs: self.opts['name'] = kargs['name'] if 'connect' in kargs: self.opts['connect'] = kargs['connect'] if 'pen' in kargs: self.setPen(kargs['pen']) if 'shadowPen' in kargs: self.setShadowPen(kargs['shadowPen']) if 'fillLevel' in kargs: self.setFillLevel(kargs['fillLevel']) if 'fillOutline' in kargs: self.opts['fillOutline'] = kargs['fillOutline'] if 'brush' in kargs: self.setBrush(kargs['brush']) if 'antialias' in kargs: self.opts['antialias'] = kargs['antialias'] profiler('set') self.update() profiler('update') self.sigPlotChanged.emit(self) profiler('emit') def generatePath(self, x, y): if self.opts['stepMode']: ## each value in the x/y arrays generates 2 points. x2 = np.empty((len(x),2), dtype=x.dtype) x2[:] = x[:,np.newaxis] if self.opts['fillLevel'] is None: x = x2.reshape(x2.size)[1:-1] y2 = np.empty((len(y),2), dtype=y.dtype) y2[:] = y[:,np.newaxis] y = y2.reshape(y2.size) else: ## If we have a fill level, add two extra points at either end x = x2.reshape(x2.size) y2 = np.empty((len(y)+2,2), dtype=y.dtype) y2[1:-1] = y[:,np.newaxis] y = y2.reshape(y2.size)[1:-1] y[0] = self.opts['fillLevel'] y[-1] = self.opts['fillLevel'] path = fn.arrayToQPath(x, y, connect=self.opts['connect']) return path def getPath(self): if self.path is None: x,y = self.getData() if x is None or len(x) == 0 or y is None or len(y) == 0: self.path = QtGui.QPainterPath() else: self.path = self.generatePath(*self.getData()) self.fillPath = None self._mouseShape = None return self.path @debug.warnOnException ## raising an exception here causes crash def paint(self, p, opt, widget): profiler = debug.Profiler() if self.xData is None or len(self.xData) == 0: return if HAVE_OPENGL and getConfigOption('enableExperimental') and isinstance(widget, QtOpenGL.QGLWidget): self.paintGL(p, opt, widget) return x = None y = None path = self.getPath() profiler('generate path') if self._exportOpts is not False: aa = self._exportOpts.get('antialias', True) else: aa = self.opts['antialias'] p.setRenderHint(p.Antialiasing, aa) cmode = self.opts['compositionMode'] if cmode is not None: p.setCompositionMode(cmode) if self.opts['brush'] is not None and self.opts['fillLevel'] is not None: if self.fillPath is None: if x is None: x,y = self.getData() p2 = QtGui.QPainterPath(self.path) if self.opts['fillLevel'] != 'enclosed': p2.lineTo(x[-1], self.opts['fillLevel']) p2.lineTo(x[0], self.opts['fillLevel']) p2.lineTo(x[0], y[0]) p2.closeSubpath() self.fillPath = p2 profiler('generate fill path') p.fillPath(self.fillPath, self.opts['brush']) profiler('draw fill path') sp = self.opts['shadowPen'] cp = self.opts['pen'] ## Copy pens and apply alpha adjustment #sp = QtGui.QPen(self.opts['shadowPen']) #cp = QtGui.QPen(self.opts['pen']) #for pen in [sp, cp]: #if pen is None: #continue #c = pen.color() #c.setAlpha(c.alpha() * self.opts['alphaHint']) #pen.setColor(c) ##pen.setCosmetic(True) if sp is not None and sp.style() != QtCore.Qt.NoPen: p.setPen(sp) p.drawPath(path) p.setPen(cp) if self.opts['fillOutline'] and self.fillPath is not None: p.drawPath(self.fillPath) else: p.drawPath(path) profiler('drawPath') #print "Render hints:", int(p.renderHints()) #p.setPen(QtGui.QPen(QtGui.QColor(255,0,0))) #p.drawRect(self.boundingRect()) def paintGL(self, p, opt, widget): p.beginNativePainting() import OpenGL.GL as gl ## set clipping viewport view = self.getViewBox() if view is not None: rect = view.mapRectToItem(self, view.boundingRect()) #gl.glViewport(int(rect.x()), int(rect.y()), int(rect.width()), int(rect.height())) #gl.glTranslate(-rect.x(), -rect.y(), 0) gl.glEnable(gl.GL_STENCIL_TEST) gl.glColorMask(gl.GL_FALSE, gl.GL_FALSE, gl.GL_FALSE, gl.GL_FALSE) # disable drawing to frame buffer gl.glDepthMask(gl.GL_FALSE) # disable drawing to depth buffer gl.glStencilFunc(gl.GL_NEVER, 1, 0xFF) gl.glStencilOp(gl.GL_REPLACE, gl.GL_KEEP, gl.GL_KEEP) ## draw stencil pattern gl.glStencilMask(0xFF) gl.glClear(gl.GL_STENCIL_BUFFER_BIT) gl.glBegin(gl.GL_TRIANGLES) gl.glVertex2f(rect.x(), rect.y()) gl.glVertex2f(rect.x()+rect.width(), rect.y()) gl.glVertex2f(rect.x(), rect.y()+rect.height()) gl.glVertex2f(rect.x()+rect.width(), rect.y()+rect.height()) gl.glVertex2f(rect.x()+rect.width(), rect.y()) gl.glVertex2f(rect.x(), rect.y()+rect.height()) gl.glEnd() gl.glColorMask(gl.GL_TRUE, gl.GL_TRUE, gl.GL_TRUE, gl.GL_TRUE) gl.glDepthMask(gl.GL_TRUE) gl.glStencilMask(0x00) gl.glStencilFunc(gl.GL_EQUAL, 1, 0xFF) try: x, y = self.getData() pos = np.empty((len(x), 2)) pos[:,0] = x pos[:,1] = y gl.glEnableClientState(gl.GL_VERTEX_ARRAY) try: gl.glVertexPointerf(pos) pen = fn.mkPen(self.opts['pen']) color = pen.color() gl.glColor4f(color.red()/255., color.green()/255., color.blue()/255., color.alpha()/255.) width = pen.width() if pen.isCosmetic() and width < 1: width = 1 gl.glPointSize(width) gl.glEnable(gl.GL_LINE_SMOOTH) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glHint(gl.GL_LINE_SMOOTH_HINT, gl.GL_NICEST) gl.glDrawArrays(gl.GL_LINE_STRIP, 0, int(pos.size / pos.shape[-1])) finally: gl.glDisableClientState(gl.GL_VERTEX_ARRAY) finally: p.endNativePainting() def clear(self): self.xData = None ## raw values self.yData = None self.xDisp = None ## display values (after log / fft) self.yDisp = None self.path = None self.fillPath = None self._mouseShape = None self._mouseBounds = None self._boundsCache = [None, None] #del self.xData, self.yData, self.xDisp, self.yDisp, self.path def mouseShape(self): """ Return a QPainterPath representing the clickable shape of the curve """ if self._mouseShape is None: view = self.getViewBox() if view is None: return QtGui.QPainterPath() stroker = QtGui.QPainterPathStroker() path = self.getPath() path = self.mapToItem(view, path) stroker.setWidth(self.opts['mouseWidth']) mousePath = stroker.createStroke(path) self._mouseShape = self.mapFromItem(view, mousePath) return self._mouseShape def mouseClickEvent(self, ev): if not self.clickable or ev.button() != QtCore.Qt.LeftButton: return if self.mouseShape().contains(ev.pos()): ev.accept() self.sigClicked.emit(self) class ROIPlotItem(PlotCurveItem): """Plot curve that monitors an ROI and image for changes to automatically replot.""" def __init__(self, roi, data, img, axes=(0,1), xVals=None, color=None): self.roi = roi self.roiData = data self.roiImg = img self.axes = axes self.xVals = xVals PlotCurveItem.__init__(self, self.getRoiData(), x=self.xVals, color=color) #roi.connect(roi, QtCore.SIGNAL('regionChanged'), self.roiChangedEvent) roi.sigRegionChanged.connect(self.roiChangedEvent) #self.roiChangedEvent() def getRoiData(self): d = self.roi.getArrayRegion(self.roiData, self.roiImg, axes=self.axes) if d is None: return while d.ndim > 1: d = d.mean(axis=1) return d def roiChangedEvent(self): d = self.getRoiData() self.updateData(d, self.xVals)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/IsocurveItem.py
.py
4,010
111
from .. import getConfigOption from .GraphicsObject import * from .. import functions as fn from ..Qt import QtGui, QtCore class IsocurveItem(GraphicsObject): """ **Bases:** :class:`GraphicsObject <pyqtgraph.GraphicsObject>` Item displaying an isocurve of a 2D array. To align this item correctly with an ImageItem, call ``isocurve.setParentItem(image)``. """ def __init__(self, data=None, level=0, pen='w', axisOrder=None): """ Create a new isocurve item. ============== =============================================================== **Arguments:** data A 2-dimensional ndarray. Can be initialized as None, and set later using :func:`setData <pyqtgraph.IsocurveItem.setData>` level The cutoff value at which to draw the isocurve. pen The color of the curve item. Can be anything valid for :func:`mkPen <pyqtgraph.mkPen>` axisOrder May be either 'row-major' or 'col-major'. By default this uses the ``imageAxisOrder`` :ref:`global configuration option <apiref_config>`. ============== =============================================================== """ GraphicsObject.__init__(self) self.level = level self.data = None self.path = None self.axisOrder = getConfigOption('imageAxisOrder') if axisOrder is None else axisOrder self.setPen(pen) self.setData(data, level) def setData(self, data, level=None): """ Set the data/image to draw isocurves for. ============== ======================================================================== **Arguments:** data A 2-dimensional ndarray. level The cutoff value at which to draw the curve. If level is not specified, the previously set level is used. ============== ======================================================================== """ if level is None: level = self.level self.level = level self.data = data self.path = None self.prepareGeometryChange() self.update() def setLevel(self, level): """Set the level at which the isocurve is drawn.""" self.level = level self.path = None self.prepareGeometryChange() self.update() def setPen(self, *args, **kwargs): """Set the pen used to draw the isocurve. Arguments can be any that are valid for :func:`mkPen <pyqtgraph.mkPen>`""" self.pen = fn.mkPen(*args, **kwargs) self.update() def setBrush(self, *args, **kwargs): """Set the brush used to draw the isocurve. Arguments can be any that are valid for :func:`mkBrush <pyqtgraph.mkBrush>`""" self.brush = fn.mkBrush(*args, **kwargs) self.update() def updateLines(self, data, level): self.setData(data, level) def boundingRect(self): if self.data is None: return QtCore.QRectF() if self.path is None: self.generatePath() return self.path.boundingRect() def generatePath(self): if self.data is None: self.path = None return if self.axisOrder == 'row-major': data = self.data.T else: data = self.data lines = fn.isocurve(data, self.level, connected=True, extendToEdge=True) self.path = QtGui.QPainterPath() for line in lines: self.path.moveTo(*line[0]) for p in line[1:]: self.path.lineTo(*p) def paint(self, p, *args): if self.data is None: return if self.path is None: self.generatePath() p.setPen(self.pen) p.drawPath(self.path)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/ItemGroup.py
.py
546
24
from ..Qt import QtGui, QtCore from .GraphicsObject import GraphicsObject __all__ = ['ItemGroup'] class ItemGroup(GraphicsObject): """ Replacement for QGraphicsItemGroup """ def __init__(self, *args): GraphicsObject.__init__(self, *args) if hasattr(self, "ItemHasNoContents"): self.setFlag(self.ItemHasNoContents) def boundingRect(self): return QtCore.QRectF() def paint(self, *args): pass def addItem(self, item): item.setParentItem(self)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/GridItem.py
.py
7,431
210
from ..Qt import QtGui, QtCore from .UIGraphicsItem import * import numpy as np from ..Point import Point from .. import functions as fn from .. import getConfigOption __all__ = ['GridItem'] class GridItem(UIGraphicsItem): """ **Bases:** :class:`UIGraphicsItem <pyqtgraph.UIGraphicsItem>` Displays a rectangular grid of lines indicating major divisions within a coordinate system. Automatically determines what divisions to use. """ def __init__(self, pen='default', textPen='default'): UIGraphicsItem.__init__(self) #QtGui.QGraphicsItem.__init__(self, *args) #self.setFlag(QtGui.QGraphicsItem.ItemClipsToShape) #self.setCacheMode(QtGui.QGraphicsItem.DeviceCoordinateCache) self.opts = {} self.setPen(pen) self.setTextPen(textPen) self.setTickSpacing(x=[None, None, None], y=[None, None, None]) def setPen(self, *args, **kwargs): """Set the pen used to draw the grid.""" if kwargs == {} and (args == () or args == ('default',)): self.opts['pen'] = fn.mkPen(getConfigOption('foreground')) else: self.opts['pen'] = fn.mkPen(*args, **kwargs) self.picture = None self.update() def setTextPen(self, *args, **kwargs): """Set the pen used to draw the texts.""" if kwargs == {} and (args == () or args == ('default',)): self.opts['textPen'] = fn.mkPen(getConfigOption('foreground')) else: if args == (None,): self.opts['textPen'] = None else: self.opts['textPen'] = fn.mkPen(*args, **kargs) self.picture = None self.update() def setTickSpacing(self, x=None, y=None): """ Set the grid tick spacing to use. Tick spacing for each axis shall be specified as an array of descending values, one for each tick scale. When the value is set to None, grid line distance is chosen automatically for this particular level. Example: Default setting of 3 scales for each axis: setTickSpacing(x=[None, None, None], y=[None, None, None]) Single scale with distance of 1.0 for X axis, Two automatic scales for Y axis: setTickSpacing(x=[1.0], y=[None, None]) Single scale with distance of 1.0 for X axis, Two scales for Y axis, one with spacing of 1.0, other one automatic: setTickSpacing(x=[1.0], y=[1.0, None]) """ self.opts['tickSpacing'] = (x or self.opts['tickSpacing'][0], y or self.opts['tickSpacing'][1]) self.grid_depth = max([len(s) for s in self.opts['tickSpacing']]) self.picture = None self.update() def viewRangeChanged(self): UIGraphicsItem.viewRangeChanged(self) self.picture = None #UIGraphicsItem.viewRangeChanged(self) #self.update() def paint(self, p, opt, widget): #p.setPen(QtGui.QPen(QtGui.QColor(100, 100, 100))) #p.drawRect(self.boundingRect()) #UIGraphicsItem.paint(self, p, opt, widget) ### draw picture if self.picture is None: #print "no pic, draw.." self.generatePicture() p.drawPicture(QtCore.QPointF(0, 0), self.picture) #p.setPen(QtGui.QPen(QtGui.QColor(255,0,0))) #p.drawLine(0, -100, 0, 100) #p.drawLine(-100, 0, 100, 0) #print "drawing Grid." def generatePicture(self): self.picture = QtGui.QPicture() p = QtGui.QPainter() p.begin(self.picture) vr = self.getViewWidget().rect() unit = self.pixelWidth(), self.pixelHeight() dim = [vr.width(), vr.height()] lvr = self.boundingRect() ul = np.array([lvr.left(), lvr.top()]) br = np.array([lvr.right(), lvr.bottom()]) texts = [] if ul[1] > br[1]: x = ul[1] ul[1] = br[1] br[1] = x lastd = [None, None] for i in range(self.grid_depth - 1, -1, -1): dist = br-ul nlTarget = 10.**i d = 10. ** np.floor(np.log10(abs(dist/nlTarget))+0.5) for ax in range(0,2): ts = self.opts['tickSpacing'][ax] try: if ts[i] is not None: d[ax] = ts[i] except IndexError: pass lastd[ax] = d[ax] ul1 = np.floor(ul / d) * d br1 = np.ceil(br / d) * d dist = br1-ul1 nl = (dist / d) + 0.5 #print "level", i #print " dim", dim #print " dist", dist #print " d", d #print " nl", nl for ax in range(0,2): ## Draw grid for both axes if i >= len(self.opts['tickSpacing'][ax]): continue if d[ax] < lastd[ax]: continue ppl = dim[ax] / nl[ax] c = np.clip(5 * (ppl-3), 0., 50.).astype(int) linePen = self.opts['pen'] lineColor = self.opts['pen'].color() lineColor.setAlpha(c) linePen.setColor(lineColor) textPen = self.opts['textPen'] if textPen is not None: textColor = self.opts['textPen'].color() textColor.setAlpha(c * 2) textPen.setColor(textColor) bx = (ax+1) % 2 for x in range(0, int(nl[ax])): linePen.setCosmetic(False) if ax == 0: linePen.setWidthF(self.pixelWidth()) #print "ax 0 height", self.pixelHeight() else: linePen.setWidthF(self.pixelHeight()) #print "ax 1 width", self.pixelWidth() p.setPen(linePen) p1 = np.array([0.,0.]) p2 = np.array([0.,0.]) p1[ax] = ul1[ax] + x * d[ax] p2[ax] = p1[ax] p1[bx] = ul[bx] p2[bx] = br[bx] ## don't draw lines that are out of bounds. if p1[ax] < min(ul[ax], br[ax]) or p1[ax] > max(ul[ax], br[ax]): continue p.drawLine(QtCore.QPointF(p1[0], p1[1]), QtCore.QPointF(p2[0], p2[1])) if i < 2 and textPen is not None: if ax == 0: x = p1[0] + unit[0] y = ul[1] + unit[1] * 8. else: x = ul[0] + unit[0]*3 y = p1[1] + unit[1] texts.append((QtCore.QPointF(x, y), "%g"%p1[ax])) tr = self.deviceTransform() #tr.scale(1.5, 1.5) p.setWorldTransform(fn.invertQTransform(tr)) if textPen is not None and len(texts) > 0: # if there is at least one text, then c is set textColor.setAlpha(c * 2) p.setPen(QtGui.QPen(textColor)) for t in texts: x = tr.map(t[0]) + Point(0.5, 0.5) p.drawText(x, t[1]) p.end()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/InfiniteLine.py
.py
23,110
621
# -*- coding: utf-8 -*- from ..Qt import QtGui, QtCore from ..Point import Point from .GraphicsObject import GraphicsObject from .TextItem import TextItem from .ViewBox import ViewBox from .. import functions as fn import numpy as np import weakref __all__ = ['InfiniteLine', 'InfLineLabel'] class InfiniteLine(GraphicsObject): """ **Bases:** :class:`GraphicsObject <pyqtgraph.GraphicsObject>` Displays a line of infinite length. This line may be dragged to indicate a position in data coordinates. =============================== =================================================== **Signals:** sigDragged(self) sigPositionChangeFinished(self) sigPositionChanged(self) =============================== =================================================== """ sigDragged = QtCore.Signal(object) sigPositionChangeFinished = QtCore.Signal(object) sigPositionChanged = QtCore.Signal(object) def __init__(self, pos=None, angle=90, pen=None, movable=False, bounds=None, hoverPen=None, label=None, labelOpts=None, span=(0, 1), markers=None, name=None): """ =============== ================================================================== **Arguments:** pos Position of the line. This can be a QPointF or a single value for vertical/horizontal lines. angle Angle of line in degrees. 0 is horizontal, 90 is vertical. pen Pen to use when drawing line. Can be any arguments that are valid for :func:`mkPen <pyqtgraph.mkPen>`. Default pen is transparent yellow. hoverPen Pen to use when the mouse cursor hovers over the line. Only used when movable=True. movable If True, the line can be dragged to a new position by the user. bounds Optional [min, max] bounding values. Bounds are only valid if the line is vertical or horizontal. hoverPen Pen to use when drawing line when hovering over it. Can be any arguments that are valid for :func:`mkPen <pyqtgraph.mkPen>`. Default pen is red. label Text to be displayed in a label attached to the line, or None to show no label (default is None). May optionally include formatting strings to display the line value. labelOpts A dict of keyword arguments to use when constructing the text label. See :class:`InfLineLabel`. span Optional tuple (min, max) giving the range over the view to draw the line. For example, with a vertical line, use span=(0.5, 1) to draw only on the top half of the view. markers List of (marker, position, size) tuples, one per marker to display on the line. See the addMarker method. name Name of the item =============== ================================================================== """ self._boundingRect = None self._name = name GraphicsObject.__init__(self) if bounds is None: ## allowed value boundaries for orthogonal lines self.maxRange = [None, None] else: self.maxRange = bounds self.moving = False self.setMovable(movable) self.mouseHovering = False self.p = [0, 0] self.setAngle(angle) if pos is None: pos = Point(0,0) self.setPos(pos) if pen is None: pen = (200, 200, 100) self.setPen(pen) if hoverPen is None: self.setHoverPen(color=(255,0,0), width=self.pen.width()) else: self.setHoverPen(hoverPen) self.span = span self.currentPen = self.pen self.markers = [] self._maxMarkerSize = 0 if markers is not None: for m in markers: self.addMarker(*m) # Cache variables for managing bounds self._endPoints = [0, 1] # self._bounds = None self._lastViewSize = None if label is not None: labelOpts = {} if labelOpts is None else labelOpts self.label = InfLineLabel(self, text=label, **labelOpts) def setMovable(self, m): """Set whether the line is movable by the user.""" self.movable = m self.setAcceptHoverEvents(m) def setBounds(self, bounds): """Set the (minimum, maximum) allowable values when dragging.""" self.maxRange = bounds self.setValue(self.value()) def bounds(self): """Return the (minimum, maximum) values allowed when dragging. """ return self.maxRange[:] def setPen(self, *args, **kwargs): """Set the pen for drawing the line. Allowable arguments are any that are valid for :func:`mkPen <pyqtgraph.mkPen>`.""" self.pen = fn.mkPen(*args, **kwargs) if not self.mouseHovering: self.currentPen = self.pen self.update() def setHoverPen(self, *args, **kwargs): """Set the pen for drawing the line while the mouse hovers over it. Allowable arguments are any that are valid for :func:`mkPen <pyqtgraph.mkPen>`. If the line is not movable, then hovering is also disabled. Added in version 0.9.9.""" # If user did not supply a width, then copy it from pen widthSpecified = ((len(args) == 1 and (isinstance(args[0], QtGui.QPen) or (isinstance(args[0], dict) and 'width' in args[0])) ) or 'width' in kwargs) self.hoverPen = fn.mkPen(*args, **kwargs) if not widthSpecified: self.hoverPen.setWidth(self.pen.width()) if self.mouseHovering: self.currentPen = self.hoverPen self.update() def addMarker(self, marker, position=0.5, size=10.0): """Add a marker to be displayed on the line. ============= ========================================================= **Arguments** marker String indicating the style of marker to add: ``'<|'``, ``'|>'``, ``'>|'``, ``'|<'``, ``'<|>'``, ``'>|<'``, ``'^'``, ``'v'``, ``'o'`` position Position (0.0-1.0) along the visible extent of the line to place the marker. Default is 0.5. size Size of the marker in pixels. Default is 10.0. ============= ========================================================= """ path = QtGui.QPainterPath() if marker == 'o': path.addEllipse(QtCore.QRectF(-0.5, -0.5, 1, 1)) if '<|' in marker: p = QtGui.QPolygonF([Point(0.5, 0), Point(0, -0.5), Point(-0.5, 0)]) path.addPolygon(p) path.closeSubpath() if '|>' in marker: p = QtGui.QPolygonF([Point(0.5, 0), Point(0, 0.5), Point(-0.5, 0)]) path.addPolygon(p) path.closeSubpath() if '>|' in marker: p = QtGui.QPolygonF([Point(0.5, -0.5), Point(0, 0), Point(-0.5, -0.5)]) path.addPolygon(p) path.closeSubpath() if '|<' in marker: p = QtGui.QPolygonF([Point(0.5, 0.5), Point(0, 0), Point(-0.5, 0.5)]) path.addPolygon(p) path.closeSubpath() if '^' in marker: p = QtGui.QPolygonF([Point(0, -0.5), Point(0.5, 0), Point(0, 0.5)]) path.addPolygon(p) path.closeSubpath() if 'v' in marker: p = QtGui.QPolygonF([Point(0, -0.5), Point(-0.5, 0), Point(0, 0.5)]) path.addPolygon(p) path.closeSubpath() self.markers.append((path, position, size)) self._maxMarkerSize = max([m[2] / 2. for m in self.markers]) self.update() def clearMarkers(self): """ Remove all markers from this line. """ self.markers = [] self._maxMarkerSize = 0 self.update() def setAngle(self, angle): """ Takes angle argument in degrees. 0 is horizontal; 90 is vertical. Note that the use of value() and setValue() changes if the line is not vertical or horizontal. """ self.angle = angle #((angle+45) % 180) - 45 ## -45 <= angle < 135 self.resetTransform() self.rotate(self.angle) self.update() def setPos(self, pos): if type(pos) in [list, tuple]: newPos = pos elif isinstance(pos, QtCore.QPointF): newPos = [pos.x(), pos.y()] else: if self.angle == 90: newPos = [pos, 0] elif self.angle == 0: newPos = [0, pos] else: raise Exception("Must specify 2D coordinate for non-orthogonal lines.") ## check bounds (only works for orthogonal lines) if self.angle == 90: if self.maxRange[0] is not None: newPos[0] = max(newPos[0], self.maxRange[0]) if self.maxRange[1] is not None: newPos[0] = min(newPos[0], self.maxRange[1]) elif self.angle == 0: if self.maxRange[0] is not None: newPos[1] = max(newPos[1], self.maxRange[0]) if self.maxRange[1] is not None: newPos[1] = min(newPos[1], self.maxRange[1]) if self.p != newPos: self.p = newPos self._invalidateCache() GraphicsObject.setPos(self, Point(self.p)) self.sigPositionChanged.emit(self) def getXPos(self): return self.p[0] def getYPos(self): return self.p[1] def getPos(self): return self.p def value(self): """Return the value of the line. Will be a single number for horizontal and vertical lines, and a list of [x,y] values for diagonal lines.""" if self.angle%180 == 0: return self.getYPos() elif self.angle%180 == 90: return self.getXPos() else: return self.getPos() def setValue(self, v): """Set the position of the line. If line is horizontal or vertical, v can be a single value. Otherwise, a 2D coordinate must be specified (list, tuple and QPointF are all acceptable).""" self.setPos(v) ## broken in 4.7 #def itemChange(self, change, val): #if change in [self.ItemScenePositionHasChanged, self.ItemSceneHasChanged]: #self.updateLine() #print "update", change #print self.getBoundingParents() #else: #print "ignore", change #return GraphicsObject.itemChange(self, change, val) def setSpan(self, mn, mx): if self.span != (mn, mx): self.span = (mn, mx) self.update() def _invalidateCache(self): self._boundingRect = None def _computeBoundingRect(self): #br = UIGraphicsItem.boundingRect(self) vr = self.viewRect() # bounds of containing ViewBox mapped to local coords. if vr is None: return QtCore.QRectF() ## add a 4-pixel radius around the line for mouse interaction. px = self.pixelLength(direction=Point(1,0), ortho=True) ## get pixel length orthogonal to the line if px is None: px = 0 pw = max(self.pen.width() / 2, self.hoverPen.width() / 2) w = max(4, self._maxMarkerSize + pw) + 1 w = w * px br = QtCore.QRectF(vr) br.setBottom(-w) br.setTop(w) length = br.width() left = br.left() + length * self.span[0] right = br.left() + length * self.span[1] br.setLeft(left) br.setRight(right) br = br.normalized() vs = self.getViewBox().size() if self._bounds != br or self._lastViewSize != vs: self._bounds = br self._lastViewSize = vs self.prepareGeometryChange() self._endPoints = (left, right) self._lastViewRect = vr return self._bounds def boundingRect(self): if self._boundingRect is None: self._boundingRect = self._computeBoundingRect() return self._boundingRect def paint(self, p, *args): p.setRenderHint(p.Antialiasing) left, right = self._endPoints pen = self.currentPen pen.setJoinStyle(QtCore.Qt.MiterJoin) p.setPen(pen) p.drawLine(Point(left, 0), Point(right, 0)) if len(self.markers) == 0: return # paint markers in native coordinate system tr = p.transform() p.resetTransform() start = tr.map(Point(left, 0)) end = tr.map(Point(right, 0)) up = tr.map(Point(left, 1)) dif = end - start length = Point(dif).length() angle = np.arctan2(dif.y(), dif.x()) * 180 / np.pi p.translate(start) p.rotate(angle) up = up - start det = up.x() * dif.y() - dif.x() * up.y() p.scale(1, 1 if det > 0 else -1) p.setBrush(fn.mkBrush(self.currentPen.color())) #p.setPen(fn.mkPen(None)) tr = p.transform() for path, pos, size in self.markers: p.setTransform(tr) x = length * pos p.translate(x, 0) p.scale(size, size) p.drawPath(path) def dataBounds(self, axis, frac=1.0, orthoRange=None): if axis == 0: return None ## x axis should never be auto-scaled else: return (0,0) def mouseDragEvent(self, ev): if self.movable and ev.button() == QtCore.Qt.LeftButton: if ev.isStart(): self.moving = True self.cursorOffset = self.pos() - self.mapToParent(ev.buttonDownPos()) self.startPosition = self.pos() ev.accept() if not self.moving: return self.setPos(self.cursorOffset + self.mapToParent(ev.pos())) self.sigDragged.emit(self) if ev.isFinish(): self.moving = False self.sigPositionChangeFinished.emit(self) def mouseClickEvent(self, ev): if self.moving and ev.button() == QtCore.Qt.RightButton: ev.accept() self.setPos(self.startPosition) self.moving = False self.sigDragged.emit(self) self.sigPositionChangeFinished.emit(self) def hoverEvent(self, ev): if (not ev.isExit()) and self.movable and ev.acceptDrags(QtCore.Qt.LeftButton): self.setMouseHover(True) else: self.setMouseHover(False) def setMouseHover(self, hover): ## Inform the item that the mouse is (not) hovering over it if self.mouseHovering == hover: return self.mouseHovering = hover if hover: self.currentPen = self.hoverPen else: self.currentPen = self.pen self.update() def viewTransformChanged(self): """ Called whenever the transformation matrix of the view has changed. (eg, the view range has changed or the view was resized) """ self._invalidateCache() def setName(self, name): self._name = name def name(self): return self._name class InfLineLabel(TextItem): """ A TextItem that attaches itself to an InfiniteLine. This class extends TextItem with the following features: * Automatically positions adjacent to the line at a fixed position along the line and within the view box. * Automatically reformats text when the line value has changed. * Can optionally be dragged to change its location along the line. * Optionally aligns to its parent line. =============== ================================================================== **Arguments:** line The InfiniteLine to which this label will be attached. text String to display in the label. May contain a {value} formatting string to display the current value of the line. movable Bool; if True, then the label can be dragged along the line. position Relative position (0.0-1.0) within the view to position the label along the line. anchors List of (x,y) pairs giving the text anchor positions that should be used when the line is moved to one side of the view or the other. This allows text to switch to the opposite side of the line as it approaches the edge of the view. These are automatically selected for some common cases, but may be specified if the default values give unexpected results. =============== ================================================================== All extra keyword arguments are passed to TextItem. A particularly useful option here is to use `rotateAxis=(1, 0)`, which will cause the text to be automatically rotated parallel to the line. """ def __init__(self, line, text="", movable=False, position=0.5, anchors=None, **kwds): self.line = line self.movable = movable self.moving = False self.orthoPos = position # text will always be placed on the line at a position relative to view bounds self.format = text self.line.sigPositionChanged.connect(self.valueChanged) self._endpoints = (None, None) if anchors is None: # automatically pick sensible anchors rax = kwds.get('rotateAxis', None) if rax is not None: if tuple(rax) == (1,0): anchors = [(0.5, 0), (0.5, 1)] else: anchors = [(0, 0.5), (1, 0.5)] else: if line.angle % 180 == 0: anchors = [(0.5, 0), (0.5, 1)] else: anchors = [(0, 0.5), (1, 0.5)] self.anchors = anchors TextItem.__init__(self, **kwds) self.setParentItem(line) self.valueChanged() def valueChanged(self): if not self.isVisible(): return value = self.line.value() self.setText(self.format.format(value=value)) self.updatePosition() def getEndpoints(self): # calculate points where line intersects view box # (in line coordinates) if self._endpoints[0] is None: lr = self.line.boundingRect() pt1 = Point(lr.left(), 0) pt2 = Point(lr.right(), 0) if self.line.angle % 90 != 0: # more expensive to find text position for oblique lines. view = self.getViewBox() if not self.isVisible() or not isinstance(view, ViewBox): # not in a viewbox, skip update return (None, None) p = QtGui.QPainterPath() p.moveTo(pt1) p.lineTo(pt2) p = self.line.itemTransform(view)[0].map(p) vr = QtGui.QPainterPath() vr.addRect(view.boundingRect()) paths = vr.intersected(p).toSubpathPolygons(QtGui.QTransform()) if len(paths) > 0: l = list(paths[0]) pt1 = self.line.mapFromItem(view, l[0]) pt2 = self.line.mapFromItem(view, l[1]) self._endpoints = (pt1, pt2) return self._endpoints def updatePosition(self): # update text position to relative view location along line self._endpoints = (None, None) pt1, pt2 = self.getEndpoints() if pt1 is None: return pt = pt2 * self.orthoPos + pt1 * (1-self.orthoPos) self.setPos(pt) # update anchor to keep text visible as it nears the view box edge vr = self.line.viewRect() if vr is not None: self.setAnchor(self.anchors[0 if vr.center().y() < 0 else 1]) def setVisible(self, v): TextItem.setVisible(self, v) if v: self.updateText() self.updatePosition() def setMovable(self, m): """Set whether this label is movable by dragging along the line. """ self.movable = m self.setAcceptHoverEvents(m) def setPosition(self, p): """Set the relative position (0.0-1.0) of this label within the view box and along the line. For horizontal (angle=0) and vertical (angle=90) lines, a value of 0.0 places the text at the bottom or left of the view, respectively. """ self.orthoPos = p self.updatePosition() def setFormat(self, text): """Set the text format string for this label. May optionally contain "{value}" to include the lines current value (the text will be reformatted whenever the line is moved). """ self.format = text self.valueChanged() def mouseDragEvent(self, ev): if self.movable and ev.button() == QtCore.Qt.LeftButton: if ev.isStart(): self._moving = True self._cursorOffset = self._posToRel(ev.buttonDownPos()) self._startPosition = self.orthoPos ev.accept() if not self._moving: return rel = self._posToRel(ev.pos()) self.orthoPos = np.clip(self._startPosition + rel - self._cursorOffset, 0, 1) self.updatePosition() if ev.isFinish(): self._moving = False def mouseClickEvent(self, ev): if self.moving and ev.button() == QtCore.Qt.RightButton: ev.accept() self.orthoPos = self._startPosition self.moving = False def hoverEvent(self, ev): if not ev.isExit() and self.movable: ev.acceptDrags(QtCore.Qt.LeftButton) def viewTransformChanged(self): self.updatePosition() TextItem.viewTransformChanged(self) def _posToRel(self, pos): # convert local position to relative position along line between view bounds pt1, pt2 = self.getEndpoints() if pt1 is None: return 0 view = self.getViewBox() pos = self.mapToParent(pos) return (pos.x() - pt1.x()) / (pt2.x()-pt1.x())
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/HistogramLUTItem.py
.py
13,668
346
# -*- coding: utf-8 -*- """ GraphicsWidget displaying an image histogram along with gradient editor. Can be used to adjust the appearance of images. """ from ..Qt import QtGui, QtCore from .. import functions as fn from .GraphicsWidget import GraphicsWidget from .ViewBox import * from .GradientEditorItem import * from .LinearRegionItem import * from .PlotDataItem import * from .AxisItem import * from .GridItem import * from ..Point import Point from .. import functions as fn import numpy as np from .. import debug as debug import weakref __all__ = ['HistogramLUTItem'] class HistogramLUTItem(GraphicsWidget): """ This is a graphicsWidget which provides controls for adjusting the display of an image. Includes: - Image histogram - Movable region over histogram to select black/white levels - Gradient editor to define color lookup table for single-channel images ================ =========================================================== image (:class:`~pyqtgraph.ImageItem` or ``None``) If *image* is provided, then the control will be automatically linked to the image and changes to the control will be immediately reflected in the image's appearance. fillHistogram (bool) By default, the histogram is rendered with a fill. For performance, set ``fillHistogram=False`` rgbHistogram (bool) Sets whether the histogram is computed once over all channels of the image, or once per channel. levelMode 'mono' or 'rgba'. If 'mono', then only a single set of black/white level lines is drawn, and the levels apply to all channels in the image. If 'rgba', then one set of levels is drawn for each channel. ================ =========================================================== """ sigLookupTableChanged = QtCore.Signal(object) sigLevelsChanged = QtCore.Signal(object) sigLevelChangeFinished = QtCore.Signal(object) def __init__(self, image=None, fillHistogram=True, rgbHistogram=False, levelMode='mono'): GraphicsWidget.__init__(self) self.lut = None self.imageItem = lambda: None # fake a dead weakref self.levelMode = levelMode self.rgbHistogram = rgbHistogram self.layout = QtGui.QGraphicsGridLayout() self.setLayout(self.layout) self.layout.setContentsMargins(1,1,1,1) self.layout.setSpacing(0) self.vb = ViewBox(parent=self) self.vb.setMaximumWidth(152) self.vb.setMinimumWidth(45) self.vb.setMouseEnabled(x=False, y=True) self.gradient = GradientEditorItem() self.gradient.setOrientation('right') self.gradient.loadPreset('grey') self.regions = [ LinearRegionItem([0, 1], 'horizontal', swapMode='block'), LinearRegionItem([0, 1], 'horizontal', swapMode='block', pen='r', brush=fn.mkBrush((255, 50, 50, 50)), span=(0., 1/3.)), LinearRegionItem([0, 1], 'horizontal', swapMode='block', pen='g', brush=fn.mkBrush((50, 255, 50, 50)), span=(1/3., 2/3.)), LinearRegionItem([0, 1], 'horizontal', swapMode='block', pen='b', brush=fn.mkBrush((50, 50, 255, 80)), span=(2/3., 1.)), LinearRegionItem([0, 1], 'horizontal', swapMode='block', pen='w', brush=fn.mkBrush((255, 255, 255, 50)), span=(2/3., 1.))] for region in self.regions: region.setZValue(1000) self.vb.addItem(region) region.lines[0].addMarker('<|', 0.5) region.lines[1].addMarker('|>', 0.5) region.sigRegionChanged.connect(self.regionChanging) region.sigRegionChangeFinished.connect(self.regionChanged) self.region = self.regions[0] # for backward compatibility. self.axis = AxisItem('left', linkView=self.vb, maxTickLength=-10, parent=self) self.layout.addItem(self.axis, 0, 0) self.layout.addItem(self.vb, 0, 1) self.layout.addItem(self.gradient, 0, 2) self.range = None self.gradient.setFlag(self.gradient.ItemStacksBehindParent) self.vb.setFlag(self.gradient.ItemStacksBehindParent) self.gradient.sigGradientChanged.connect(self.gradientChanged) self.vb.sigRangeChanged.connect(self.viewRangeChanged) add = QtGui.QPainter.CompositionMode_Plus self.plots = [ PlotCurveItem(pen=(200, 200, 200, 100)), # mono PlotCurveItem(pen=(255, 0, 0, 100), compositionMode=add), # r PlotCurveItem(pen=(0, 255, 0, 100), compositionMode=add), # g PlotCurveItem(pen=(0, 0, 255, 100), compositionMode=add), # b PlotCurveItem(pen=(200, 200, 200, 100), compositionMode=add), # a ] self.plot = self.plots[0] # for backward compatibility. for plot in self.plots: plot.rotate(90) self.vb.addItem(plot) self.fillHistogram(fillHistogram) self._showRegions() self.vb.addItem(self.plot) self.autoHistogramRange() if image is not None: self.setImageItem(image) def fillHistogram(self, fill=True, level=0.0, color=(100, 100, 200)): colors = [color, (255, 0, 0, 50), (0, 255, 0, 50), (0, 0, 255, 50), (255, 255, 255, 50)] for i,plot in enumerate(self.plots): if fill: plot.setFillLevel(level) plot.setBrush(colors[i]) else: plot.setFillLevel(None) def paint(self, p, *args): if self.levelMode != 'mono': return pen = self.region.lines[0].pen rgn = self.getLevels() p1 = self.vb.mapFromViewToItem(self, Point(self.vb.viewRect().center().x(), rgn[0])) p2 = self.vb.mapFromViewToItem(self, Point(self.vb.viewRect().center().x(), rgn[1])) gradRect = self.gradient.mapRectToParent(self.gradient.gradRect.rect()) for pen in [fn.mkPen((0, 0, 0, 100), width=3), pen]: p.setPen(pen) p.drawLine(p1 + Point(0, 5), gradRect.bottomLeft()) p.drawLine(p2 - Point(0, 5), gradRect.topLeft()) p.drawLine(gradRect.topLeft(), gradRect.topRight()) p.drawLine(gradRect.bottomLeft(), gradRect.bottomRight()) def setHistogramRange(self, mn, mx, padding=0.1): """Set the Y range on the histogram plot. This disables auto-scaling.""" self.vb.enableAutoRange(self.vb.YAxis, False) self.vb.setYRange(mn, mx, padding) def autoHistogramRange(self): """Enable auto-scaling on the histogram plot.""" self.vb.enableAutoRange(self.vb.XYAxes) def setImageItem(self, img): """Set an ImageItem to have its levels and LUT automatically controlled by this HistogramLUTItem. """ self.imageItem = weakref.ref(img) img.sigImageChanged.connect(self.imageChanged) img.setLookupTable(self.getLookupTable) ## send function pointer, not the result self.regionChanged() self.imageChanged(autoLevel=True) def viewRangeChanged(self): self.update() def gradientChanged(self): if self.imageItem() is not None: if self.gradient.isLookupTrivial(): self.imageItem().setLookupTable(None) #lambda x: x.astype(np.uint8)) else: self.imageItem().setLookupTable(self.getLookupTable) ## send function pointer, not the result self.lut = None self.sigLookupTableChanged.emit(self) def getLookupTable(self, img=None, n=None, alpha=None): """Return a lookup table from the color gradient defined by this HistogramLUTItem. """ if self.levelMode != 'mono': return None if n is None: if img.dtype == np.uint8: n = 256 else: n = 512 if self.lut is None: self.lut = self.gradient.getLookupTable(n, alpha=alpha) return self.lut def regionChanged(self): if self.imageItem() is not None: self.imageItem().setLevels(self.getLevels()) self.sigLevelChangeFinished.emit(self) def regionChanging(self): if self.imageItem() is not None: self.imageItem().setLevels(self.getLevels()) self.update() self.sigLevelsChanged.emit(self) def imageChanged(self, autoLevel=False, autoRange=False): if self.imageItem() is None: return if self.levelMode == 'mono': for plt in self.plots[1:]: plt.setVisible(False) self.plots[0].setVisible(True) # plot one histogram for all image data profiler = debug.Profiler() h = self.imageItem().getHistogram() profiler('get histogram') if h[0] is None: return self.plot.setData(*h) profiler('set plot') if autoLevel: mn = h[0][0] mx = h[0][-1] self.region.setRegion([mn, mx]) profiler('set region') else: mn, mx = self.imageItem().levels self.region.setRegion([mn, mx]) else: # plot one histogram for each channel self.plots[0].setVisible(False) ch = self.imageItem().getHistogram(perChannel=True) if ch[0] is None: return for i in range(1, 5): if len(ch) >= i: h = ch[i-1] self.plots[i].setVisible(True) self.plots[i].setData(*h) if autoLevel: mn = h[0][0] mx = h[0][-1] self.region[i].setRegion([mn, mx]) else: # hide channels not present in image data self.plots[i].setVisible(False) # make sure we are displaying the correct number of channels self._showRegions() def getLevels(self): """Return the min and max levels. For rgba mode, this returns a list of the levels for each channel. """ if self.levelMode == 'mono': return self.region.getRegion() else: nch = self.imageItem().channels() if nch is None: nch = 3 return [r.getRegion() for r in self.regions[1:nch+1]] def setLevels(self, min=None, max=None, rgba=None): """Set the min/max (bright and dark) levels. Arguments may be *min* and *max* for single-channel data, or *rgba* = [(rmin, rmax), ...] for multi-channel data. """ if self.levelMode == 'mono': if min is None: min, max = rgba[0] assert None not in (min, max) self.region.setRegion((min, max)) else: if rgba is None: raise TypeError("Must specify rgba argument when levelMode != 'mono'.") for i, levels in enumerate(rgba): self.regions[i+1].setRegion(levels) def setLevelMode(self, mode): """ Set the method of controlling the image levels offered to the user. Options are 'mono' or 'rgba'. """ assert mode in ('mono', 'rgba') if mode == self.levelMode: return oldLevels = self.getLevels() self.levelMode = mode self._showRegions() # do our best to preserve old levels if mode == 'mono': levels = np.array(oldLevels).mean(axis=0) self.setLevels(*levels) else: levels = [oldLevels] * 4 self.setLevels(rgba=levels) # force this because calling self.setLevels might not set the imageItem # levels if there was no change to the region item self.imageItem().setLevels(self.getLevels()) self.imageChanged() self.update() def _showRegions(self): for i in range(len(self.regions)): self.regions[i].setVisible(False) if self.levelMode == 'rgba': imax = 4 if self.imageItem() is not None: # Only show rgb channels if connected image lacks alpha. nch = self.imageItem().channels() if nch is None: nch = 3 xdif = 1.0 / nch for i in range(1, nch+1): self.regions[i].setVisible(True) self.regions[i].setSpan((i-1) * xdif, i * xdif) self.gradient.hide() elif self.levelMode == 'mono': self.regions[0].setVisible(True) self.gradient.show() else: raise ValueError("Unknown level mode %r" % self.levelMode) def saveState(self): return { 'gradient': self.gradient.saveState(), 'levels': self.getLevels(), 'mode': self.levelMode, } def restoreState(self, state): self.setLevelMode(state['mode']) self.gradient.restoreState(state['gradient']) self.setLevels(*state['levels'])
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/TextItem.py
.py
8,259
211
import numpy as np from ..Qt import QtCore, QtGui from ..Point import Point from .. import functions as fn from .GraphicsObject import GraphicsObject class TextItem(GraphicsObject): """ GraphicsItem displaying unscaled text (the text will always appear normal even inside a scaled ViewBox). """ def __init__(self, text='', color=(200,200,200), html=None, anchor=(0,0), border=None, fill=None, angle=0, rotateAxis=None): """ ============== ================================================================================= **Arguments:** *text* The text to display *color* The color of the text (any format accepted by pg.mkColor) *html* If specified, this overrides both *text* and *color* *anchor* A QPointF or (x,y) sequence indicating what region of the text box will be anchored to the item's position. A value of (0,0) sets the upper-left corner of the text box to be at the position specified by setPos(), while a value of (1,1) sets the lower-right corner. *border* A pen to use when drawing the border *fill* A brush to use when filling within the border *angle* Angle in degrees to rotate text. Default is 0; text will be displayed upright. *rotateAxis* If None, then a text angle of 0 always points along the +x axis of the scene. If a QPointF or (x,y) sequence is given, then it represents a vector direction in the parent's coordinate system that the 0-degree line will be aligned to. This Allows text to follow both the position and orientation of its parent while still discarding any scale and shear factors. ============== ================================================================================= The effects of the `rotateAxis` and `angle` arguments are added independently. So for example: * rotateAxis=None, angle=0 -> normal horizontal text * rotateAxis=None, angle=90 -> normal vertical text * rotateAxis=(1, 0), angle=0 -> text aligned with x axis of its parent * rotateAxis=(0, 1), angle=0 -> text aligned with y axis of its parent * rotateAxis=(1, 0), angle=90 -> text orthogonal to x axis of its parent """ self.anchor = Point(anchor) self.rotateAxis = None if rotateAxis is None else Point(rotateAxis) #self.angle = 0 GraphicsObject.__init__(self) self.textItem = QtGui.QGraphicsTextItem() self.textItem.setParentItem(self) self._lastTransform = None self._lastScene = None self._bounds = QtCore.QRectF() if html is None: self.setColor(color) self.setText(text) else: self.setHtml(html) self.fill = fn.mkBrush(fill) self.border = fn.mkPen(border) self.setAngle(angle) def setText(self, text, color=None): """ Set the text of this item. This method sets the plain text of the item; see also setHtml(). """ if color is not None: self.setColor(color) self.textItem.setPlainText(text) self.updateTextPos() def setPlainText(self, *args): """ Set the plain text to be rendered by this item. See QtGui.QGraphicsTextItem.setPlainText(). """ self.textItem.setPlainText(*args) self.updateTextPos() def setHtml(self, *args): """ Set the HTML code to be rendered by this item. See QtGui.QGraphicsTextItem.setHtml(). """ self.textItem.setHtml(*args) self.updateTextPos() def setTextWidth(self, *args): """ Set the width of the text. If the text requires more space than the width limit, then it will be wrapped into multiple lines. See QtGui.QGraphicsTextItem.setTextWidth(). """ self.textItem.setTextWidth(*args) self.updateTextPos() def setFont(self, *args): """ Set the font for this text. See QtGui.QGraphicsTextItem.setFont(). """ self.textItem.setFont(*args) self.updateTextPos() def setAngle(self, angle): """ Set the angle of the text in degrees. This sets the rotation angle of the text as a whole, measured counter-clockwise from the x axis of the parent. Note that this rotation angle does not depend on horizontal/vertical scaling of the parent. """ self.angle = angle self.updateTransform(force=True) def setAnchor(self, anchor): self.anchor = Point(anchor) self.updateTextPos() def setColor(self, color): """ Set the color for this text. See QtGui.QGraphicsItem.setDefaultTextColor(). """ self.color = fn.mkColor(color) self.textItem.setDefaultTextColor(self.color) def updateTextPos(self): # update text position to obey anchor r = self.textItem.boundingRect() tl = self.textItem.mapToParent(r.topLeft()) br = self.textItem.mapToParent(r.bottomRight()) offset = (br - tl) * self.anchor self.textItem.setPos(-offset) ### Needed to maintain font size when rendering to image with increased resolution #self.textItem.resetTransform() ##self.textItem.rotate(self.angle) #if self._exportOpts is not False and 'resolutionScale' in self._exportOpts: #s = self._exportOpts['resolutionScale'] #self.textItem.scale(s, s) def boundingRect(self): return self.textItem.mapToParent(self.textItem.boundingRect()).boundingRect() def viewTransformChanged(self): # called whenever view transform has changed. # Do this here to avoid double-updates when view changes. self.updateTransform() def paint(self, p, *args): # this is not ideal because it requires the transform to be updated at every draw. # ideally, we would have a sceneTransformChanged event to react to.. s = self.scene() ls = self._lastScene if s is not ls: if ls is not None: ls.sigPrepareForPaint.disconnect(self.updateTransform) self._lastScene = s if s is not None: s.sigPrepareForPaint.connect(self.updateTransform) self.updateTransform() p.setTransform(self.sceneTransform()) if self.border.style() != QtCore.Qt.NoPen or self.fill.style() != QtCore.Qt.NoBrush: p.setPen(self.border) p.setBrush(self.fill) p.setRenderHint(p.Antialiasing, True) p.drawPolygon(self.textItem.mapToParent(self.textItem.boundingRect())) def updateTransform(self, force=False): # update transform such that this item has the correct orientation # and scaling relative to the scene, but inherits its position from its # parent. # This is similar to setting ItemIgnoresTransformations = True, but # does not break mouse interaction and collision detection. p = self.parentItem() if p is None: pt = QtGui.QTransform() else: pt = p.sceneTransform() if not force and pt == self._lastTransform: return t = pt.inverted()[0] # reset translation t.setMatrix(t.m11(), t.m12(), t.m13(), t.m21(), t.m22(), t.m23(), 0, 0, t.m33()) # apply rotation angle = -self.angle if self.rotateAxis is not None: d = pt.map(self.rotateAxis) - pt.map(Point(0, 0)) a = np.arctan2(d.y(), d.x()) * 180 / np.pi angle += a t.rotate(angle) self.setTransform(t) self._lastTransform = pt self.updateTextPos()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/MultiPlotItem.py
.py
2,063
63
# -*- coding: utf-8 -*- """ MultiPlotItem.py - Graphics item used for displaying an array of PlotItems Copyright 2010 Luke Campagnola Distributed under MIT/X11 license. See license.txt for more information. """ from numpy import ndarray from . import GraphicsLayout from ..metaarray import * __all__ = ['MultiPlotItem'] class MultiPlotItem(GraphicsLayout.GraphicsLayout): """ Automatically generates a grid of plots from a multi-dimensional array """ def __init__(self, *args, **kwds): GraphicsLayout.GraphicsLayout.__init__(self, *args, **kwds) self.plots = [] def plot(self, data): #self.layout.clear() if hasattr(data, 'implements') and data.implements('MetaArray'): if data.ndim != 2: raise Exception("MultiPlot currently only accepts 2D MetaArray.") ic = data.infoCopy() ax = 0 for i in [0, 1]: if 'cols' in ic[i]: ax = i break #print "Plotting using axis %d as columns (%d plots)" % (ax, data.shape[ax]) for i in range(data.shape[ax]): pi = self.addPlot() self.nextRow() sl = [slice(None)] * 2 sl[ax] = i pi.plot(data[tuple(sl)]) #self.layout.addItem(pi, i, 0) self.plots.append((pi, i, 0)) info = ic[ax]['cols'][i] title = info.get('title', info.get('name', None)) units = info.get('units', None) pi.setLabel('left', text=title, units=units) info = ic[1-ax] title = info.get('title', info.get('name', None)) units = info.get('units', None) pi.setLabel('bottom', text=title, units=units) else: raise Exception("Data type %s not (yet?) supported for MultiPlot." % type(data)) def close(self): for p in self.plots: p[0].close() self.plots = None self.clear()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/DateAxisItem.py
.py
12,290
319
import sys import numpy as np import time from datetime import datetime, timedelta from .AxisItem import AxisItem from ..pgcollections import OrderedDict __all__ = ['DateAxisItem'] MS_SPACING = 1/1000.0 SECOND_SPACING = 1 MINUTE_SPACING = 60 HOUR_SPACING = 3600 DAY_SPACING = 24 * HOUR_SPACING WEEK_SPACING = 7 * DAY_SPACING MONTH_SPACING = 30 * DAY_SPACING YEAR_SPACING = 365 * DAY_SPACING if sys.platform == 'win32': _epoch = datetime.utcfromtimestamp(0) def utcfromtimestamp(timestamp): return _epoch + timedelta(seconds=timestamp) else: utcfromtimestamp = datetime.utcfromtimestamp MIN_REGULAR_TIMESTAMP = (datetime(1, 1, 1) - datetime(1970,1,1)).total_seconds() MAX_REGULAR_TIMESTAMP = (datetime(9999, 1, 1) - datetime(1970,1,1)).total_seconds() SEC_PER_YEAR = 365.25*24*3600 def makeMSStepper(stepSize): def stepper(val, n): if val < MIN_REGULAR_TIMESTAMP or val > MAX_REGULAR_TIMESTAMP: return np.inf val *= 1000 f = stepSize * 1000 return (val // (n*f) + 1) * (n*f) / 1000.0 return stepper def makeSStepper(stepSize): def stepper(val, n): if val < MIN_REGULAR_TIMESTAMP or val > MAX_REGULAR_TIMESTAMP: return np.inf return (val // (n*stepSize) + 1) * (n*stepSize) return stepper def makeMStepper(stepSize): def stepper(val, n): if val < MIN_REGULAR_TIMESTAMP or val > MAX_REGULAR_TIMESTAMP: return np.inf d = utcfromtimestamp(val) base0m = (d.month + n*stepSize - 1) d = datetime(d.year + base0m // 12, base0m % 12 + 1, 1) return (d - datetime(1970, 1, 1)).total_seconds() return stepper def makeYStepper(stepSize): def stepper(val, n): if val < MIN_REGULAR_TIMESTAMP or val > MAX_REGULAR_TIMESTAMP: return np.inf d = utcfromtimestamp(val) next_year = (d.year // (n*stepSize) + 1) * (n*stepSize) if next_year > 9999: return np.inf next_date = datetime(next_year, 1, 1) return (next_date - datetime(1970, 1, 1)).total_seconds() return stepper class TickSpec: """ Specifies the properties for a set of date ticks and computes ticks within a given utc timestamp range """ def __init__(self, spacing, stepper, format, autoSkip=None): """ ============= ========================================================== Arguments spacing approximate (average) tick spacing stepper a stepper function that takes a utc time stamp and a step steps number n to compute the start of the next unit. You can use the make_X_stepper functions to create common steppers. format a strftime compatible format string which will be used to convert tick locations to date/time strings autoSkip list of step size multipliers to be applied when the tick density becomes too high. The tick spec automatically applies additional powers of 10 (10, 100, ...) to the list if necessary. Set to None to switch autoSkip off ============= ========================================================== """ self.spacing = spacing self.step = stepper self.format = format self.autoSkip = autoSkip def makeTicks(self, minVal, maxVal, minSpc): ticks = [] n = self.skipFactor(minSpc) x = self.step(minVal, n) while x <= maxVal: ticks.append(x) x = self.step(x, n) return (np.array(ticks), n) def skipFactor(self, minSpc): if self.autoSkip is None or minSpc < self.spacing: return 1 factors = np.array(self.autoSkip, dtype=np.float) while True: for f in factors: spc = self.spacing * f if spc > minSpc: return int(f) factors *= 10 class ZoomLevel: """ Generates the ticks which appear in a specific zoom level """ def __init__(self, tickSpecs, exampleText): """ ============= ========================================================== tickSpecs a list of one or more TickSpec objects with decreasing coarseness ============= ========================================================== """ self.tickSpecs = tickSpecs self.utcOffset = 0 self.exampleText = exampleText def tickValues(self, minVal, maxVal, minSpc): # return tick values for this format in the range minVal, maxVal # the return value is a list of tuples (<avg spacing>, [tick positions]) # minSpc indicates the minimum spacing (in seconds) between two ticks # to fullfill the maxTicksPerPt constraint of the DateAxisItem at the # current zoom level. This is used for auto skipping ticks. allTicks = [] valueSpecs = [] # back-project (minVal maxVal) to UTC, compute ticks then offset to # back to local time again utcMin = minVal - self.utcOffset utcMax = maxVal - self.utcOffset for spec in self.tickSpecs: ticks, skipFactor = spec.makeTicks(utcMin, utcMax, minSpc) # reposition tick labels to local time coordinates ticks += self.utcOffset # remove any ticks that were present in higher levels tick_list = [x for x in ticks.tolist() if x not in allTicks] allTicks.extend(tick_list) valueSpecs.append((spec.spacing, tick_list)) # if we're skipping ticks on the current level there's no point in # producing lower level ticks if skipFactor > 1: break return valueSpecs YEAR_MONTH_ZOOM_LEVEL = ZoomLevel([ TickSpec(YEAR_SPACING, makeYStepper(1), '%Y', autoSkip=[1, 5, 10, 25]), TickSpec(MONTH_SPACING, makeMStepper(1), '%b') ], "YYYY") MONTH_DAY_ZOOM_LEVEL = ZoomLevel([ TickSpec(MONTH_SPACING, makeMStepper(1), '%b'), TickSpec(DAY_SPACING, makeSStepper(DAY_SPACING), '%d', autoSkip=[1, 5]) ], "MMM") DAY_HOUR_ZOOM_LEVEL = ZoomLevel([ TickSpec(DAY_SPACING, makeSStepper(DAY_SPACING), '%a %d'), TickSpec(HOUR_SPACING, makeSStepper(HOUR_SPACING), '%H:%M', autoSkip=[1, 6]) ], "MMM 00") HOUR_MINUTE_ZOOM_LEVEL = ZoomLevel([ TickSpec(DAY_SPACING, makeSStepper(DAY_SPACING), '%a %d'), TickSpec(MINUTE_SPACING, makeSStepper(MINUTE_SPACING), '%H:%M', autoSkip=[1, 5, 15]) ], "MMM 00") HMS_ZOOM_LEVEL = ZoomLevel([ TickSpec(SECOND_SPACING, makeSStepper(SECOND_SPACING), '%H:%M:%S', autoSkip=[1, 5, 15, 30]) ], "99:99:99") MS_ZOOM_LEVEL = ZoomLevel([ TickSpec(MINUTE_SPACING, makeSStepper(MINUTE_SPACING), '%H:%M:%S'), TickSpec(MS_SPACING, makeMSStepper(MS_SPACING), '%S.%f', autoSkip=[1, 5, 10, 25]) ], "99:99:99") class DateAxisItem(AxisItem): """ **Bases:** :class:`AxisItem <pyqtgraph.AxisItem>` An AxisItem that displays dates from unix timestamps. The display format is adjusted automatically depending on the current time density (seconds/point) on the axis. For more details on changing this behaviour, see :func:`setZoomLevelForDensity() <pyqtgraph.DateAxisItem.setZoomLevelForDensity>`. Can be added to an existing plot e.g. via :func:`setAxisItems({'bottom':axis}) <pyqtgraph.PlotItem.setAxisItems>`. """ def __init__(self, orientation='bottom', **kwargs): """ Create a new DateAxisItem. For `orientation` and `**kwargs`, see :func:`AxisItem.__init__ <pyqtgraph.AxisItem.__init__>`. """ super(DateAxisItem, self).__init__(orientation, **kwargs) # Set the zoom level to use depending on the time density on the axis self.utcOffset = time.timezone self.zoomLevels = OrderedDict([ (np.inf, YEAR_MONTH_ZOOM_LEVEL), (5 * 3600*24, MONTH_DAY_ZOOM_LEVEL), (6 * 3600, DAY_HOUR_ZOOM_LEVEL), (15 * 60, HOUR_MINUTE_ZOOM_LEVEL), (30, HMS_ZOOM_LEVEL), (1, MS_ZOOM_LEVEL), ]) def tickStrings(self, values, scale, spacing): tickSpecs = self.zoomLevel.tickSpecs tickSpec = next((s for s in tickSpecs if s.spacing == spacing), None) try: dates = [utcfromtimestamp(v - self.utcOffset) for v in values] except (OverflowError, ValueError, OSError): # should not normally happen return ['%g' % ((v-self.utcOffset)//SEC_PER_YEAR + 1970) for v in values] formatStrings = [] for x in dates: try: s = x.strftime(tickSpec.format) if '%f' in tickSpec.format: # we only support ms precision s = s[:-3] elif '%Y' in tickSpec.format: s = s.lstrip('0') formatStrings.append(s) except ValueError: # Windows can't handle dates before 1970 formatStrings.append('') return formatStrings def tickValues(self, minVal, maxVal, size): density = (maxVal - minVal) / size self.setZoomLevelForDensity(density) values = self.zoomLevel.tickValues(minVal, maxVal, minSpc=self.minSpacing) return values def setZoomLevelForDensity(self, density): """ Setting `zoomLevel` and `minSpacing` based on given density of seconds per pixel The display format is adjusted automatically depending on the current time density (seconds/point) on the axis. You can customize the behaviour by overriding this function or setting a different set of zoom levels than the default one. The `zoomLevels` variable is a dictionary with the maximal distance of ticks in seconds which are allowed for each zoom level before the axis switches to the next coarser level. To customize the zoom level selection, override this function. """ padding = 10 # Size in pixels a specific tick label will take if self.orientation in ['bottom', 'top']: def sizeOf(text): return self.fontMetrics.boundingRect(text).width() + padding*self.fontScaleFactor else: def sizeOf(text): return self.fontMetrics.boundingRect(text).height() + padding*self.fontScaleFactor # Fallback zoom level: Years/Months self.zoomLevel = YEAR_MONTH_ZOOM_LEVEL for maximalSpacing, zoomLevel in self.zoomLevels.items(): size = sizeOf(zoomLevel.exampleText) # Test if zoom level is too fine grained if maximalSpacing/size < density: break self.zoomLevel = zoomLevel # Set up zoomLevel self.zoomLevel.utcOffset = self.utcOffset # Calculate minimal spacing of items on the axis size = sizeOf(self.zoomLevel.exampleText) self.minSpacing = density*size def linkToView(self, view): super(DateAxisItem, self).linkToView(view) # Set default limits _min = MIN_REGULAR_TIMESTAMP _max = MAX_REGULAR_TIMESTAMP if self.orientation in ['right', 'left']: view.setLimits(yMin=_min, yMax=_max) else: view.setLimits(xMin=_min, xMax=_max) def generateDrawSpecs(self, p): # Get font metrics from QPainter # Not happening in "paint", as the QPainter p there is a different one from the one here, # so changing that font could cause unwanted side effects if self.style['tickFont'] is not None: p.setFont(self.style['tickFont']) self.fontMetrics = p.fontMetrics() # Get font scale factor by current window resolution self.fontScaleFactor = p.device().logicalDpiX() / 96 return super(DateAxisItem, self).generateDrawSpecs(p)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/GraphicsWidget.py
.py
2,151
60
from ..Qt import QtGui, QtCore from ..GraphicsScene import GraphicsScene from .GraphicsItem import GraphicsItem __all__ = ['GraphicsWidget'] class GraphicsWidget(GraphicsItem, QtGui.QGraphicsWidget): _qtBaseClass = QtGui.QGraphicsWidget def __init__(self, *args, **kargs): """ **Bases:** :class:`GraphicsItem <pyqtgraph.GraphicsItem>`, :class:`QtGui.QGraphicsWidget` Extends QGraphicsWidget with several helpful methods and workarounds for PyQt bugs. Most of the extra functionality is inherited from :class:`GraphicsItem <pyqtgraph.GraphicsItem>`. """ QtGui.QGraphicsWidget.__init__(self, *args, **kargs) GraphicsItem.__init__(self) ## done by GraphicsItem init #GraphicsScene.registerObject(self) ## workaround for pyqt bug in graphicsscene.items() # Removed due to https://bugreports.qt-project.org/browse/PYSIDE-86 #def itemChange(self, change, value): ## BEWARE: Calling QGraphicsWidget.itemChange can lead to crashing! ##ret = QtGui.QGraphicsWidget.itemChange(self, change, value) ## segv occurs here ## The default behavior is just to return the value argument, so we'll do that ## without calling the original method. #ret = value #if change in [self.ItemParentHasChanged, self.ItemSceneHasChanged]: #self._updateView() #return ret def setFixedHeight(self, h): self.setMaximumHeight(h) self.setMinimumHeight(h) def setFixedWidth(self, h): self.setMaximumWidth(h) self.setMinimumWidth(h) def height(self): return self.geometry().height() def width(self): return self.geometry().width() def boundingRect(self): br = self.mapRectFromParent(self.geometry()).normalized() #print "bounds:", br return br def shape(self): ## No idea why this is necessary, but rotated items do not receive clicks otherwise. p = QtGui.QPainterPath() p.addRect(self.boundingRect()) #print "shape:", p.boundingRect() return p
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/PlotDataItem.py
.py
35,978
875
# -*- coding: utf-8 -*- import numpy as np from .. import metaarray as metaarray from ..Qt import QtCore from .GraphicsObject import GraphicsObject from .PlotCurveItem import PlotCurveItem from .ScatterPlotItem import ScatterPlotItem from .. import functions as fn from .. import debug as debug from .. import getConfigOption class PlotDataItem(GraphicsObject): """ **Bases:** :class:`GraphicsObject <pyqtgraph.GraphicsObject>` GraphicsItem for displaying plot curves, scatter plots, or both. While it is possible to use :class:`PlotCurveItem <pyqtgraph.PlotCurveItem>` or :class:`ScatterPlotItem <pyqtgraph.ScatterPlotItem>` individually, this class provides a unified interface to both. Instances of :class:`PlotDataItem` are usually created by plot() methods such as :func:`pyqtgraph.plot` and :func:`PlotItem.plot() <pyqtgraph.PlotItem.plot>`. ============================== ============================================== **Signals:** sigPlotChanged(self) Emitted when the data in this item is updated. sigClicked(self) Emitted when the item is clicked. sigPointsClicked(self, points) Emitted when a plot point is clicked Sends the list of points under the mouse. ============================== ============================================== """ sigPlotChanged = QtCore.Signal(object) sigClicked = QtCore.Signal(object) sigPointsClicked = QtCore.Signal(object, object) def __init__(self, *args, **kargs): """ There are many different ways to create a PlotDataItem: **Data initialization arguments:** (x,y data only) =================================== ====================================== PlotDataItem(xValues, yValues) x and y values may be any sequence (including ndarray) of real numbers PlotDataItem(yValues) y values only -- x will be automatically set to range(len(y)) PlotDataItem(x=xValues, y=yValues) x and y given by keyword arguments PlotDataItem(ndarray(Nx2)) numpy array with shape (N, 2) where ``x=data[:,0]`` and ``y=data[:,1]`` =================================== ====================================== **Data initialization arguments:** (x,y data AND may include spot style) ============================ ========================================= PlotDataItem(recarray) numpy array with ``dtype=[('x', float), ('y', float), ...]`` PlotDataItem(list-of-dicts) ``[{'x': x, 'y': y, ...}, ...]`` PlotDataItem(dict-of-lists) ``{'x': [...], 'y': [...], ...}`` PlotDataItem(MetaArray) 1D array of Y values with X sepecified as axis values OR 2D array with a column 'y' and extra columns as needed. ============================ ========================================= **Line style keyword arguments:** ============ ============================================================================== connect Specifies how / whether vertexes should be connected. See :func:`arrayToQPath() <pyqtgraph.arrayToQPath>` pen Pen to use for drawing line between points. Default is solid grey, 1px width. Use None to disable line drawing. May be any single argument accepted by :func:`mkPen() <pyqtgraph.mkPen>` shadowPen Pen for secondary line to draw behind the primary line. disabled by default. May be any single argument accepted by :func:`mkPen() <pyqtgraph.mkPen>` fillLevel Fill the area between the curve and fillLevel fillOutline (bool) If True, an outline surrounding the *fillLevel* area is drawn. fillBrush Fill to use when fillLevel is specified. May be any single argument accepted by :func:`mkBrush() <pyqtgraph.mkBrush>` stepMode If True, two orthogonal lines are drawn for each sample as steps. This is commonly used when drawing histograms. Note that in this case, ``len(x) == len(y) + 1`` (added in version 0.9.9) ============ ============================================================================== **Point style keyword arguments:** (see :func:`ScatterPlotItem.setData() <pyqtgraph.ScatterPlotItem.setData>` for more information) ============ ===================================================== symbol Symbol to use for drawing points OR list of symbols, one per point. Default is no symbol. Options are o, s, t, d, +, or any QPainterPath symbolPen Outline pen for drawing points OR list of pens, one per point. May be any single argument accepted by :func:`mkPen() <pyqtgraph.mkPen>` symbolBrush Brush for filling points OR list of brushes, one per point. May be any single argument accepted by :func:`mkBrush() <pyqtgraph.mkBrush>` symbolSize Diameter of symbols OR list of diameters. pxMode (bool) If True, then symbolSize is specified in pixels. If False, then symbolSize is specified in data coordinates. ============ ===================================================== **Optimization keyword arguments:** ================ ===================================================================== antialias (bool) By default, antialiasing is disabled to improve performance. Note that in some cases (in particluar, when pxMode=True), points will be rendered antialiased even if this is set to False. decimate deprecated. downsample (int) Reduce the number of samples displayed by this value downsampleMethod 'subsample': Downsample by taking the first of N samples. This method is fastest and least accurate. 'mean': Downsample by taking the mean of N samples. 'peak': Downsample by drawing a saw wave that follows the min and max of the original data. This method produces the best visual representation of the data but is slower. autoDownsample (bool) If True, resample the data before plotting to avoid plotting multiple line segments per pixel. This can improve performance when viewing very high-density data, but increases the initial overhead and memory usage. clipToView (bool) If True, only plot data that is visible within the X range of the containing ViewBox. This can improve performance when plotting very large data sets where only a fraction of the data is visible at any time. identical *deprecated* ================ ===================================================================== **Meta-info keyword arguments:** ========== ================================================ name name of dataset. This would appear in a legend ========== ================================================ """ GraphicsObject.__init__(self) self.setFlag(self.ItemHasNoContents) self.xData = None self.yData = None self.xDisp = None self.yDisp = None #self.dataMask = None #self.curves = [] #self.scatters = [] self.curve = PlotCurveItem() self.scatter = ScatterPlotItem() self.curve.setParentItem(self) self.scatter.setParentItem(self) self.curve.sigClicked.connect(self.curveClicked) self.scatter.sigClicked.connect(self.scatterClicked) #self.clear() self.opts = { 'connect': 'all', 'fftMode': False, 'logMode': [False, False], 'alphaHint': 1.0, 'alphaMode': False, 'pen': (200,200,200), 'shadowPen': None, 'fillLevel': None, 'fillOutline': False, 'fillBrush': None, 'stepMode': None, 'symbol': None, 'symbolSize': 10, 'symbolPen': (200,200,200), 'symbolBrush': (50, 50, 150), 'pxMode': True, 'antialias': getConfigOption('antialias'), 'pointMode': None, 'downsample': 1, 'autoDownsample': False, 'downsampleMethod': 'peak', 'autoDownsampleFactor': 5., # draw ~5 samples per pixel 'clipToView': False, 'data': None, } self.setData(*args, **kargs) def implements(self, interface=None): ints = ['plotData'] if interface is None: return ints return interface in ints def name(self): return self.opts.get('name', None) def boundingRect(self): return QtCore.QRectF() ## let child items handle this def setAlpha(self, alpha, auto): if self.opts['alphaHint'] == alpha and self.opts['alphaMode'] == auto: return self.opts['alphaHint'] = alpha self.opts['alphaMode'] = auto self.setOpacity(alpha) #self.update() def setFftMode(self, mode): if self.opts['fftMode'] == mode: return self.opts['fftMode'] = mode self.xDisp = self.yDisp = None self.xClean = self.yClean = None self.updateItems() self.informViewBoundsChanged() def setLogMode(self, xMode, yMode): if self.opts['logMode'] == [xMode, yMode]: return self.opts['logMode'] = [xMode, yMode] self.xDisp = self.yDisp = None self.xClean = self.yClean = None self.updateItems() self.informViewBoundsChanged() def setPointMode(self, mode): if self.opts['pointMode'] == mode: return self.opts['pointMode'] = mode self.update() def setPen(self, *args, **kargs): """ | Sets the pen used to draw lines between points. | *pen* can be a QPen or any argument accepted by :func:`pyqtgraph.mkPen() <pyqtgraph.mkPen>` """ pen = fn.mkPen(*args, **kargs) self.opts['pen'] = pen #self.curve.setPen(pen) #for c in self.curves: #c.setPen(pen) #self.update() self.updateItems() def setShadowPen(self, *args, **kargs): """ | Sets the shadow pen used to draw lines between points (this is for enhancing contrast or emphacizing data). | This line is drawn behind the primary pen (see :func:`setPen() <pyqtgraph.PlotDataItem.setPen>`) and should generally be assigned greater width than the primary pen. | *pen* can be a QPen or any argument accepted by :func:`pyqtgraph.mkPen() <pyqtgraph.mkPen>` """ pen = fn.mkPen(*args, **kargs) self.opts['shadowPen'] = pen #for c in self.curves: #c.setPen(pen) #self.update() self.updateItems() def setFillBrush(self, *args, **kargs): brush = fn.mkBrush(*args, **kargs) if self.opts['fillBrush'] == brush: return self.opts['fillBrush'] = brush self.updateItems() def setBrush(self, *args, **kargs): return self.setFillBrush(*args, **kargs) def setFillLevel(self, level): if self.opts['fillLevel'] == level: return self.opts['fillLevel'] = level self.updateItems() def setSymbol(self, symbol): if self.opts['symbol'] == symbol: return self.opts['symbol'] = symbol #self.scatter.setSymbol(symbol) self.updateItems() def setSymbolPen(self, *args, **kargs): pen = fn.mkPen(*args, **kargs) if self.opts['symbolPen'] == pen: return self.opts['symbolPen'] = pen #self.scatter.setSymbolPen(pen) self.updateItems() def setSymbolBrush(self, *args, **kargs): brush = fn.mkBrush(*args, **kargs) if self.opts['symbolBrush'] == brush: return self.opts['symbolBrush'] = brush #self.scatter.setSymbolBrush(brush) self.updateItems() def setSymbolSize(self, size): if self.opts['symbolSize'] == size: return self.opts['symbolSize'] = size #self.scatter.setSymbolSize(symbolSize) self.updateItems() def setDownsampling(self, ds=None, auto=None, method=None): """ Set the downsampling mode of this item. Downsampling reduces the number of samples drawn to increase performance. ============== ================================================================= **Arguments:** ds (int) Reduce visible plot samples by this factor. To disable, set ds=1. auto (bool) If True, automatically pick *ds* based on visible range mode 'subsample': Downsample by taking the first of N samples. This method is fastest and least accurate. 'mean': Downsample by taking the mean of N samples. 'peak': Downsample by drawing a saw wave that follows the min and max of the original data. This method produces the best visual representation of the data but is slower. ============== ================================================================= """ changed = False if ds is not None: if self.opts['downsample'] != ds: changed = True self.opts['downsample'] = ds if auto is not None and self.opts['autoDownsample'] != auto: self.opts['autoDownsample'] = auto changed = True if method is not None: if self.opts['downsampleMethod'] != method: changed = True self.opts['downsampleMethod'] = method if changed: self.xDisp = self.yDisp = None self.updateItems() def setClipToView(self, clip): if self.opts['clipToView'] == clip: return self.opts['clipToView'] = clip self.xDisp = self.yDisp = None self.updateItems() def setData(self, *args, **kargs): """ Clear any data displayed by this item and display new data. See :func:`__init__() <pyqtgraph.PlotDataItem.__init__>` for details; it accepts the same arguments. """ #self.clear() profiler = debug.Profiler() y = None x = None if len(args) == 1: data = args[0] dt = dataType(data) if dt == 'empty': pass elif dt == 'listOfValues': y = np.array(data) elif dt == 'Nx2array': x = data[:,0] y = data[:,1] elif dt == 'recarray' or dt == 'dictOfLists': if 'x' in data: x = np.array(data['x']) if 'y' in data: y = np.array(data['y']) elif dt == 'listOfDicts': if 'x' in data[0]: x = np.array([d.get('x',None) for d in data]) if 'y' in data[0]: y = np.array([d.get('y',None) for d in data]) for k in ['data', 'symbolSize', 'symbolPen', 'symbolBrush', 'symbolShape']: if k in data: kargs[k] = [d.get(k, None) for d in data] elif dt == 'MetaArray': y = data.view(np.ndarray) x = data.xvals(0).view(np.ndarray) else: raise Exception('Invalid data type %s' % type(data)) elif len(args) == 2: seq = ('listOfValues', 'MetaArray', 'empty') dtyp = dataType(args[0]), dataType(args[1]) if dtyp[0] not in seq or dtyp[1] not in seq: raise Exception('When passing two unnamed arguments, both must be a list or array of values. (got %s, %s)' % (str(type(args[0])), str(type(args[1])))) if not isinstance(args[0], np.ndarray): #x = np.array(args[0]) if dtyp[0] == 'MetaArray': x = args[0].asarray() else: x = np.array(args[0]) else: x = args[0].view(np.ndarray) if not isinstance(args[1], np.ndarray): #y = np.array(args[1]) if dtyp[1] == 'MetaArray': y = args[1].asarray() else: y = np.array(args[1]) else: y = args[1].view(np.ndarray) if 'x' in kargs: x = kargs['x'] if 'y' in kargs: y = kargs['y'] profiler('interpret data') ## pull in all style arguments. ## Use self.opts to fill in anything not present in kargs. if 'name' in kargs: self.opts['name'] = kargs['name'] if 'connect' in kargs: self.opts['connect'] = kargs['connect'] ## if symbol pen/brush are given with no symbol, then assume symbol is 'o' if 'symbol' not in kargs and ('symbolPen' in kargs or 'symbolBrush' in kargs or 'symbolSize' in kargs): kargs['symbol'] = 'o' if 'brush' in kargs: kargs['fillBrush'] = kargs['brush'] for k in list(self.opts.keys()): if k in kargs: self.opts[k] = kargs[k] #curveArgs = {} #for k in ['pen', 'shadowPen', 'fillLevel', 'brush']: #if k in kargs: #self.opts[k] = kargs[k] #curveArgs[k] = self.opts[k] #scatterArgs = {} #for k,v in [('symbolPen','pen'), ('symbolBrush','brush'), ('symbol','symbol')]: #if k in kargs: #self.opts[k] = kargs[k] #scatterArgs[v] = self.opts[k] if y is None: self.updateItems() profiler('update items') return if y is not None and x is None: x = np.arange(len(y)) if not isinstance(x, np.ndarray): x = np.array(x) if not isinstance(y, np.ndarray): y = np.array(y) self.xData = x.view(np.ndarray) ## one last check to make sure there are no MetaArrays getting by self.yData = y.view(np.ndarray) self.xClean = self.yClean = None self.xDisp = None self.yDisp = None profiler('set data') self.updateItems() profiler('update items') self.informViewBoundsChanged() #view = self.getViewBox() #if view is not None: #view.itemBoundsChanged(self) ## inform view so it can update its range if it wants self.sigPlotChanged.emit(self) profiler('emit') def updateItems(self): curveArgs = {} for k,v in [('pen','pen'), ('shadowPen','shadowPen'), ('fillLevel','fillLevel'), ('fillOutline', 'fillOutline'), ('fillBrush', 'brush'), ('antialias', 'antialias'), ('connect', 'connect'), ('stepMode', 'stepMode')]: curveArgs[v] = self.opts[k] scatterArgs = {} for k,v in [('symbolPen','pen'), ('symbolBrush','brush'), ('symbol','symbol'), ('symbolSize', 'size'), ('data', 'data'), ('pxMode', 'pxMode'), ('antialias', 'antialias')]: if k in self.opts: scatterArgs[v] = self.opts[k] x,y = self.getData() #scatterArgs['mask'] = self.dataMask if curveArgs['pen'] is not None or (curveArgs['brush'] is not None and curveArgs['fillLevel'] is not None): self.curve.setData(x=x, y=y, **curveArgs) self.curve.show() else: self.curve.hide() if scatterArgs['symbol'] is not None: if self.opts.get('stepMode', False) is True: x = 0.5 * (x[:-1] + x[1:]) self.scatter.setData(x=x, y=y, **scatterArgs) self.scatter.show() else: self.scatter.hide() def getData(self): if self.xData is None: return (None, None) if self.xDisp is None: x = self.xData y = self.yData if self.opts['fftMode']: x,y = self._fourierTransform(x, y) # Ignore the first bin for fft data if we have a logx scale if self.opts['logMode'][0]: x=x[1:] y=y[1:] with np.errstate(divide='ignore'): if self.opts['logMode'][0]: x = np.log10(x) if self.opts['logMode'][1]: y = np.log10(y) ds = self.opts['downsample'] if not isinstance(ds, int): ds = 1 if self.opts['autoDownsample']: # this option presumes that x-values have uniform spacing range = self.viewRect() if range is not None and len(x) > 1: dx = float(x[-1]-x[0]) / (len(x)-1) if dx != 0.0: x0 = (range.left()-x[0]) / dx x1 = (range.right()-x[0]) / dx width = self.getViewBox().width() if width != 0.0: ds = int(max(1, int((x1-x0) / (width*self.opts['autoDownsampleFactor'])))) ## downsampling is expensive; delay until after clipping. if self.opts['clipToView']: view = self.getViewBox() if view is None or not view.autoRangeEnabled()[0]: # this option presumes that x-values are in increasing order range = self.viewRect() if range is not None and len(x) > 1: # clip to visible region extended by downsampling value, assuming # uniform spacing of x-values, has O(1) performance dx = float(x[-1]-x[0]) / (len(x)-1) x0 = np.clip(int((range.left()-x[0])/dx) - 1*ds, 0, len(x)-1) x1 = np.clip(int((range.right()-x[0])/dx) + 2*ds, 0, len(x)-1) # if data has been clipped too strongly (in case of non-uniform # spacing of x-values), refine the clipping region as required # worst case performance: O(log(n)) # best case performance: O(1) if x[x0] > range.left(): x0 = np.searchsorted(x, range.left()) - 1*ds x0 = np.clip(x0, a_min=0, a_max=len(x)) if x[x1] < range.right(): x1 = np.searchsorted(x, range.right()) + 2*ds x1 = np.clip(x1, a_min=0, a_max=len(x)) x = x[x0:x1] y = y[x0:x1] if ds > 1: if self.opts['downsampleMethod'] == 'subsample': x = x[::ds] y = y[::ds] elif self.opts['downsampleMethod'] == 'mean': n = len(x) // ds x = x[:n*ds:ds] y = y[:n*ds].reshape(n,ds).mean(axis=1) elif self.opts['downsampleMethod'] == 'peak': n = len(x) // ds x1 = np.empty((n,2)) x1[:] = x[:n*ds:ds,np.newaxis] x = x1.reshape(n*2) y1 = np.empty((n,2)) y2 = y[:n*ds].reshape((n, ds)) y1[:,0] = y2.max(axis=1) y1[:,1] = y2.min(axis=1) y = y1.reshape(n*2) self.xDisp = x self.yDisp = y return self.xDisp, self.yDisp def dataBounds(self, ax, frac=1.0, orthoRange=None): """ Returns the range occupied by the data (along a specific axis) in this item. This method is called by ViewBox when auto-scaling. =============== ============================================================= **Arguments:** ax (0 or 1) the axis for which to return this item's data range frac (float 0.0-1.0) Specifies what fraction of the total data range to return. By default, the entire range is returned. This allows the ViewBox to ignore large spikes in the data when auto-scaling. orthoRange ([min,max] or None) Specifies that only the data within the given range (orthogonal to *ax*) should me measured when returning the data range. (For example, a ViewBox might ask what is the y-range of all data with x-values between min and max) =============== ============================================================= """ range = [None, None] if self.curve.isVisible(): range = self.curve.dataBounds(ax, frac, orthoRange) elif self.scatter.isVisible(): r2 = self.scatter.dataBounds(ax, frac, orthoRange) range = [ r2[0] if range[0] is None else (range[0] if r2[0] is None else min(r2[0], range[0])), r2[1] if range[1] is None else (range[1] if r2[1] is None else min(r2[1], range[1])) ] return range def pixelPadding(self): """ Return the size in pixels that this item may draw beyond the values returned by dataBounds(). This method is called by ViewBox when auto-scaling. """ pad = 0 if self.curve.isVisible(): pad = max(pad, self.curve.pixelPadding()) elif self.scatter.isVisible(): pad = max(pad, self.scatter.pixelPadding()) return pad def clear(self): #for i in self.curves+self.scatters: #if i.scene() is not None: #i.scene().removeItem(i) #self.curves = [] #self.scatters = [] self.xData = None self.yData = None #self.xClean = None #self.yClean = None self.xDisp = None self.yDisp = None self.curve.clear() self.scatter.clear() def appendData(self, *args, **kargs): pass def curveClicked(self): self.sigClicked.emit(self) def scatterClicked(self, plt, points): self.sigClicked.emit(self) self.sigPointsClicked.emit(self, points) def viewRangeChanged(self): # view range has changed; re-plot if needed if self.opts['clipToView'] or self.opts['autoDownsample']: self.xDisp = self.yDisp = None self.updateItems() def _fourierTransform(self, x, y): ## Perform fourier transform. If x values are not sampled uniformly, ## then use np.interp to resample before taking fft. dx = np.diff(x) uniform = not np.any(np.abs(dx-dx[0]) > (abs(dx[0]) / 1000.)) if not uniform: x2 = np.linspace(x[0], x[-1], len(x)) y = np.interp(x2, x, y) x = x2 n = y.size f = np.fft.rfft(y) / n d = float(x[-1]-x[0]) / (len(x)-1) x = np.fft.rfftfreq(n, d) y = np.abs(f) return x, y def dataType(obj): if hasattr(obj, '__len__') and len(obj) == 0: return 'empty' if isinstance(obj, dict): return 'dictOfLists' elif isSequence(obj): first = obj[0] if (hasattr(obj, 'implements') and obj.implements('MetaArray')): return 'MetaArray' elif isinstance(obj, np.ndarray): if obj.ndim == 1: if obj.dtype.names is None: return 'listOfValues' else: return 'recarray' elif obj.ndim == 2 and obj.dtype.names is None and obj.shape[1] == 2: return 'Nx2array' else: raise Exception('array shape must be (N,) or (N,2); got %s instead' % str(obj.shape)) elif isinstance(first, dict): return 'listOfDicts' else: return 'listOfValues' def isSequence(obj): return hasattr(obj, '__iter__') or isinstance(obj, np.ndarray) or (hasattr(obj, 'implements') and obj.implements('MetaArray')) #class TableData: #""" #Class for presenting multiple forms of tabular data through a consistent interface. #May contain: #- numpy record array #- list-of-dicts (all dicts are _not_ required to have the same keys) #- dict-of-lists #- dict (single record) #Note: if all the values in this record are lists, it will be interpreted as multiple records #Data can be accessed and modified by column, by row, or by value #data[columnName] #data[rowId] #data[columnName, rowId] = value #data[columnName] = [value, value, ...] #data[rowId] = {columnName: value, ...} #""" #def __init__(self, data): #self.data = data #if isinstance(data, np.ndarray): #self.mode = 'array' #elif isinstance(data, list): #self.mode = 'list' #elif isinstance(data, dict): #types = set(map(type, data.values())) ### dict may be a dict-of-lists or a single record #types -= set([list, np.ndarray]) ## if dict contains any non-sequence values, it is probably a single record. #if len(types) != 0: #self.data = [self.data] #self.mode = 'list' #else: #self.mode = 'dict' #elif isinstance(data, TableData): #self.data = data.data #self.mode = data.mode #else: #raise TypeError(type(data)) #for fn in ['__getitem__', '__setitem__']: #setattr(self, fn, getattr(self, '_TableData'+fn+self.mode)) #def originalData(self): #return self.data #def toArray(self): #if self.mode == 'array': #return self.data #if len(self) < 1: ##return np.array([]) ## need to return empty array *with correct columns*, but this is very difficult, so just return None #return None #rec1 = self[0] #dtype = functions.suggestRecordDType(rec1) ##print rec1, dtype #arr = np.empty(len(self), dtype=dtype) #arr[0] = tuple(rec1.values()) #for i in xrange(1, len(self)): #arr[i] = tuple(self[i].values()) #return arr #def __getitem__array(self, arg): #if isinstance(arg, tuple): #return self.data[arg[0]][arg[1]] #else: #return self.data[arg] #def __getitem__list(self, arg): #if isinstance(arg, basestring): #return [d.get(arg, None) for d in self.data] #elif isinstance(arg, int): #return self.data[arg] #elif isinstance(arg, tuple): #arg = self._orderArgs(arg) #return self.data[arg[0]][arg[1]] #else: #raise TypeError(type(arg)) #def __getitem__dict(self, arg): #if isinstance(arg, basestring): #return self.data[arg] #elif isinstance(arg, int): #return dict([(k, v[arg]) for k, v in self.data.items()]) #elif isinstance(arg, tuple): #arg = self._orderArgs(arg) #return self.data[arg[1]][arg[0]] #else: #raise TypeError(type(arg)) #def __setitem__array(self, arg, val): #if isinstance(arg, tuple): #self.data[arg[0]][arg[1]] = val #else: #self.data[arg] = val #def __setitem__list(self, arg, val): #if isinstance(arg, basestring): #if len(val) != len(self.data): #raise Exception("Values (%d) and data set (%d) are not the same length." % (len(val), len(self.data))) #for i, rec in enumerate(self.data): #rec[arg] = val[i] #elif isinstance(arg, int): #self.data[arg] = val #elif isinstance(arg, tuple): #arg = self._orderArgs(arg) #self.data[arg[0]][arg[1]] = val #else: #raise TypeError(type(arg)) #def __setitem__dict(self, arg, val): #if isinstance(arg, basestring): #if len(val) != len(self.data[arg]): #raise Exception("Values (%d) and data set (%d) are not the same length." % (len(val), len(self.data[arg]))) #self.data[arg] = val #elif isinstance(arg, int): #for k in self.data: #self.data[k][arg] = val[k] #elif isinstance(arg, tuple): #arg = self._orderArgs(arg) #self.data[arg[1]][arg[0]] = val #else: #raise TypeError(type(arg)) #def _orderArgs(self, args): ### return args in (int, str) order #if isinstance(args[0], basestring): #return (args[1], args[0]) #else: #return args #def __iter__(self): #for i in xrange(len(self)): #yield self[i] #def __len__(self): #if self.mode == 'array' or self.mode == 'list': #return len(self.data) #else: #return max(map(len, self.data.values())) #def columnNames(self): #"""returns column names in no particular order""" #if self.mode == 'array': #return self.data.dtype.names #elif self.mode == 'list': #names = set() #for row in self.data: #names.update(row.keys()) #return list(names) #elif self.mode == 'dict': #return self.data.keys() #def keys(self): #return self.columnNames()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/ScatterPlotItem.py
.py
36,929
965
from itertools import starmap, repeat try: from itertools import imap except ImportError: imap = map import numpy as np import weakref from ..Qt import QtGui, QtCore, QT_LIB from ..Point import Point from .. import functions as fn from .GraphicsItem import GraphicsItem from .GraphicsObject import GraphicsObject from .. import getConfigOption from ..pgcollections import OrderedDict from .. import debug from ..python2_3 import basestring __all__ = ['ScatterPlotItem', 'SpotItem'] ## Build all symbol paths Symbols = OrderedDict([(name, QtGui.QPainterPath()) for name in ['o', 's', 't', 't1', 't2', 't3','d', '+', 'x', 'p', 'h', 'star']]) Symbols['o'].addEllipse(QtCore.QRectF(-0.5, -0.5, 1, 1)) Symbols['s'].addRect(QtCore.QRectF(-0.5, -0.5, 1, 1)) coords = { 't': [(-0.5, -0.5), (0, 0.5), (0.5, -0.5)], 't1': [(-0.5, 0.5), (0, -0.5), (0.5, 0.5)], 't2': [(-0.5, -0.5), (-0.5, 0.5), (0.5, 0)], 't3': [(0.5, 0.5), (0.5, -0.5), (-0.5, 0)], 'd': [(0., -0.5), (-0.4, 0.), (0, 0.5), (0.4, 0)], '+': [ (-0.5, -0.05), (-0.5, 0.05), (-0.05, 0.05), (-0.05, 0.5), (0.05, 0.5), (0.05, 0.05), (0.5, 0.05), (0.5, -0.05), (0.05, -0.05), (0.05, -0.5), (-0.05, -0.5), (-0.05, -0.05) ], 'p': [(0, -0.5), (-0.4755, -0.1545), (-0.2939, 0.4045), (0.2939, 0.4045), (0.4755, -0.1545)], 'h': [(0.433, 0.25), (0., 0.5), (-0.433, 0.25), (-0.433, -0.25), (0, -0.5), (0.433, -0.25)], 'star': [(0, -0.5), (-0.1123, -0.1545), (-0.4755, -0.1545), (-0.1816, 0.059), (-0.2939, 0.4045), (0, 0.1910), (0.2939, 0.4045), (0.1816, 0.059), (0.4755, -0.1545), (0.1123, -0.1545)] } for k, c in coords.items(): Symbols[k].moveTo(*c[0]) for x,y in c[1:]: Symbols[k].lineTo(x, y) Symbols[k].closeSubpath() tr = QtGui.QTransform() tr.rotate(45) Symbols['x'] = tr.map(Symbols['+']) def drawSymbol(painter, symbol, size, pen, brush): if symbol is None: return painter.scale(size, size) painter.setPen(pen) painter.setBrush(brush) if isinstance(symbol, basestring): symbol = Symbols[symbol] if np.isscalar(symbol): symbol = list(Symbols.values())[symbol % len(Symbols)] painter.drawPath(symbol) def renderSymbol(symbol, size, pen, brush, device=None): """ Render a symbol specification to QImage. Symbol may be either a QPainterPath or one of the keys in the Symbols dict. If *device* is None, a new QPixmap will be returned. Otherwise, the symbol will be rendered into the device specified (See QPainter documentation for more information). """ ## Render a spot with the given parameters to a pixmap penPxWidth = max(np.ceil(pen.widthF()), 1) if device is None: device = QtGui.QImage(int(size+penPxWidth), int(size+penPxWidth), QtGui.QImage.Format_ARGB32) device.fill(0) p = QtGui.QPainter(device) try: p.setRenderHint(p.Antialiasing) p.translate(device.width()*0.5, device.height()*0.5) drawSymbol(p, symbol, size, pen, brush) finally: p.end() return device def makeSymbolPixmap(size, pen, brush, symbol): ## deprecated img = renderSymbol(symbol, size, pen, brush) return QtGui.QPixmap(img) class SymbolAtlas(object): """ Used to efficiently construct a single QPixmap containing all rendered symbols for a ScatterPlotItem. This is required for fragment rendering. Use example: atlas = SymbolAtlas() sc1 = atlas.getSymbolCoords('o', 5, QPen(..), QBrush(..)) sc2 = atlas.getSymbolCoords('t', 10, QPen(..), QBrush(..)) pm = atlas.getAtlas() """ def __init__(self): # symbol key : QRect(...) coordinates where symbol can be found in atlas. # note that the coordinate list will always be the same list object as # long as the symbol is in the atlas, but the coordinates may # change if the atlas is rebuilt. # weak value; if all external refs to this list disappear, # the symbol will be forgotten. self.symbolMap = weakref.WeakValueDictionary() self.atlasData = None # numpy array of atlas image self.atlas = None # atlas as QPixmap self.atlasValid = False self.max_width=0 def getSymbolCoords(self, opts): """ Given a list of spot records, return an object representing the coordinates of that symbol within the atlas """ sourceRect = [] keyi = None sourceRecti = None symbol_map = self.symbolMap for i, rec in enumerate(opts.tolist()): size, symbol, pen, brush = rec[2: 6] key = id(symbol), size, id(pen), id(brush) if key == keyi: sourceRect.append(sourceRecti) else: try: sourceRect.append(symbol_map[key]) except KeyError: newRectSrc = QtCore.QRectF() newRectSrc.pen = pen newRectSrc.brush = brush newRectSrc.symbol = symbol symbol_map[key] = newRectSrc self.atlasValid = False sourceRect.append(newRectSrc) keyi = key sourceRecti = newRectSrc sourceRect = np.array(sourceRect, dtype=object) return sourceRect def buildAtlas(self): # get rendered array for all symbols, keep track of avg/max width rendered = {} avgWidth = 0.0 maxWidth = 0 images = [] for key, sourceRect in self.symbolMap.items(): if sourceRect.width() == 0: img = renderSymbol(sourceRect.symbol, key[1], sourceRect.pen, sourceRect.brush) images.append(img) ## we only need this to prevent the images being garbage collected immediately arr = fn.imageToArray(img, copy=False, transpose=False) else: (y,x,h,w) = sourceRect.getRect() arr = self.atlasData[int(x):int(x+w), int(y):int(y+w)] rendered[key] = arr w = arr.shape[0] avgWidth += w maxWidth = max(maxWidth, w) nSymbols = len(rendered) if nSymbols > 0: avgWidth /= nSymbols width = max(maxWidth, avgWidth * (nSymbols**0.5)) else: avgWidth = 0 width = 0 # sort symbols by height symbols = sorted(rendered.keys(), key=lambda x: rendered[x].shape[1], reverse=True) self.atlasRows = [] x = width y = 0 rowheight = 0 for key in symbols: arr = rendered[key] w,h = arr.shape[:2] if x+w > width: y += rowheight x = 0 rowheight = h self.atlasRows.append([y, rowheight, 0]) self.symbolMap[key].setRect(y, x, h, w) x += w self.atlasRows[-1][2] = x height = y + rowheight self.atlasData = np.zeros((int(width), int(height), 4), dtype=np.ubyte) for key in symbols: y, x, h, w = self.symbolMap[key].getRect() self.atlasData[int(x):int(x+w), int(y):int(y+h)] = rendered[key] self.atlas = None self.atlasValid = True self.max_width = maxWidth def getAtlas(self): if not self.atlasValid: self.buildAtlas() if self.atlas is None: if len(self.atlasData) == 0: return QtGui.QPixmap(0,0) img = fn.makeQImage(self.atlasData, copy=False, transpose=False) self.atlas = QtGui.QPixmap(img) return self.atlas class ScatterPlotItem(GraphicsObject): """ Displays a set of x/y points. Instances of this class are created automatically as part of PlotDataItem; these rarely need to be instantiated directly. The size, shape, pen, and fill brush may be set for each point individually or for all points. ======================== =============================================== **Signals:** sigPlotChanged(self) Emitted when the data being plotted has changed sigClicked(self, points) Emitted when the curve is clicked. Sends a list of all the points under the mouse pointer. ======================== =============================================== """ #sigPointClicked = QtCore.Signal(object, object) sigClicked = QtCore.Signal(object, object) ## self, points sigPlotChanged = QtCore.Signal(object) def __init__(self, *args, **kargs): """ Accepts the same arguments as setData() """ profiler = debug.Profiler() GraphicsObject.__init__(self) self.picture = None # QPicture used for rendering when pxmode==False self.fragmentAtlas = SymbolAtlas() self.data = np.empty(0, dtype=[('x', float), ('y', float), ('size', float), ('symbol', object), ('pen', object), ('brush', object), ('data', object), ('item', object), ('sourceRect', object), ('targetRect', object), ('width', float)]) self.bounds = [None, None] ## caches data bounds self._maxSpotWidth = 0 ## maximum size of the scale-variant portion of all spots self._maxSpotPxWidth = 0 ## maximum size of the scale-invariant portion of all spots self.opts = { 'pxMode': True, 'useCache': True, ## If useCache is False, symbols are re-drawn on every paint. 'antialias': getConfigOption('antialias'), 'compositionMode': None, 'name': None, } self.setPen(fn.mkPen(getConfigOption('foreground')), update=False) self.setBrush(fn.mkBrush(100,100,150), update=False) self.setSymbol('o', update=False) self.setSize(7, update=False) profiler() self.setData(*args, **kargs) profiler('setData') #self.setCacheMode(self.DeviceCoordinateCache) def setData(self, *args, **kargs): """ **Ordered Arguments:** * If there is only one unnamed argument, it will be interpreted like the 'spots' argument. * If there are two unnamed arguments, they will be interpreted as sequences of x and y values. ====================== =============================================================================================== **Keyword Arguments:** *spots* Optional list of dicts. Each dict specifies parameters for a single spot: {'pos': (x,y), 'size', 'pen', 'brush', 'symbol'}. This is just an alternate method of passing in data for the corresponding arguments. *x*,*y* 1D arrays of x,y values. *pos* 2D structure of x,y pairs (such as Nx2 array or list of tuples) *pxMode* If True, spots are always the same size regardless of scaling, and size is given in px. Otherwise, size is in scene coordinates and the spots scale with the view. Default is True *symbol* can be one (or a list) of: * 'o' circle (default) * 's' square * 't' triangle * 'd' diamond * '+' plus * any QPainterPath to specify custom symbol shapes. To properly obey the position and size, custom symbols should be centered at (0,0) and width and height of 1.0. Note that it is also possible to 'install' custom shapes by setting ScatterPlotItem.Symbols[key] = shape. *pen* The pen (or list of pens) to use for drawing spot outlines. *brush* The brush (or list of brushes) to use for filling spots. *size* The size (or list of sizes) of spots. If *pxMode* is True, this value is in pixels. Otherwise, it is in the item's local coordinate system. *data* a list of python objects used to uniquely identify each spot. *identical* *Deprecated*. This functionality is handled automatically now. *antialias* Whether to draw symbols with antialiasing. Note that if pxMode is True, symbols are always rendered with antialiasing (since the rendered symbols can be cached, this incurs very little performance cost) *compositionMode* If specified, this sets the composition mode used when drawing the scatter plot (see QPainter::CompositionMode in the Qt documentation). *name* The name of this item. Names are used for automatically generating LegendItem entries and by some exporters. ====================== =============================================================================================== """ oldData = self.data ## this causes cached pixmaps to be preserved while new data is registered. self.clear() ## clear out all old data self.addPoints(*args, **kargs) def addPoints(self, *args, **kargs): """ Add new points to the scatter plot. Arguments are the same as setData() """ ## deal with non-keyword arguments if len(args) == 1: kargs['spots'] = args[0] elif len(args) == 2: kargs['x'] = args[0] kargs['y'] = args[1] elif len(args) > 2: raise Exception('Only accepts up to two non-keyword arguments.') ## convert 'pos' argument to 'x' and 'y' if 'pos' in kargs: pos = kargs['pos'] if isinstance(pos, np.ndarray): kargs['x'] = pos[:,0] kargs['y'] = pos[:,1] else: x = [] y = [] for p in pos: if isinstance(p, QtCore.QPointF): x.append(p.x()) y.append(p.y()) else: x.append(p[0]) y.append(p[1]) kargs['x'] = x kargs['y'] = y ## determine how many spots we have if 'spots' in kargs: numPts = len(kargs['spots']) elif 'y' in kargs and kargs['y'] is not None: numPts = len(kargs['y']) else: kargs['x'] = [] kargs['y'] = [] numPts = 0 ## Extend record array oldData = self.data self.data = np.empty(len(oldData)+numPts, dtype=self.data.dtype) ## note that np.empty initializes object fields to None and string fields to '' self.data[:len(oldData)] = oldData #for i in range(len(oldData)): #oldData[i]['item']._data = self.data[i] ## Make sure items have proper reference to new array newData = self.data[len(oldData):] newData['size'] = -1 ## indicates to use default size if 'spots' in kargs: spots = kargs['spots'] for i in range(len(spots)): spot = spots[i] for k in spot: if k == 'pos': pos = spot[k] if isinstance(pos, QtCore.QPointF): x,y = pos.x(), pos.y() else: x,y = pos[0], pos[1] newData[i]['x'] = x newData[i]['y'] = y elif k == 'pen': newData[i][k] = fn.mkPen(spot[k]) elif k == 'brush': newData[i][k] = fn.mkBrush(spot[k]) elif k in ['x', 'y', 'size', 'symbol', 'brush', 'data']: newData[i][k] = spot[k] else: raise Exception("Unknown spot parameter: %s" % k) elif 'y' in kargs: newData['x'] = kargs['x'] newData['y'] = kargs['y'] if 'pxMode' in kargs: self.setPxMode(kargs['pxMode']) if 'antialias' in kargs: self.opts['antialias'] = kargs['antialias'] ## Set any extra parameters provided in keyword arguments for k in ['pen', 'brush', 'symbol', 'size']: if k in kargs: setMethod = getattr(self, 'set' + k[0].upper() + k[1:]) setMethod(kargs[k], update=False, dataSet=newData, mask=kargs.get('mask', None)) if 'data' in kargs: self.setPointData(kargs['data'], dataSet=newData) self.prepareGeometryChange() self.informViewBoundsChanged() self.bounds = [None, None] self.invalidate() self.updateSpots(newData) self.sigPlotChanged.emit(self) def invalidate(self): ## clear any cached drawing state self.picture = None self.update() def getData(self): return self.data['x'], self.data['y'] def setPoints(self, *args, **kargs): ##Deprecated; use setData return self.setData(*args, **kargs) def implements(self, interface=None): ints = ['plotData'] if interface is None: return ints return interface in ints def name(self): return self.opts.get('name', None) def setPen(self, *args, **kargs): """Set the pen(s) used to draw the outline around each spot. If a list or array is provided, then the pen for each spot will be set separately. Otherwise, the arguments are passed to pg.mkPen and used as the default pen for all spots which do not have a pen explicitly set.""" update = kargs.pop('update', True) dataSet = kargs.pop('dataSet', self.data) if len(args) == 1 and (isinstance(args[0], np.ndarray) or isinstance(args[0], list)): pens = args[0] if 'mask' in kargs and kargs['mask'] is not None: pens = pens[kargs['mask']] if len(pens) != len(dataSet): raise Exception("Number of pens does not match number of points (%d != %d)" % (len(pens), len(dataSet))) dataSet['pen'] = pens else: self.opts['pen'] = fn.mkPen(*args, **kargs) dataSet['sourceRect'] = None if update: self.updateSpots(dataSet) def setBrush(self, *args, **kargs): """Set the brush(es) used to fill the interior of each spot. If a list or array is provided, then the brush for each spot will be set separately. Otherwise, the arguments are passed to pg.mkBrush and used as the default brush for all spots which do not have a brush explicitly set.""" update = kargs.pop('update', True) dataSet = kargs.pop('dataSet', self.data) if len(args) == 1 and (isinstance(args[0], np.ndarray) or isinstance(args[0], list)): brushes = args[0] if 'mask' in kargs and kargs['mask'] is not None: brushes = brushes[kargs['mask']] if len(brushes) != len(dataSet): raise Exception("Number of brushes does not match number of points (%d != %d)" % (len(brushes), len(dataSet))) dataSet['brush'] = brushes else: self.opts['brush'] = fn.mkBrush(*args, **kargs) #self._spotPixmap = None dataSet['sourceRect'] = None if update: self.updateSpots(dataSet) def setSymbol(self, symbol, update=True, dataSet=None, mask=None): """Set the symbol(s) used to draw each spot. If a list or array is provided, then the symbol for each spot will be set separately. Otherwise, the argument will be used as the default symbol for all spots which do not have a symbol explicitly set.""" if dataSet is None: dataSet = self.data if isinstance(symbol, np.ndarray) or isinstance(symbol, list): symbols = symbol if mask is not None: symbols = symbols[mask] if len(symbols) != len(dataSet): raise Exception("Number of symbols does not match number of points (%d != %d)" % (len(symbols), len(dataSet))) dataSet['symbol'] = symbols else: self.opts['symbol'] = symbol self._spotPixmap = None dataSet['sourceRect'] = None if update: self.updateSpots(dataSet) def setSize(self, size, update=True, dataSet=None, mask=None): """Set the size(s) used to draw each spot. If a list or array is provided, then the size for each spot will be set separately. Otherwise, the argument will be used as the default size for all spots which do not have a size explicitly set.""" if dataSet is None: dataSet = self.data if isinstance(size, np.ndarray) or isinstance(size, list): sizes = size if mask is not None: sizes = sizes[mask] if len(sizes) != len(dataSet): raise Exception("Number of sizes does not match number of points (%d != %d)" % (len(sizes), len(dataSet))) dataSet['size'] = sizes else: self.opts['size'] = size self._spotPixmap = None dataSet['sourceRect'] = None if update: self.updateSpots(dataSet) def setPointData(self, data, dataSet=None, mask=None): if dataSet is None: dataSet = self.data if isinstance(data, np.ndarray) or isinstance(data, list): if mask is not None: data = data[mask] if len(data) != len(dataSet): raise Exception("Length of meta data does not match number of points (%d != %d)" % (len(data), len(dataSet))) ## Bug: If data is a numpy record array, then items from that array must be copied to dataSet one at a time. ## (otherwise they are converted to tuples and thus lose their field names. if isinstance(data, np.ndarray) and (data.dtype.fields is not None)and len(data.dtype.fields) > 1: for i, rec in enumerate(data): dataSet['data'][i] = rec else: dataSet['data'] = data def setPxMode(self, mode): if self.opts['pxMode'] == mode: return self.opts['pxMode'] = mode self.invalidate() def updateSpots(self, dataSet=None): if dataSet is None: dataSet = self.data invalidate = False if self.opts['pxMode']: mask = np.equal(dataSet['sourceRect'], None) if np.any(mask): invalidate = True opts = self.getSpotOpts(dataSet[mask]) sourceRect = self.fragmentAtlas.getSymbolCoords(opts) dataSet['sourceRect'][mask] = sourceRect self.fragmentAtlas.getAtlas() # generate atlas so source widths are available. dataSet['width'] = np.array(list(imap(QtCore.QRectF.width, dataSet['sourceRect'])))/2 dataSet['targetRect'] = None self._maxSpotPxWidth = self.fragmentAtlas.max_width else: self._maxSpotWidth = 0 self._maxSpotPxWidth = 0 self.measureSpotSizes(dataSet) if invalidate: self.invalidate() def getSpotOpts(self, recs, scale=1.0): if recs.ndim == 0: rec = recs symbol = rec['symbol'] if symbol is None: symbol = self.opts['symbol'] size = rec['size'] if size < 0: size = self.opts['size'] pen = rec['pen'] if pen is None: pen = self.opts['pen'] brush = rec['brush'] if brush is None: brush = self.opts['brush'] return (symbol, size*scale, fn.mkPen(pen), fn.mkBrush(brush)) else: recs = recs.copy() recs['symbol'][np.equal(recs['symbol'], None)] = self.opts['symbol'] recs['size'][np.equal(recs['size'], -1)] = self.opts['size'] recs['size'] *= scale recs['pen'][np.equal(recs['pen'], None)] = fn.mkPen(self.opts['pen']) recs['brush'][np.equal(recs['brush'], None)] = fn.mkBrush(self.opts['brush']) return recs def measureSpotSizes(self, dataSet): for rec in dataSet: ## keep track of the maximum spot size and pixel size symbol, size, pen, brush = self.getSpotOpts(rec) width = 0 pxWidth = 0 if self.opts['pxMode']: pxWidth = size + pen.widthF() else: width = size if pen.isCosmetic(): pxWidth += pen.widthF() else: width += pen.widthF() self._maxSpotWidth = max(self._maxSpotWidth, width) self._maxSpotPxWidth = max(self._maxSpotPxWidth, pxWidth) self.bounds = [None, None] def clear(self): """Remove all spots from the scatter plot""" #self.clearItems() self.data = np.empty(0, dtype=self.data.dtype) self.bounds = [None, None] self.invalidate() def dataBounds(self, ax, frac=1.0, orthoRange=None): if frac >= 1.0 and orthoRange is None and self.bounds[ax] is not None: return self.bounds[ax] #self.prepareGeometryChange() if self.data is None or len(self.data) == 0: return (None, None) if ax == 0: d = self.data['x'] d2 = self.data['y'] elif ax == 1: d = self.data['y'] d2 = self.data['x'] if orthoRange is not None: mask = (d2 >= orthoRange[0]) * (d2 <= orthoRange[1]) d = d[mask] d2 = d2[mask] if d.size == 0: return (None, None) if frac >= 1.0: self.bounds[ax] = (np.nanmin(d) - self._maxSpotWidth*0.7072, np.nanmax(d) + self._maxSpotWidth*0.7072) return self.bounds[ax] elif frac <= 0.0: raise Exception("Value for parameter 'frac' must be > 0. (got %s)" % str(frac)) else: mask = np.isfinite(d) d = d[mask] return np.percentile(d, [50 * (1 - frac), 50 * (1 + frac)]) def pixelPadding(self): return self._maxSpotPxWidth*0.7072 def boundingRect(self): (xmn, xmx) = self.dataBounds(ax=0) (ymn, ymx) = self.dataBounds(ax=1) if xmn is None or xmx is None: xmn = 0 xmx = 0 if ymn is None or ymx is None: ymn = 0 ymx = 0 px = py = 0.0 pxPad = self.pixelPadding() if pxPad > 0: # determine length of pixel in local x, y directions px, py = self.pixelVectors() try: px = 0 if px is None else px.length() except OverflowError: px = 0 try: py = 0 if py is None else py.length() except OverflowError: py = 0 # return bounds expanded by pixel size px *= pxPad py *= pxPad return QtCore.QRectF(xmn-px, ymn-py, (2*px)+xmx-xmn, (2*py)+ymx-ymn) def viewTransformChanged(self): self.prepareGeometryChange() GraphicsObject.viewTransformChanged(self) self.bounds = [None, None] self.data['targetRect'] = None def setExportMode(self, *args, **kwds): GraphicsObject.setExportMode(self, *args, **kwds) self.invalidate() def mapPointsToDevice(self, pts): # Map point locations to device tr = self.deviceTransform() if tr is None: return None pts = fn.transformCoordinates(tr, pts) pts -= self.data['width'] pts = np.clip(pts, -2**30, 2**30) ## prevent Qt segmentation fault. return pts def getViewMask(self, pts): # Return bool mask indicating all points that are within viewbox # pts is expressed in *device coordiantes* vb = self.getViewBox() if vb is None: return None viewBounds = vb.mapRectToDevice(vb.boundingRect()) w = self.data['width'] mask = ((pts[0] + w > viewBounds.left()) & (pts[0] - w < viewBounds.right()) & (pts[1] + w > viewBounds.top()) & (pts[1] - w < viewBounds.bottom())) ## remove out of view points return mask @debug.warnOnException ## raising an exception here causes crash def paint(self, p, *args): cmode = self.opts.get('compositionMode', None) if cmode is not None: p.setCompositionMode(cmode) #p.setPen(fn.mkPen('r')) #p.drawRect(self.boundingRect()) if self._exportOpts is not False: aa = self._exportOpts.get('antialias', True) scale = self._exportOpts.get('resolutionScale', 1.0) ## exporting to image; pixel resolution may have changed else: aa = self.opts['antialias'] scale = 1.0 if self.opts['pxMode'] is True: p.resetTransform() # Map point coordinates to device pts = np.vstack([self.data['x'], self.data['y']]) pts = self.mapPointsToDevice(pts) if pts is None: return # Cull points that are outside view viewMask = self.getViewMask(pts) if self.opts['useCache'] and self._exportOpts is False: # Draw symbols from pre-rendered atlas atlas = self.fragmentAtlas.getAtlas() # Update targetRects if necessary updateMask = viewMask & np.equal(self.data['targetRect'], None) if np.any(updateMask): updatePts = pts[:,updateMask] width = self.data[updateMask]['width']*2 self.data['targetRect'][updateMask] = list(imap(QtCore.QRectF, updatePts[0,:], updatePts[1,:], width, width)) data = self.data[viewMask] if QT_LIB == 'PyQt4': p.drawPixmapFragments(data['targetRect'].tolist(), data['sourceRect'].tolist(), atlas) else: list(imap(p.drawPixmap, data['targetRect'], repeat(atlas), data['sourceRect'])) else: # render each symbol individually p.setRenderHint(p.Antialiasing, aa) data = self.data[viewMask] pts = pts[:,viewMask] for i, rec in enumerate(data): p.resetTransform() p.translate(pts[0,i] + rec['width']/2, pts[1,i] + rec['width']/2) drawSymbol(p, *self.getSpotOpts(rec, scale)) else: if self.picture is None: self.picture = QtGui.QPicture() p2 = QtGui.QPainter(self.picture) for rec in self.data: if scale != 1.0: rec = rec.copy() rec['size'] *= scale p2.resetTransform() p2.translate(rec['x'], rec['y']) drawSymbol(p2, *self.getSpotOpts(rec, scale)) p2.end() p.setRenderHint(p.Antialiasing, aa) self.picture.play(p) def points(self): for i,rec in enumerate(self.data): if rec['item'] is None: rec['item'] = SpotItem(rec, self, i) return self.data['item'] def pointsAt(self, pos): x = pos.x() y = pos.y() pw = self.pixelWidth() ph = self.pixelHeight() pts = [] for s in self.points(): sp = s.pos() ss = s.size() sx = sp.x() sy = sp.y() s2x = s2y = ss * 0.5 if self.opts['pxMode']: s2x *= pw s2y *= ph if x > sx-s2x and x < sx+s2x and y > sy-s2y and y < sy+s2y: pts.append(s) #print "HIT:", x, y, sx, sy, s2x, s2y #else: #print "No hit:", (x, y), (sx, sy) #print " ", (sx-s2x, sy-s2y), (sx+s2x, sy+s2y) return pts[::-1] def mouseClickEvent(self, ev): if ev.button() == QtCore.Qt.LeftButton: pts = self.pointsAt(ev.pos()) if len(pts) > 0: self.ptsClicked = pts ev.accept() self.sigClicked.emit(self, self.ptsClicked) else: #print "no spots" ev.ignore() else: ev.ignore() class SpotItem(object): """ Class referring to individual spots in a scatter plot. These can be retrieved by calling ScatterPlotItem.points() or by connecting to the ScatterPlotItem's click signals. """ def __init__(self, data, plot, index): self._data = data self._index = index # SpotItems are kept in plot.data["items"] numpy object array which # does not support cyclic garbage collection (numpy issue 6581). # Keeping a strong ref to plot here would leak the cycle self.__plot_ref = weakref.ref(plot) @property def _plot(self): return self.__plot_ref() def data(self): """Return the user data associated with this spot.""" return self._data['data'] def index(self): """Return the index of this point as given in the scatter plot data.""" return self._index def size(self): """Return the size of this spot. If the spot has no explicit size set, then return the ScatterPlotItem's default size instead.""" if self._data['size'] == -1: return self._plot.opts['size'] else: return self._data['size'] def pos(self): return Point(self._data['x'], self._data['y']) def viewPos(self): return self._plot.mapToView(self.pos()) def setSize(self, size): """Set the size of this spot. If the size is set to -1, then the ScatterPlotItem's default size will be used instead.""" self._data['size'] = size self.updateItem() def symbol(self): """Return the symbol of this spot. If the spot has no explicit symbol set, then return the ScatterPlotItem's default symbol instead. """ symbol = self._data['symbol'] if symbol is None: symbol = self._plot.opts['symbol'] try: n = int(symbol) symbol = list(Symbols.keys())[n % len(Symbols)] except: pass return symbol def setSymbol(self, symbol): """Set the symbol for this spot. If the symbol is set to '', then the ScatterPlotItem's default symbol will be used instead.""" self._data['symbol'] = symbol self.updateItem() def pen(self): pen = self._data['pen'] if pen is None: pen = self._plot.opts['pen'] return fn.mkPen(pen) def setPen(self, *args, **kargs): """Set the outline pen for this spot""" pen = fn.mkPen(*args, **kargs) self._data['pen'] = pen self.updateItem() def resetPen(self): """Remove the pen set for this spot; the scatter plot's default pen will be used instead.""" self._data['pen'] = None ## Note this is NOT the same as calling setPen(None) self.updateItem() def brush(self): brush = self._data['brush'] if brush is None: brush = self._plot.opts['brush'] return fn.mkBrush(brush) def setBrush(self, *args, **kargs): """Set the fill brush for this spot""" brush = fn.mkBrush(*args, **kargs) self._data['brush'] = brush self.updateItem() def resetBrush(self): """Remove the brush set for this spot; the scatter plot's default brush will be used instead.""" self._data['brush'] = None ## Note this is NOT the same as calling setBrush(None) self.updateItem() def setData(self, data): """Set the user-data associated with this spot""" self._data['data'] = data def updateItem(self): self._data['sourceRect'] = None self._plot.updateSpots(self._data.reshape(1)) self._plot.invalidate()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/GradientEditorItem.py
.py
38,002
952
# -*- coding: utf-8 -*- import operator import weakref import numpy as np from ..Qt import QtGui, QtCore from .. import functions as fn from .GraphicsObject import GraphicsObject from .GraphicsWidget import GraphicsWidget from ..widgets.SpinBox import SpinBox from ..pgcollections import OrderedDict from ..colormap import ColorMap __all__ = ['TickSliderItem', 'GradientEditorItem'] Gradients = OrderedDict([ ('thermal', {'ticks': [(0.3333, (185, 0, 0, 255)), (0.6666, (255, 220, 0, 255)), (1, (255, 255, 255, 255)), (0, (0, 0, 0, 255))], 'mode': 'rgb'}), ('flame', {'ticks': [(0.2, (7, 0, 220, 255)), (0.5, (236, 0, 134, 255)), (0.8, (246, 246, 0, 255)), (1.0, (255, 255, 255, 255)), (0.0, (0, 0, 0, 255))], 'mode': 'rgb'}), ('yellowy', {'ticks': [(0.0, (0, 0, 0, 255)), (0.2328863796753704, (32, 0, 129, 255)), (0.8362738179251941, (255, 255, 0, 255)), (0.5257586450247, (115, 15, 255, 255)), (1.0, (255, 255, 255, 255))], 'mode': 'rgb'} ), ('bipolar', {'ticks': [(0.0, (0, 255, 255, 255)), (1.0, (255, 255, 0, 255)), (0.5, (0, 0, 0, 255)), (0.25, (0, 0, 255, 255)), (0.75, (255, 0, 0, 255))], 'mode': 'rgb'}), ('spectrum', {'ticks': [(1.0, (255, 0, 255, 255)), (0.0, (255, 0, 0, 255))], 'mode': 'hsv'}), ('cyclic', {'ticks': [(0.0, (255, 0, 4, 255)), (1.0, (255, 0, 0, 255))], 'mode': 'hsv'}), ('greyclip', {'ticks': [(0.0, (0, 0, 0, 255)), (0.99, (255, 255, 255, 255)), (1.0, (255, 0, 0, 255))], 'mode': 'rgb'}), ('grey', {'ticks': [(0.0, (0, 0, 0, 255)), (1.0, (255, 255, 255, 255))], 'mode': 'rgb'}), # Perceptually uniform sequential colormaps from Matplotlib 2.0 ('viridis', {'ticks': [(0.0, (68, 1, 84, 255)), (0.25, (58, 82, 139, 255)), (0.5, (32, 144, 140, 255)), (0.75, (94, 201, 97, 255)), (1.0, (253, 231, 36, 255))], 'mode': 'rgb'}), ('inferno', {'ticks': [(0.0, (0, 0, 3, 255)), (0.25, (87, 15, 109, 255)), (0.5, (187, 55, 84, 255)), (0.75, (249, 142, 8, 255)), (1.0, (252, 254, 164, 255))], 'mode': 'rgb'}), ('plasma', {'ticks': [(0.0, (12, 7, 134, 255)), (0.25, (126, 3, 167, 255)), (0.5, (203, 71, 119, 255)), (0.75, (248, 149, 64, 255)), (1.0, (239, 248, 33, 255))], 'mode': 'rgb'}), ('magma', {'ticks': [(0.0, (0, 0, 3, 255)), (0.25, (80, 18, 123, 255)), (0.5, (182, 54, 121, 255)), (0.75, (251, 136, 97, 255)), (1.0, (251, 252, 191, 255))], 'mode': 'rgb'}), ]) def addGradientListToDocstring(): """Decorator to add list of current pre-defined gradients to the end of a function docstring.""" def dec(fn): if fn.__doc__ is not None: fn.__doc__ = fn.__doc__ + str(Gradients.keys()).strip('[').strip(']') return fn return dec class TickSliderItem(GraphicsWidget): ## public class """**Bases:** :class:`GraphicsWidget <pyqtgraph.GraphicsWidget>` A rectangular item with tick marks along its length that can (optionally) be moved by the user.""" def __init__(self, orientation='bottom', allowAdd=True, **kargs): """ ============== ================================================================================= **Arguments:** orientation Set the orientation of the gradient. Options are: 'left', 'right' 'top', and 'bottom'. allowAdd Specifies whether ticks can be added to the item by the user. tickPen Default is white. Specifies the color of the outline of the ticks. Can be any of the valid arguments for :func:`mkPen <pyqtgraph.mkPen>` ============== ================================================================================= """ ## public GraphicsWidget.__init__(self) self.orientation = orientation self.length = 100 self.tickSize = 15 self.ticks = {} self.maxDim = 20 self.allowAdd = allowAdd if 'tickPen' in kargs: self.tickPen = fn.mkPen(kargs['tickPen']) else: self.tickPen = fn.mkPen('w') self.orientations = { 'left': (90, 1, 1), 'right': (90, 1, 1), 'top': (0, 1, -1), 'bottom': (0, 1, 1) } self.setOrientation(orientation) #self.setFrameStyle(QtGui.QFrame.NoFrame | QtGui.QFrame.Plain) #self.setBackgroundRole(QtGui.QPalette.NoRole) #self.setMouseTracking(True) #def boundingRect(self): #return self.mapRectFromParent(self.geometry()).normalized() #def shape(self): ## No idea why this is necessary, but rotated items do not receive clicks otherwise. #p = QtGui.QPainterPath() #p.addRect(self.boundingRect()) #return p def paint(self, p, opt, widget): #p.setPen(fn.mkPen('g', width=3)) #p.drawRect(self.boundingRect()) return def keyPressEvent(self, ev): ev.ignore() def setMaxDim(self, mx=None): if mx is None: mx = self.maxDim else: self.maxDim = mx if self.orientation in ['bottom', 'top']: self.setFixedHeight(mx) self.setMaximumWidth(16777215) else: self.setFixedWidth(mx) self.setMaximumHeight(16777215) def setOrientation(self, orientation): ## public """Set the orientation of the TickSliderItem. ============== =================================================================== **Arguments:** orientation Options are: 'left', 'right', 'top', 'bottom' The orientation option specifies which side of the slider the ticks are on, as well as whether the slider is vertical ('right' and 'left') or horizontal ('top' and 'bottom'). ============== =================================================================== """ self.orientation = orientation self.setMaxDim() self.resetTransform() ort = orientation if ort == 'top': transform = QtGui.QTransform.fromScale(1, -1) transform.translate(0, -self.height()) self.setTransform(transform) elif ort == 'left': transform = QtGui.QTransform() transform.rotate(270) transform.scale(1, -1) transform.translate(-self.height(), -self.maxDim) self.setTransform(transform) elif ort == 'right': transform = QtGui.QTransform() transform.rotate(270) transform.translate(-self.height(), 0) self.setTransform(transform) elif ort != 'bottom': raise Exception("%s is not a valid orientation. Options are 'left', 'right', 'top', and 'bottom'" %str(ort)) self.translate(self.tickSize/2., 0) def addTick(self, x, color=None, movable=True): ## public """ Add a tick to the item. ============== ================================================================== **Arguments:** x Position where tick should be added. color Color of added tick. If color is not specified, the color will be white. movable Specifies whether the tick is movable with the mouse. ============== ================================================================== """ if color is None: color = QtGui.QColor(255,255,255) tick = Tick(self, [x*self.length, 0], color, movable, self.tickSize, pen=self.tickPen) self.ticks[tick] = x tick.setParentItem(self) return tick def removeTick(self, tick): ## public """ Removes the specified tick. """ del self.ticks[tick] tick.setParentItem(None) if self.scene() is not None: self.scene().removeItem(tick) def tickMoved(self, tick, pos): #print "tick changed" ## Correct position of tick if it has left bounds. newX = min(max(0, pos.x()), self.length) pos.setX(newX) tick.setPos(pos) self.ticks[tick] = float(newX) / self.length def tickMoveFinished(self, tick): pass def tickClicked(self, tick, ev): if ev.button() == QtCore.Qt.RightButton: self.removeTick(tick) def widgetLength(self): if self.orientation in ['bottom', 'top']: return self.width() else: return self.height() def resizeEvent(self, ev): wlen = max(40, self.widgetLength()) self.setLength(wlen-self.tickSize-2) self.setOrientation(self.orientation) #bounds = self.scene().itemsBoundingRect() #bounds.setLeft(min(-self.tickSize*0.5, bounds.left())) #bounds.setRight(max(self.length + self.tickSize, bounds.right())) #self.setSceneRect(bounds) #self.fitInView(bounds, QtCore.Qt.KeepAspectRatio) def setLength(self, newLen): #private for t, x in list(self.ticks.items()): t.setPos(x * newLen + 1, t.pos().y()) self.length = float(newLen) #def mousePressEvent(self, ev): #QtGui.QGraphicsView.mousePressEvent(self, ev) #self.ignoreRelease = False #for i in self.items(ev.pos()): #if isinstance(i, Tick): #self.ignoreRelease = True #break ##if len(self.items(ev.pos())) > 0: ## Let items handle their own clicks ##self.ignoreRelease = True #def mouseReleaseEvent(self, ev): #QtGui.QGraphicsView.mouseReleaseEvent(self, ev) #if self.ignoreRelease: #return #pos = self.mapToScene(ev.pos()) #if ev.button() == QtCore.Qt.LeftButton and self.allowAdd: #if pos.x() < 0 or pos.x() > self.length: #return #if pos.y() < 0 or pos.y() > self.tickSize: #return #pos.setX(min(max(pos.x(), 0), self.length)) #self.addTick(pos.x()/self.length) #elif ev.button() == QtCore.Qt.RightButton: #self.showMenu(ev) def mouseClickEvent(self, ev): if ev.button() == QtCore.Qt.LeftButton and self.allowAdd: pos = ev.pos() if pos.x() < 0 or pos.x() > self.length: return if pos.y() < 0 or pos.y() > self.tickSize: return pos.setX(min(max(pos.x(), 0), self.length)) self.addTick(pos.x()/self.length) elif ev.button() == QtCore.Qt.RightButton: self.showMenu(ev) #if ev.button() == QtCore.Qt.RightButton: #if self.moving: #ev.accept() #self.setPos(self.startPosition) #self.moving = False #self.sigMoving.emit(self) #self.sigMoved.emit(self) #else: #pass #self.view().tickClicked(self, ev) ###remove def hoverEvent(self, ev): if (not ev.isExit()) and ev.acceptClicks(QtCore.Qt.LeftButton): ev.acceptClicks(QtCore.Qt.RightButton) ## show ghost tick #self.currentPen = fn.mkPen(255, 0,0) #else: #self.currentPen = self.pen #self.update() def showMenu(self, ev): pass def setTickColor(self, tick, color): """Set the color of the specified tick. ============== ================================================================== **Arguments:** tick Can be either an integer corresponding to the index of the tick or a Tick object. Ex: if you had a slider with 3 ticks and you wanted to change the middle tick, the index would be 1. color The color to make the tick. Can be any argument that is valid for :func:`mkBrush <pyqtgraph.mkBrush>` ============== ================================================================== """ tick = self.getTick(tick) tick.color = color tick.update() #tick.setBrush(QtGui.QBrush(QtGui.QColor(tick.color))) def setTickValue(self, tick, val): ## public """ Set the position (along the slider) of the tick. ============== ================================================================== **Arguments:** tick Can be either an integer corresponding to the index of the tick or a Tick object. Ex: if you had a slider with 3 ticks and you wanted to change the middle tick, the index would be 1. val The desired position of the tick. If val is < 0, position will be set to 0. If val is > 1, position will be set to 1. ============== ================================================================== """ tick = self.getTick(tick) val = min(max(0.0, val), 1.0) x = val * self.length pos = tick.pos() pos.setX(x) tick.setPos(pos) self.ticks[tick] = val self.updateGradient() def tickValue(self, tick): ## public """Return the value (from 0.0 to 1.0) of the specified tick. ============== ================================================================== **Arguments:** tick Can be either an integer corresponding to the index of the tick or a Tick object. Ex: if you had a slider with 3 ticks and you wanted the value of the middle tick, the index would be 1. ============== ================================================================== """ tick = self.getTick(tick) return self.ticks[tick] def getTick(self, tick): ## public """Return the Tick object at the specified index. ============== ================================================================== **Arguments:** tick An integer corresponding to the index of the desired tick. If the argument is not an integer it will be returned unchanged. ============== ================================================================== """ if type(tick) is int: tick = self.listTicks()[tick][0] return tick #def mouseMoveEvent(self, ev): #QtGui.QGraphicsView.mouseMoveEvent(self, ev) def listTicks(self): """Return a sorted list of all the Tick objects on the slider.""" ## public ticks = sorted(self.ticks.items(), key=operator.itemgetter(1)) return ticks class GradientEditorItem(TickSliderItem): """ **Bases:** :class:`TickSliderItem <pyqtgraph.TickSliderItem>` An item that can be used to define a color gradient. Implements common pre-defined gradients that are customizable by the user. :class: `GradientWidget <pyqtgraph.GradientWidget>` provides a widget with a GradientEditorItem that can be added to a GUI. ================================ =========================================================== **Signals:** sigGradientChanged(self) Signal is emitted anytime the gradient changes. The signal is emitted in real time while ticks are being dragged or colors are being changed. sigGradientChangeFinished(self) Signal is emitted when the gradient is finished changing. ================================ =========================================================== """ sigGradientChanged = QtCore.Signal(object) sigGradientChangeFinished = QtCore.Signal(object) def __init__(self, *args, **kargs): """ Create a new GradientEditorItem. All arguments are passed to :func:`TickSliderItem.__init__ <pyqtgraph.TickSliderItem.__init__>` =============== ================================================================================= **Arguments:** orientation Set the orientation of the gradient. Options are: 'left', 'right' 'top', and 'bottom'. allowAdd Default is True. Specifies whether ticks can be added to the item. tickPen Default is white. Specifies the color of the outline of the ticks. Can be any of the valid arguments for :func:`mkPen <pyqtgraph.mkPen>` =============== ================================================================================= """ self.currentTick = None self.currentTickColor = None self.rectSize = 15 self.gradRect = QtGui.QGraphicsRectItem(QtCore.QRectF(0, self.rectSize, 100, self.rectSize)) self.backgroundRect = QtGui.QGraphicsRectItem(QtCore.QRectF(0, -self.rectSize, 100, self.rectSize)) self.backgroundRect.setBrush(QtGui.QBrush(QtCore.Qt.DiagCrossPattern)) self.colorMode = 'rgb' TickSliderItem.__init__(self, *args, **kargs) self.colorDialog = QtGui.QColorDialog() self.colorDialog.setOption(QtGui.QColorDialog.ShowAlphaChannel, True) self.colorDialog.setOption(QtGui.QColorDialog.DontUseNativeDialog, True) self.colorDialog.currentColorChanged.connect(self.currentColorChanged) self.colorDialog.rejected.connect(self.currentColorRejected) self.colorDialog.accepted.connect(self.currentColorAccepted) self.backgroundRect.setParentItem(self) self.gradRect.setParentItem(self) self.setMaxDim(self.rectSize + self.tickSize) self.rgbAction = QtGui.QAction('RGB', self) self.rgbAction.setCheckable(True) self.rgbAction.triggered.connect(lambda: self.setColorMode('rgb')) self.hsvAction = QtGui.QAction('HSV', self) self.hsvAction.setCheckable(True) self.hsvAction.triggered.connect(lambda: self.setColorMode('hsv')) self.menu = QtGui.QMenu() ## build context menu of gradients l = self.length self.length = 100 global Gradients for g in Gradients: px = QtGui.QPixmap(100, 15) p = QtGui.QPainter(px) self.restoreState(Gradients[g]) grad = self.getGradient() brush = QtGui.QBrush(grad) p.fillRect(QtCore.QRect(0, 0, 100, 15), brush) p.end() label = QtGui.QLabel() label.setPixmap(px) label.setContentsMargins(1, 1, 1, 1) labelName = QtGui.QLabel(g) hbox = QtGui.QHBoxLayout() hbox.addWidget(labelName) hbox.addWidget(label) widget = QtGui.QWidget() widget.setLayout(hbox) act = QtGui.QWidgetAction(self) act.setDefaultWidget(widget) act.triggered.connect(self.contextMenuClicked) act.name = g self.menu.addAction(act) self.length = l self.menu.addSeparator() self.menu.addAction(self.rgbAction) self.menu.addAction(self.hsvAction) for t in list(self.ticks.keys()): self.removeTick(t) self.addTick(0, QtGui.QColor(0,0,0), True) self.addTick(1, QtGui.QColor(255,0,0), True) self.setColorMode('rgb') self.updateGradient() def setOrientation(self, orientation): ## public """ Set the orientation of the GradientEditorItem. ============== =================================================================== **Arguments:** orientation Options are: 'left', 'right', 'top', 'bottom' The orientation option specifies which side of the gradient the ticks are on, as well as whether the gradient is vertical ('right' and 'left') or horizontal ('top' and 'bottom'). ============== =================================================================== """ TickSliderItem.setOrientation(self, orientation) self.translate(0, self.rectSize) def showMenu(self, ev): #private self.menu.popup(ev.screenPos().toQPoint()) def contextMenuClicked(self, b=None): #private #global Gradients act = self.sender() self.loadPreset(act.name) @addGradientListToDocstring() def loadPreset(self, name): """ Load a predefined gradient. Currently defined gradients are: """## TODO: provide image with names of defined gradients #global Gradients self.restoreState(Gradients[name]) def setColorMode(self, cm): """ Set the color mode for the gradient. Options are: 'hsv', 'rgb' """ ## public if cm not in ['rgb', 'hsv']: raise Exception("Unknown color mode %s. Options are 'rgb' and 'hsv'." % str(cm)) try: self.rgbAction.blockSignals(True) self.hsvAction.blockSignals(True) self.rgbAction.setChecked(cm == 'rgb') self.hsvAction.setChecked(cm == 'hsv') finally: self.rgbAction.blockSignals(False) self.hsvAction.blockSignals(False) self.colorMode = cm self.updateGradient() def colorMap(self): """Return a ColorMap object representing the current state of the editor.""" if self.colorMode == 'hsv': raise NotImplementedError('hsv colormaps not yet supported') pos = [] color = [] for t,x in self.listTicks(): pos.append(x) c = t.color color.append([c.red(), c.green(), c.blue(), c.alpha()]) return ColorMap(np.array(pos), np.array(color, dtype=np.ubyte)) def updateGradient(self): #private self.gradient = self.getGradient() self.gradRect.setBrush(QtGui.QBrush(self.gradient)) self.sigGradientChanged.emit(self) def setLength(self, newLen): #private (but maybe public) TickSliderItem.setLength(self, newLen) self.backgroundRect.setRect(1, -self.rectSize, newLen, self.rectSize) self.gradRect.setRect(1, -self.rectSize, newLen, self.rectSize) self.updateGradient() def currentColorChanged(self, color): #private if color.isValid() and self.currentTick is not None: self.setTickColor(self.currentTick, color) self.updateGradient() def currentColorRejected(self): #private self.setTickColor(self.currentTick, self.currentTickColor) self.updateGradient() def currentColorAccepted(self): self.sigGradientChangeFinished.emit(self) def tickClicked(self, tick, ev): #private if ev.button() == QtCore.Qt.LeftButton: self.raiseColorDialog(tick) elif ev.button() == QtCore.Qt.RightButton: self.raiseTickContextMenu(tick, ev) def raiseColorDialog(self, tick): if not tick.colorChangeAllowed: return self.currentTick = tick self.currentTickColor = tick.color self.colorDialog.setCurrentColor(tick.color) self.colorDialog.open() def raiseTickContextMenu(self, tick, ev): self.tickMenu = TickMenu(tick, self) self.tickMenu.popup(ev.screenPos().toQPoint()) def tickMoved(self, tick, pos): #private TickSliderItem.tickMoved(self, tick, pos) self.updateGradient() def tickMoveFinished(self, tick): self.sigGradientChangeFinished.emit(self) def getGradient(self): """Return a QLinearGradient object.""" g = QtGui.QLinearGradient(QtCore.QPointF(0,0), QtCore.QPointF(self.length,0)) if self.colorMode == 'rgb': ticks = self.listTicks() g.setStops([(x, QtGui.QColor(t.color)) for t,x in ticks]) elif self.colorMode == 'hsv': ## HSV mode is approximated for display by interpolating 10 points between each stop ticks = self.listTicks() stops = [] stops.append((ticks[0][1], ticks[0][0].color)) for i in range(1,len(ticks)): x1 = ticks[i-1][1] x2 = ticks[i][1] dx = (x2-x1) / 10. for j in range(1,10): x = x1 + dx*j stops.append((x, self.getColor(x))) stops.append((x2, self.getColor(x2))) g.setStops(stops) return g def getColor(self, x, toQColor=True): """ Return a color for a given value. ============== ================================================================== **Arguments:** x Value (position on gradient) of requested color. toQColor If true, returns a QColor object, else returns a (r,g,b,a) tuple. ============== ================================================================== """ ticks = self.listTicks() if x <= ticks[0][1]: c = ticks[0][0].color if toQColor: return QtGui.QColor(c) # always copy colors before handing them out else: return (c.red(), c.green(), c.blue(), c.alpha()) if x >= ticks[-1][1]: c = ticks[-1][0].color if toQColor: return QtGui.QColor(c) # always copy colors before handing them out else: return (c.red(), c.green(), c.blue(), c.alpha()) x2 = ticks[0][1] for i in range(1,len(ticks)): x1 = x2 x2 = ticks[i][1] if x1 <= x and x2 >= x: break dx = (x2-x1) if dx == 0: f = 0. else: f = (x-x1) / dx c1 = ticks[i-1][0].color c2 = ticks[i][0].color if self.colorMode == 'rgb': r = c1.red() * (1.-f) + c2.red() * f g = c1.green() * (1.-f) + c2.green() * f b = c1.blue() * (1.-f) + c2.blue() * f a = c1.alpha() * (1.-f) + c2.alpha() * f if toQColor: return QtGui.QColor(int(r), int(g), int(b), int(a)) else: return (r,g,b,a) elif self.colorMode == 'hsv': h1,s1,v1,_ = c1.getHsv() h2,s2,v2,_ = c2.getHsv() h = h1 * (1.-f) + h2 * f s = s1 * (1.-f) + s2 * f v = v1 * (1.-f) + v2 * f c = QtGui.QColor() c.setHsv(*map(int, [h,s,v])) if toQColor: return c else: return (c.red(), c.green(), c.blue(), c.alpha()) def getLookupTable(self, nPts, alpha=None): """ Return an RGB(A) lookup table (ndarray). ============== ============================================================================ **Arguments:** nPts The number of points in the returned lookup table. alpha True, False, or None - Specifies whether or not alpha values are included in the table.If alpha is None, alpha will be automatically determined. ============== ============================================================================ """ if alpha is None: alpha = self.usesAlpha() if alpha: table = np.empty((nPts,4), dtype=np.ubyte) else: table = np.empty((nPts,3), dtype=np.ubyte) for i in range(nPts): x = float(i)/(nPts-1) color = self.getColor(x, toQColor=False) table[i] = color[:table.shape[1]] return table def usesAlpha(self): """Return True if any ticks have an alpha < 255""" ticks = self.listTicks() for t in ticks: if t[0].color.alpha() < 255: return True return False def isLookupTrivial(self): """Return True if the gradient has exactly two stops in it: black at 0.0 and white at 1.0""" ticks = self.listTicks() if len(ticks) != 2: return False if ticks[0][1] != 0.0 or ticks[1][1] != 1.0: return False c1 = fn.colorTuple(ticks[0][0].color) c2 = fn.colorTuple(ticks[1][0].color) if c1 != (0,0,0,255) or c2 != (255,255,255,255): return False return True def mouseReleaseEvent(self, ev): #private TickSliderItem.mouseReleaseEvent(self, ev) self.updateGradient() def addTick(self, x, color=None, movable=True, finish=True): """ Add a tick to the gradient. Return the tick. ============== ================================================================== **Arguments:** x Position where tick should be added. color Color of added tick. If color is not specified, the color will be the color of the gradient at the specified position. movable Specifies whether the tick is movable with the mouse. ============== ================================================================== """ if color is None: color = self.getColor(x) t = TickSliderItem.addTick(self, x, color=color, movable=movable) t.colorChangeAllowed = True t.removeAllowed = True if finish: self.sigGradientChangeFinished.emit(self) return t def removeTick(self, tick, finish=True): TickSliderItem.removeTick(self, tick) if finish: self.updateGradient() self.sigGradientChangeFinished.emit(self) def saveState(self): """ Return a dictionary with parameters for rebuilding the gradient. Keys will include: - 'mode': hsv or rgb - 'ticks': a list of tuples (pos, (r,g,b,a)) """ ## public ticks = [] for t in self.ticks: c = t.color ticks.append((self.ticks[t], (c.red(), c.green(), c.blue(), c.alpha()))) state = {'mode': self.colorMode, 'ticks': ticks} return state def restoreState(self, state): """ Restore the gradient specified in state. ============== ==================================================================== **Arguments:** state A dictionary with same structure as those returned by :func:`saveState <pyqtgraph.GradientEditorItem.saveState>` Keys must include: - 'mode': hsv or rgb - 'ticks': a list of tuples (pos, (r,g,b,a)) ============== ==================================================================== """ ## public self.setColorMode(state['mode']) for t in list(self.ticks.keys()): self.removeTick(t, finish=False) for t in state['ticks']: c = QtGui.QColor(*t[1]) self.addTick(t[0], c, finish=False) self.updateGradient() self.sigGradientChangeFinished.emit(self) def setColorMap(self, cm): self.setColorMode('rgb') for t in list(self.ticks.keys()): self.removeTick(t, finish=False) colors = cm.getColors(mode='qcolor') for i in range(len(cm.pos)): x = cm.pos[i] c = colors[i] self.addTick(x, c, finish=False) self.updateGradient() self.sigGradientChangeFinished.emit(self) class Tick(QtGui.QGraphicsWidget): ## NOTE: Making this a subclass of GraphicsObject instead results in ## activating this bug: https://bugreports.qt-project.org/browse/PYSIDE-86 ## private class # When making Tick a subclass of QtGui.QGraphicsObject as origin, # ..GraphicsScene.items(self, *args) will get Tick object as a # class of QtGui.QMultimediaWidgets.QGraphicsVideoItem in python2.7-PyQt5(5.4.0) sigMoving = QtCore.Signal(object) sigMoved = QtCore.Signal(object) def __init__(self, view, pos, color, movable=True, scale=10, pen='w'): self.movable = movable self.moving = False self.view = weakref.ref(view) self.scale = scale self.color = color self.pen = fn.mkPen(pen) self.hoverPen = fn.mkPen(255,255,0) self.currentPen = self.pen self.pg = QtGui.QPainterPath(QtCore.QPointF(0,0)) self.pg.lineTo(QtCore.QPointF(-scale/3**0.5, scale)) self.pg.lineTo(QtCore.QPointF(scale/3**0.5, scale)) self.pg.closeSubpath() QtGui.QGraphicsWidget.__init__(self) self.setPos(pos[0], pos[1]) if self.movable: self.setZValue(1) else: self.setZValue(0) def boundingRect(self): return self.pg.boundingRect() def shape(self): return self.pg def paint(self, p, *args): p.setRenderHints(QtGui.QPainter.Antialiasing) p.fillPath(self.pg, fn.mkBrush(self.color)) p.setPen(self.currentPen) p.drawPath(self.pg) def mouseDragEvent(self, ev): if self.movable and ev.button() == QtCore.Qt.LeftButton: if ev.isStart(): self.moving = True self.cursorOffset = self.pos() - self.mapToParent(ev.buttonDownPos()) self.startPosition = self.pos() ev.accept() if not self.moving: return newPos = self.cursorOffset + self.mapToParent(ev.pos()) newPos.setY(self.pos().y()) self.setPos(newPos) self.view().tickMoved(self, newPos) self.sigMoving.emit(self) if ev.isFinish(): self.moving = False self.sigMoved.emit(self) self.view().tickMoveFinished(self) def mouseClickEvent(self, ev): if ev.button() == QtCore.Qt.RightButton and self.moving: ev.accept() self.setPos(self.startPosition) self.view().tickMoved(self, self.startPosition) self.moving = False self.sigMoving.emit(self) self.sigMoved.emit(self) else: self.view().tickClicked(self, ev) ##remove def hoverEvent(self, ev): if (not ev.isExit()) and ev.acceptDrags(QtCore.Qt.LeftButton): ev.acceptClicks(QtCore.Qt.LeftButton) ev.acceptClicks(QtCore.Qt.RightButton) self.currentPen = self.hoverPen else: self.currentPen = self.pen self.update() class TickMenu(QtGui.QMenu): def __init__(self, tick, sliderItem): QtGui.QMenu.__init__(self) self.tick = weakref.ref(tick) self.sliderItem = weakref.ref(sliderItem) self.removeAct = self.addAction("Remove Tick", lambda: self.sliderItem().removeTick(tick)) if (not self.tick().removeAllowed) or len(self.sliderItem().ticks) < 3: self.removeAct.setEnabled(False) positionMenu = self.addMenu("Set Position") w = QtGui.QWidget() l = QtGui.QGridLayout() w.setLayout(l) value = sliderItem.tickValue(tick) self.fracPosSpin = SpinBox() self.fracPosSpin.setOpts(value=value, bounds=(0.0, 1.0), step=0.01, decimals=2) #self.dataPosSpin = SpinBox(value=dataVal) #self.dataPosSpin.setOpts(decimals=3, siPrefix=True) l.addWidget(QtGui.QLabel("Position:"), 0,0) l.addWidget(self.fracPosSpin, 0, 1) #l.addWidget(QtGui.QLabel("Position (data units):"), 1, 0) #l.addWidget(self.dataPosSpin, 1,1) #if self.sliderItem().dataParent is None: # self.dataPosSpin.setEnabled(False) a = QtGui.QWidgetAction(self) a.setDefaultWidget(w) positionMenu.addAction(a) self.fracPosSpin.sigValueChanging.connect(self.fractionalValueChanged) #self.dataPosSpin.valueChanged.connect(self.dataValueChanged) colorAct = self.addAction("Set Color", lambda: self.sliderItem().raiseColorDialog(self.tick())) if not self.tick().colorChangeAllowed: colorAct.setEnabled(False) def fractionalValueChanged(self, x): self.sliderItem().setTickValue(self.tick(), self.fracPosSpin.value()) #if self.sliderItem().dataParent is not None: # self.dataPosSpin.blockSignals(True) # self.dataPosSpin.setValue(self.sliderItem().tickDataValue(self.tick())) # self.dataPosSpin.blockSignals(False) #def dataValueChanged(self, val): # self.sliderItem().setTickValue(self.tick(), val, dataUnits=True) # self.fracPosSpin.blockSignals(True) # self.fracPosSpin.setValue(self.sliderItem().tickValue(self.tick())) # self.fracPosSpin.blockSignals(False)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/LegendItem.py
.py
9,250
255
# -*- coding: utf-8 -*- from .GraphicsWidget import GraphicsWidget from .LabelItem import LabelItem from ..Qt import QtGui, QtCore from .. import functions as fn from ..Point import Point from .ScatterPlotItem import ScatterPlotItem, drawSymbol from .PlotDataItem import PlotDataItem from .GraphicsWidgetAnchor import GraphicsWidgetAnchor __all__ = ['LegendItem'] class LegendItem(GraphicsWidget, GraphicsWidgetAnchor): """ Displays a legend used for describing the contents of a plot. LegendItems are most commonly created by calling PlotItem.addLegend(). Note that this item should not be added directly to a PlotItem. Instead, Make it a direct descendant of the PlotItem:: legend.setParentItem(plotItem) """ def __init__(self, size=None, offset=None, horSpacing=25, verSpacing=0, pen=None, brush=None, labelTextColor=None, **kwargs): """ ============== =============================================================== **Arguments:** size Specifies the fixed size (width, height) of the legend. If this argument is omitted, the legend will automatically resize to fit its contents. offset Specifies the offset position relative to the legend's parent. Positive values offset from the left or top; negative values offset from the right or bottom. If offset is None, the legend must be anchored manually by calling anchor() or positioned by calling setPos(). horSpacing Specifies the spacing between the line symbol and the label. verSpacing Specifies the spacing between individual entries of the legend vertically. (Can also be negative to have them really close) pen Pen to use when drawing legend border. Any single argument accepted by :func:`mkPen <pyqtgraph.mkPen>` is allowed. brush QBrush to use as legend background filling. Any single argument accepted by :func:`mkBrush <pyqtgraph.mkBrush>` is allowed. labelTextColor Pen to use when drawing legend text. Any single argument accepted by :func:`mkPen <pyqtgraph.mkPen>` is allowed. ============== =============================================================== """ GraphicsWidget.__init__(self) GraphicsWidgetAnchor.__init__(self) self.setFlag(self.ItemIgnoresTransformations) self.layout = QtGui.QGraphicsGridLayout() self.layout.setVerticalSpacing(verSpacing) self.layout.setHorizontalSpacing(horSpacing) self.setLayout(self.layout) self.items = [] self.size = size if size is not None: self.setGeometry(QtCore.QRectF(0, 0, self.size[0], self.size[1])) self.opts = { 'pen': fn.mkPen(pen), 'brush': fn.mkBrush(brush), 'labelTextColor': labelTextColor, 'offset': offset, } self.opts.update(kwargs) def offset(self): return self.opts['offset'] def setOffset(self, offset): self.opts['offset'] = offset offset = Point(self.opts['offset']) anchorx = 1 if offset[0] <= 0 else 0 anchory = 1 if offset[1] <= 0 else 0 anchor = (anchorx, anchory) self.anchor(itemPos=anchor, parentPos=anchor, offset=offset) def pen(self): return self.opts['pen'] def setPen(self, *args, **kargs): """ Sets the pen used to draw lines between points. *pen* can be a QPen or any argument accepted by :func:`pyqtgraph.mkPen() <pyqtgraph.mkPen>` """ pen = fn.mkPen(*args, **kargs) self.opts['pen'] = pen self.update() def brush(self): return self.opts['brush'] def setBrush(self, *args, **kargs): brush = fn.mkBrush(*args, **kargs) if self.opts['brush'] == brush: return self.opts['brush'] = brush self.update() def labelTextColor(self): return self.opts['labelTextColor'] def setLabelTextColor(self, *args, **kargs): """ Sets the color of the label text. *pen* can be a QPen or any argument accepted by :func:`pyqtgraph.mkColor() <pyqtgraph.mkPen>` """ self.opts['labelTextColor'] = fn.mkColor(*args, **kargs) for sample, label in self.items: label.setAttr('color', self.opts['labelTextColor']) self.update() def setParentItem(self, p): ret = GraphicsWidget.setParentItem(self, p) if self.opts['offset'] is not None: offset = Point(self.opts['offset']) anchorx = 1 if offset[0] <= 0 else 0 anchory = 1 if offset[1] <= 0 else 0 anchor = (anchorx, anchory) self.anchor(itemPos=anchor, parentPos=anchor, offset=offset) return ret def addItem(self, item, name): """ Add a new entry to the legend. ============== ======================================================== **Arguments:** item A PlotDataItem from which the line and point style of the item will be determined or an instance of ItemSample (or a subclass), allowing the item display to be customized. title The title to display for this item. Simple HTML allowed. ============== ======================================================== """ label = LabelItem(name, color=self.opts['labelTextColor'], justify='left') if isinstance(item, ItemSample): sample = item else: sample = ItemSample(item) row = self.layout.rowCount() self.items.append((sample, label)) self.layout.addItem(sample, row, 0) self.layout.addItem(label, row, 1) self.updateSize() def removeItem(self, item): """ Removes one item from the legend. ============== ======================================================== **Arguments:** item The item to remove or its name. ============== ======================================================== """ for sample, label in self.items: if sample.item is item or label.text == item: self.items.remove((sample, label)) # remove from itemlist self.layout.removeItem(sample) # remove from layout sample.close() # remove from drawing self.layout.removeItem(label) label.close() self.updateSize() # redraq box return # return after first match def clear(self): """Removes all items from legend.""" for sample, label in self.items: self.layout.removeItem(sample) self.layout.removeItem(label) self.items = [] self.updateSize() def clear(self): """ Removes all items from the legend. Useful for reusing and dynamically updating charts and their legends. """ while self.items != []: self.removeItem(self.items[0][1].text) def updateSize(self): if self.size is not None: return self.setGeometry(0, 0, 0, 0) def boundingRect(self): return QtCore.QRectF(0, 0, self.width(), self.height()) def paint(self, p, *args): p.setPen(self.opts['pen']) p.setBrush(self.opts['brush']) p.drawRect(self.boundingRect()) def hoverEvent(self, ev): ev.acceptDrags(QtCore.Qt.LeftButton) def mouseDragEvent(self, ev): if ev.button() == QtCore.Qt.LeftButton: ev.accept() dpos = ev.pos() - ev.lastPos() self.autoAnchor(self.pos() + dpos) class ItemSample(GraphicsWidget): """ Class responsible for drawing a single item in a LegendItem (sans label). This may be subclassed to draw custom graphics in a Legend. """ ## Todo: make this more generic; let each item decide how it should be represented. def __init__(self, item): GraphicsWidget.__init__(self) self.item = item def boundingRect(self): return QtCore.QRectF(0, 0, 20, 20) def paint(self, p, *args): opts = self.item.opts if opts['antialias']: p.setRenderHint(p.Antialiasing) if not isinstance(self.item, ScatterPlotItem): p.setPen(fn.mkPen(opts['pen'])) p.drawLine(0, 11, 20, 11) symbol = opts.get('symbol', None) if symbol is not None: if isinstance(self.item, PlotDataItem): opts = self.item.scatter.opts pen = fn.mkPen(opts['pen']) brush = fn.mkBrush(opts['brush']) size = opts['size'] p.translate(10, 10) path = drawSymbol(p, symbol, size, pen, brush)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/ArrowItem.py
.py
4,687
130
from ..Qt import QtGui, QtCore from .. import functions as fn import numpy as np __all__ = ['ArrowItem'] class ArrowItem(QtGui.QGraphicsPathItem): """ For displaying scale-invariant arrows. For arrows pointing to a location on a curve, see CurveArrow """ def __init__(self, **opts): """ Arrows can be initialized with any keyword arguments accepted by the setStyle() method. """ self.opts = {} QtGui.QGraphicsPathItem.__init__(self, opts.get('parent', None)) if 'size' in opts: opts['headLen'] = opts['size'] if 'width' in opts: opts['headWidth'] = opts['width'] defaultOpts = { 'pxMode': True, 'angle': -150, ## If the angle is 0, the arrow points left 'pos': (0,0), 'headLen': 20, 'tipAngle': 25, 'baseAngle': 0, 'tailLen': None, 'tailWidth': 3, 'pen': (200,200,200), 'brush': (50,50,200), } defaultOpts.update(opts) self.setStyle(**defaultOpts) self.moveBy(*self.opts['pos']) def setStyle(self, **opts): """ Changes the appearance of the arrow. All arguments are optional: ====================== ================================================= **Keyword Arguments:** angle Orientation of the arrow in degrees. Default is 0; arrow pointing to the left. headLen Length of the arrow head, from tip to base. default=20 headWidth Width of the arrow head at its base. tipAngle Angle of the tip of the arrow in degrees. Smaller values make a 'sharper' arrow. If tipAngle is specified, ot overrides headWidth. default=25 baseAngle Angle of the base of the arrow head. Default is 0, which means that the base of the arrow head is perpendicular to the arrow tail. tailLen Length of the arrow tail, measured from the base of the arrow head to the end of the tail. If this value is None, no tail will be drawn. default=None tailWidth Width of the tail. default=3 pen The pen used to draw the outline of the arrow. brush The brush used to fill the arrow. ====================== ================================================= """ self.opts.update(opts) opt = dict([(k,self.opts[k]) for k in ['headLen', 'tipAngle', 'baseAngle', 'tailLen', 'tailWidth']]) tr = QtGui.QTransform() tr.rotate(self.opts['angle']) self.path = tr.map(fn.makeArrowPath(**opt)) self.setPath(self.path) self.setPen(fn.mkPen(self.opts['pen'])) self.setBrush(fn.mkBrush(self.opts['brush'])) if self.opts['pxMode']: self.setFlags(self.flags() | self.ItemIgnoresTransformations) else: self.setFlags(self.flags() & ~self.ItemIgnoresTransformations) def paint(self, p, *args): p.setRenderHint(QtGui.QPainter.Antialiasing) QtGui.QGraphicsPathItem.paint(self, p, *args) #p.setPen(fn.mkPen('r')) #p.setBrush(fn.mkBrush(None)) #p.drawRect(self.boundingRect()) def shape(self): #if not self.opts['pxMode']: #return QtGui.QGraphicsPathItem.shape(self) return self.path ## dataBounds and pixelPadding methods are provided to ensure ViewBox can ## properly auto-range def dataBounds(self, ax, frac, orthoRange=None): pw = 0 pen = self.pen() if not pen.isCosmetic(): pw = pen.width() * 0.7072 if self.opts['pxMode']: return [0,0] else: br = self.boundingRect() if ax == 0: return [br.left()-pw, br.right()+pw] else: return [br.top()-pw, br.bottom()+pw] def pixelPadding(self): pad = 0 if self.opts['pxMode']: br = self.boundingRect() pad += (br.width()**2 + br.height()**2) ** 0.5 pen = self.pen() if pen.isCosmetic(): pad += max(1, pen.width()) * 0.7072 return pad
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/ROI.py
.py
93,116
2,274
# -*- coding: utf-8 -*- """ ROI.py - Interactive graphics items for GraphicsView (ROI widgets) Copyright 2010 Luke Campagnola Distributed under MIT/X11 license. See license.txt for more information. Implements a series of graphics items which display movable/scalable/rotatable shapes for use as region-of-interest markers. ROI class automatically handles extraction of array data from ImageItems. The ROI class is meant to serve as the base for more specific types; see several examples of how to build an ROI at the bottom of the file. """ from ..Qt import QtCore, QtGui import numpy as np #from numpy.linalg import norm from ..Point import * from ..SRTTransform import SRTTransform from math import cos, sin from .. import functions as fn from .GraphicsObject import GraphicsObject from .UIGraphicsItem import UIGraphicsItem from .. import getConfigOption __all__ = [ 'ROI', 'TestROI', 'RectROI', 'EllipseROI', 'CircleROI', 'PolygonROI', 'LineROI', 'MultiLineROI', 'MultiRectROI', 'LineSegmentROI', 'PolyLineROI', 'CrosshairROI', ] def rectStr(r): return "[%f, %f] + [%f, %f]" % (r.x(), r.y(), r.width(), r.height()) class ROI(GraphicsObject): """ Generic region-of-interest widget. Can be used for implementing many types of selection box with rotate/translate/scale handles. ROIs can be customized to have a variety of shapes (by subclassing or using any of the built-in subclasses) and any combination of draggable handles that allow the user to manipulate the ROI. Default mouse interaction: * Left drag moves the ROI * Left drag + Ctrl moves the ROI with position snapping * Left drag + Alt rotates the ROI * Left drag + Alt + Ctrl rotates the ROI with angle snapping * Left drag + Shift scales the ROI * Left drag + Shift + Ctrl scales the ROI with size snapping In addition to the above interaction modes, it is possible to attach any number of handles to the ROI that can be dragged to change the ROI in various ways (see the ROI.add____Handle methods). ================ =========================================================== **Arguments** pos (length-2 sequence) Indicates the position of the ROI's origin. For most ROIs, this is the lower-left corner of its bounding rectangle. size (length-2 sequence) Indicates the width and height of the ROI. angle (float) The rotation of the ROI in degrees. Default is 0. invertible (bool) If True, the user may resize the ROI to have negative width or height (assuming the ROI has scale handles). Default is False. maxBounds (QRect, QRectF, or None) Specifies boundaries that the ROI cannot be dragged outside of by the user. Default is None. snapSize (float) The spacing of snap positions used when *scaleSnap* or *translateSnap* are enabled. Default is 1.0. scaleSnap (bool) If True, the width and height of the ROI are forced to be integer multiples of *snapSize* when being resized by the user. Default is False. translateSnap (bool) If True, the x and y positions of the ROI are forced to be integer multiples of *snapSize* when being resized by the user. Default is False. rotateSnap (bool) If True, the ROI angle is forced to a multiple of the ROI's snap angle (default is 15 degrees) when rotated by the user. Default is False. parent (QGraphicsItem) The graphics item parent of this ROI. It is generally not necessary to specify the parent. pen (QPen or argument to pg.mkPen) The pen to use when drawing the shape of the ROI. movable (bool) If True, the ROI can be moved by dragging anywhere inside the ROI. Default is True. rotatable (bool) If True, the ROI can be rotated by mouse drag + ALT resizable (bool) If True, the ROI can be resized by mouse drag + SHIFT removable (bool) If True, the ROI will be given a context menu with an option to remove the ROI. The ROI emits sigRemoveRequested when this menu action is selected. Default is False. ================ =========================================================== ======================= ==================================================== **Signals** sigRegionChangeFinished Emitted when the user stops dragging the ROI (or one of its handles) or if the ROI is changed programatically. sigRegionChangeStarted Emitted when the user starts dragging the ROI (or one of its handles). sigRegionChanged Emitted any time the position of the ROI changes, including while it is being dragged by the user. sigHoverEvent Emitted when the mouse hovers over the ROI. sigClicked Emitted when the user clicks on the ROI. Note that clicking is disabled by default to prevent stealing clicks from objects behind the ROI. To enable clicking, call roi.setAcceptedMouseButtons(QtCore.Qt.LeftButton). See QtGui.QGraphicsItem documentation for more details. sigRemoveRequested Emitted when the user selects 'remove' from the ROI's context menu (if available). ======================= ==================================================== """ sigRegionChangeFinished = QtCore.Signal(object) sigRegionChangeStarted = QtCore.Signal(object) sigRegionChanged = QtCore.Signal(object) sigHoverEvent = QtCore.Signal(object) sigClicked = QtCore.Signal(object, object) sigRemoveRequested = QtCore.Signal(object) def __init__(self, pos, size=Point(1, 1), angle=0.0, invertible=False, maxBounds=None, snapSize=1.0, scaleSnap=False, translateSnap=False, rotateSnap=False, parent=None, pen=None, movable=True, rotatable=True, resizable=True, removable=False): GraphicsObject.__init__(self, parent) self.setAcceptedMouseButtons(QtCore.Qt.NoButton) pos = Point(pos) size = Point(size) self.aspectLocked = False self.translatable = movable self.rotatable = rotatable self.resizable = resizable self.removable = removable self.menu = None self.freeHandleMoved = False ## keep track of whether free handles have moved since last change signal was emitted. self.mouseHovering = False if pen is None: pen = (255, 255, 255) self.setPen(pen) self.handlePen = QtGui.QPen(QtGui.QColor(150, 255, 255)) self.handles = [] self.state = {'pos': Point(0,0), 'size': Point(1,1), 'angle': 0} ## angle is in degrees for ease of Qt integration self.lastState = None self.setPos(pos) self.setAngle(angle) self.setSize(size) self.setZValue(10) self.isMoving = False self.handleSize = 5 self.invertible = invertible self.maxBounds = maxBounds self.snapSize = snapSize self.translateSnap = translateSnap self.rotateSnap = rotateSnap self.rotateSnapAngle = 15.0 self.scaleSnap = scaleSnap self.scaleSnapSize = snapSize # Implement mouse handling in a separate class to allow easier customization self.mouseDragHandler = MouseDragHandler(self) def getState(self): return self.stateCopy() def stateCopy(self): sc = {} sc['pos'] = Point(self.state['pos']) sc['size'] = Point(self.state['size']) sc['angle'] = self.state['angle'] return sc def saveState(self): """Return the state of the widget in a format suitable for storing to disk. (Points are converted to tuple) Combined with setState(), this allows ROIs to be easily saved and restored.""" state = {} state['pos'] = tuple(self.state['pos']) state['size'] = tuple(self.state['size']) state['angle'] = self.state['angle'] return state def setState(self, state, update=True): """ Set the state of the ROI from a structure generated by saveState() or getState(). """ self.setPos(state['pos'], update=False) self.setSize(state['size'], update=False) self.setAngle(state['angle'], update=update) def setZValue(self, z): QtGui.QGraphicsItem.setZValue(self, z) for h in self.handles: h['item'].setZValue(z+1) def parentBounds(self): """ Return the bounding rectangle of this ROI in the coordinate system of its parent. """ return self.mapToParent(self.boundingRect()).boundingRect() def setPen(self, *args, **kwargs): """ Set the pen to use when drawing the ROI shape. For arguments, see :func:`mkPen <pyqtgraph.mkPen>`. """ self.pen = fn.mkPen(*args, **kwargs) self.currentPen = self.pen self.update() def size(self): """Return the size (w,h) of the ROI.""" return self.getState()['size'] def pos(self): """Return the position (x,y) of the ROI's origin. For most ROIs, this will be the lower-left corner.""" return self.getState()['pos'] def angle(self): """Return the angle of the ROI in degrees.""" return self.getState()['angle'] def setPos(self, pos, y=None, update=True, finish=True): """Set the position of the ROI (in the parent's coordinate system). Accepts either separate (x, y) arguments or a single :class:`Point` or ``QPointF`` argument. By default, this method causes both ``sigRegionChanged`` and ``sigRegionChangeFinished`` to be emitted. If *finish* is False, then ``sigRegionChangeFinished`` will not be emitted. You can then use stateChangeFinished() to cause the signal to be emitted after a series of state changes. If *update* is False, the state change will be remembered but not processed and no signals will be emitted. You can then use stateChanged() to complete the state change. This allows multiple change functions to be called sequentially while minimizing processing overhead and repeated signals. Setting ``update=False`` also forces ``finish=False``. """ if update not in (True, False): raise TypeError("update argument must be bool") if y is None: pos = Point(pos) else: # avoid ambiguity where update is provided as a positional argument if isinstance(y, bool): raise TypeError("Positional arguments to setPos() must be numerical.") pos = Point(pos, y) self.state['pos'] = pos QtGui.QGraphicsItem.setPos(self, pos) if update: self.stateChanged(finish=finish) def setSize(self, size, center=None, centerLocal=None, snap=False, update=True, finish=True): """ Set the ROI's size. =============== ========================================================================== **Arguments** size (Point | QPointF | sequence) The final size of the ROI center (None | Point) Optional center point around which the ROI is scaled, expressed as [0-1, 0-1] over the size of the ROI. centerLocal (None | Point) Same as *center*, but the position is expressed in the local coordinate system of the ROI snap (bool) If True, the final size is snapped to the nearest increment (see ROI.scaleSnapSize) update (bool) See setPos() finish (bool) See setPos() =============== ========================================================================== """ if update not in (True, False): raise TypeError("update argument must be bool") size = Point(size) if snap: size[0] = round(size[0] / self.scaleSnapSize) * self.scaleSnapSize size[1] = round(size[1] / self.scaleSnapSize) * self.scaleSnapSize if centerLocal is not None: oldSize = Point(self.state['size']) oldSize[0] = 1 if oldSize[0] == 0 else oldSize[0] oldSize[1] = 1 if oldSize[1] == 0 else oldSize[1] center = Point(centerLocal) / oldSize if center is not None: center = Point(center) c = self.mapToParent(Point(center) * self.state['size']) c1 = self.mapToParent(Point(center) * size) newPos = self.state['pos'] + c - c1 self.setPos(newPos, update=False, finish=False) self.prepareGeometryChange() self.state['size'] = size if update: self.stateChanged(finish=finish) def setAngle(self, angle, center=None, centerLocal=None, snap=False, update=True, finish=True): """ Set the ROI's rotation angle. =============== ========================================================================== **Arguments** angle (float) The final ROI angle in degrees center (None | Point) Optional center point around which the ROI is rotated, expressed as [0-1, 0-1] over the size of the ROI. centerLocal (None | Point) Same as *center*, but the position is expressed in the local coordinate system of the ROI snap (bool) If True, the final ROI angle is snapped to the nearest increment (default is 15 degrees; see ROI.rotateSnapAngle) update (bool) See setPos() finish (bool) See setPos() =============== ========================================================================== """ if update not in (True, False): raise TypeError("update argument must be bool") if snap is True: angle = round(angle / self.rotateSnapAngle) * self.rotateSnapAngle self.state['angle'] = angle tr = QtGui.QTransform() # note: only rotation is contained in the transform tr.rotate(angle) if center is not None: centerLocal = Point(center) * self.state['size'] if centerLocal is not None: centerLocal = Point(centerLocal) # rotate to new angle, keeping a specific point anchored as the center of rotation cc = self.mapToParent(centerLocal) - (tr.map(centerLocal) + self.state['pos']) self.translate(cc, update=False) self.setTransform(tr) if update: self.stateChanged(finish=finish) def scale(self, s, center=None, centerLocal=None, snap=False, update=True, finish=True): """ Resize the ROI by scaling relative to *center*. See setPos() for an explanation of the *update* and *finish* arguments. """ newSize = self.state['size'] * s self.setSize(newSize, center=center, centerLocal=centerLocal, snap=snap, update=update, finish=finish) def translate(self, *args, **kargs): """ Move the ROI to a new position. Accepts either (x, y, snap) or ([x,y], snap) as arguments If the ROI is bounded and the move would exceed boundaries, then the ROI is moved to the nearest acceptable position instead. *snap* can be: =============== ========================================================================== None (default) use self.translateSnap and self.snapSize to determine whether/how to snap False do not snap Point(w,h) snap to rectangular grid with spacing (w,h) True snap using self.snapSize (and ignoring self.translateSnap) =============== ========================================================================== Also accepts *update* and *finish* arguments (see setPos() for a description of these). """ if len(args) == 1: pt = args[0] else: pt = args newState = self.stateCopy() newState['pos'] = newState['pos'] + pt snap = kargs.get('snap', None) if snap is None: snap = self.translateSnap if snap is not False: newState['pos'] = self.getSnapPosition(newState['pos'], snap=snap) if self.maxBounds is not None: r = self.stateRect(newState) d = Point(0,0) if self.maxBounds.left() > r.left(): d[0] = self.maxBounds.left() - r.left() elif self.maxBounds.right() < r.right(): d[0] = self.maxBounds.right() - r.right() if self.maxBounds.top() > r.top(): d[1] = self.maxBounds.top() - r.top() elif self.maxBounds.bottom() < r.bottom(): d[1] = self.maxBounds.bottom() - r.bottom() newState['pos'] += d update = kargs.get('update', True) finish = kargs.get('finish', True) self.setPos(newState['pos'], update=update, finish=finish) def rotate(self, angle, center=None, snap=False, update=True, finish=True): """ Rotate the ROI by *angle* degrees. =============== ========================================================================== **Arguments** angle (float) The angle in degrees to rotate center (None | Point) Optional center point around which the ROI is rotated, in the local coordinate system of the ROI snap (bool) If True, the final ROI angle is snapped to the nearest increment (default is 15 degrees; see ROI.rotateSnapAngle) update (bool) See setPos() finish (bool) See setPos() =============== ========================================================================== """ self.setAngle(self.angle()+angle, center=center, snap=snap, update=update, finish=finish) def handleMoveStarted(self): self.preMoveState = self.getState() self.sigRegionChangeStarted.emit(self) def addTranslateHandle(self, pos, axes=None, item=None, name=None, index=None): """ Add a new translation handle to the ROI. Dragging the handle will move the entire ROI without changing its angle or shape. Note that, by default, ROIs may be moved by dragging anywhere inside the ROI. However, for larger ROIs it may be desirable to disable this and instead provide one or more translation handles. =================== ==================================================== **Arguments** pos (length-2 sequence) The position of the handle relative to the shape of the ROI. A value of (0,0) indicates the origin, whereas (1, 1) indicates the upper-right corner, regardless of the ROI's size. item The Handle instance to add. If None, a new handle will be created. name The name of this handle (optional). Handles are identified by name when calling getLocalHandlePositions and getSceneHandlePositions. =================== ==================================================== """ pos = Point(pos) return self.addHandle({'name': name, 'type': 't', 'pos': pos, 'item': item}, index=index) def addFreeHandle(self, pos=None, axes=None, item=None, name=None, index=None): """ Add a new free handle to the ROI. Dragging free handles has no effect on the position or shape of the ROI. =================== ==================================================== **Arguments** pos (length-2 sequence) The position of the handle relative to the shape of the ROI. A value of (0,0) indicates the origin, whereas (1, 1) indicates the upper-right corner, regardless of the ROI's size. item The Handle instance to add. If None, a new handle will be created. name The name of this handle (optional). Handles are identified by name when calling getLocalHandlePositions and getSceneHandlePositions. =================== ==================================================== """ if pos is not None: pos = Point(pos) return self.addHandle({'name': name, 'type': 'f', 'pos': pos, 'item': item}, index=index) def addScaleHandle(self, pos, center, axes=None, item=None, name=None, lockAspect=False, index=None): """ Add a new scale handle to the ROI. Dragging a scale handle allows the user to change the height and/or width of the ROI. =================== ==================================================== **Arguments** pos (length-2 sequence) The position of the handle relative to the shape of the ROI. A value of (0,0) indicates the origin, whereas (1, 1) indicates the upper-right corner, regardless of the ROI's size. center (length-2 sequence) The center point around which scaling takes place. If the center point has the same x or y value as the handle position, then scaling will be disabled for that axis. item The Handle instance to add. If None, a new handle will be created. name The name of this handle (optional). Handles are identified by name when calling getLocalHandlePositions and getSceneHandlePositions. =================== ==================================================== """ pos = Point(pos) center = Point(center) info = {'name': name, 'type': 's', 'center': center, 'pos': pos, 'item': item, 'lockAspect': lockAspect} if pos.x() == center.x(): info['xoff'] = True if pos.y() == center.y(): info['yoff'] = True return self.addHandle(info, index=index) def addRotateHandle(self, pos, center, item=None, name=None, index=None): """ Add a new rotation handle to the ROI. Dragging a rotation handle allows the user to change the angle of the ROI. =================== ==================================================== **Arguments** pos (length-2 sequence) The position of the handle relative to the shape of the ROI. A value of (0,0) indicates the origin, whereas (1, 1) indicates the upper-right corner, regardless of the ROI's size. center (length-2 sequence) The center point around which rotation takes place. item The Handle instance to add. If None, a new handle will be created. name The name of this handle (optional). Handles are identified by name when calling getLocalHandlePositions and getSceneHandlePositions. =================== ==================================================== """ pos = Point(pos) center = Point(center) return self.addHandle({'name': name, 'type': 'r', 'center': center, 'pos': pos, 'item': item}, index=index) def addScaleRotateHandle(self, pos, center, item=None, name=None, index=None): """ Add a new scale+rotation handle to the ROI. When dragging a handle of this type, the user can simultaneously rotate the ROI around an arbitrary center point as well as scale the ROI by dragging the handle toward or away from the center point. =================== ==================================================== **Arguments** pos (length-2 sequence) The position of the handle relative to the shape of the ROI. A value of (0,0) indicates the origin, whereas (1, 1) indicates the upper-right corner, regardless of the ROI's size. center (length-2 sequence) The center point around which scaling and rotation take place. item The Handle instance to add. If None, a new handle will be created. name The name of this handle (optional). Handles are identified by name when calling getLocalHandlePositions and getSceneHandlePositions. =================== ==================================================== """ pos = Point(pos) center = Point(center) if pos[0] != center[0] and pos[1] != center[1]: raise Exception("Scale/rotate handles must have either the same x or y coordinate as their center point.") return self.addHandle({'name': name, 'type': 'sr', 'center': center, 'pos': pos, 'item': item}, index=index) def addRotateFreeHandle(self, pos, center, axes=None, item=None, name=None, index=None): """ Add a new rotation+free handle to the ROI. When dragging a handle of this type, the user can rotate the ROI around an arbitrary center point, while moving toward or away from the center point has no effect on the shape of the ROI. =================== ==================================================== **Arguments** pos (length-2 sequence) The position of the handle relative to the shape of the ROI. A value of (0,0) indicates the origin, whereas (1, 1) indicates the upper-right corner, regardless of the ROI's size. center (length-2 sequence) The center point around which rotation takes place. item The Handle instance to add. If None, a new handle will be created. name The name of this handle (optional). Handles are identified by name when calling getLocalHandlePositions and getSceneHandlePositions. =================== ==================================================== """ pos = Point(pos) center = Point(center) return self.addHandle({'name': name, 'type': 'rf', 'center': center, 'pos': pos, 'item': item}, index=index) def addHandle(self, info, index=None): ## If a Handle was not supplied, create it now if 'item' not in info or info['item'] is None: h = Handle(self.handleSize, typ=info['type'], pen=self.handlePen, parent=self) h.setPos(info['pos'] * self.state['size']) info['item'] = h else: h = info['item'] if info['pos'] is None: info['pos'] = h.pos() ## connect the handle to this ROI #iid = len(self.handles) h.connectROI(self) if index is None: self.handles.append(info) else: self.handles.insert(index, info) h.setZValue(self.zValue()+1) self.stateChanged() return h def indexOfHandle(self, handle): """ Return the index of *handle* in the list of this ROI's handles. """ if isinstance(handle, Handle): index = [i for i, info in enumerate(self.handles) if info['item'] is handle] if len(index) == 0: raise Exception("Cannot return handle index; not attached to this ROI") return index[0] else: return handle def removeHandle(self, handle): """Remove a handle from this ROI. Argument may be either a Handle instance or the integer index of the handle.""" index = self.indexOfHandle(handle) handle = self.handles[index]['item'] self.handles.pop(index) handle.disconnectROI(self) if len(handle.rois) == 0: self.scene().removeItem(handle) self.stateChanged() def replaceHandle(self, oldHandle, newHandle): """Replace one handle in the ROI for another. This is useful when connecting multiple ROIs together. *oldHandle* may be a Handle instance or the index of a handle to be replaced.""" index = self.indexOfHandle(oldHandle) info = self.handles[index] self.removeHandle(index) info['item'] = newHandle info['pos'] = newHandle.pos() self.addHandle(info, index=index) def checkRemoveHandle(self, handle): ## This is used when displaying a Handle's context menu to determine ## whether removing is allowed. ## Subclasses may wish to override this to disable the menu entry. ## Note: by default, handles are not user-removable even if this method returns True. return True def getLocalHandlePositions(self, index=None): """Returns the position of handles in the ROI's coordinate system. The format returned is a list of (name, pos) tuples. """ if index == None: positions = [] for h in self.handles: positions.append((h['name'], h['pos'])) return positions else: return (self.handles[index]['name'], self.handles[index]['pos']) def getSceneHandlePositions(self, index=None): """Returns the position of handles in the scene coordinate system. The format returned is a list of (name, pos) tuples. """ if index == None: positions = [] for h in self.handles: positions.append((h['name'], h['item'].scenePos())) return positions else: return (self.handles[index]['name'], self.handles[index]['item'].scenePos()) def getHandles(self): """ Return a list of this ROI's Handles. """ return [h['item'] for h in self.handles] def mapSceneToParent(self, pt): return self.mapToParent(self.mapFromScene(pt)) def setSelected(self, s): QtGui.QGraphicsItem.setSelected(self, s) #print "select", self, s if s: for h in self.handles: h['item'].show() else: for h in self.handles: h['item'].hide() def hoverEvent(self, ev): hover = False if not ev.isExit(): if self.translatable and ev.acceptDrags(QtCore.Qt.LeftButton): hover=True for btn in [QtCore.Qt.LeftButton, QtCore.Qt.RightButton, QtCore.Qt.MidButton]: if int(self.acceptedMouseButtons() & btn) > 0 and ev.acceptClicks(btn): hover=True if self.contextMenuEnabled(): ev.acceptClicks(QtCore.Qt.RightButton) if hover: self.setMouseHover(True) ev.acceptClicks(QtCore.Qt.LeftButton) ## If the ROI is hilighted, we should accept all clicks to avoid confusion. ev.acceptClicks(QtCore.Qt.RightButton) ev.acceptClicks(QtCore.Qt.MidButton) self.sigHoverEvent.emit(self) else: self.setMouseHover(False) def setMouseHover(self, hover): ## Inform the ROI that the mouse is(not) hovering over it if self.mouseHovering == hover: return self.mouseHovering = hover self._updateHoverColor() def _updateHoverColor(self): pen = self._makePen() if self.currentPen != pen: self.currentPen = pen self.update() def _makePen(self): # Generate the pen color for this ROI based on its current state. if self.mouseHovering: return fn.mkPen(255, 255, 0) else: return self.pen def contextMenuEnabled(self): return self.removable def raiseContextMenu(self, ev): if not self.contextMenuEnabled(): return menu = self.getMenu() menu = self.scene().addParentContextMenus(self, menu, ev) pos = ev.screenPos() menu.popup(QtCore.QPoint(pos.x(), pos.y())) def getMenu(self): if self.menu is None: self.menu = QtGui.QMenu() self.menu.setTitle("ROI") remAct = QtGui.QAction("Remove ROI", self.menu) remAct.triggered.connect(self.removeClicked) self.menu.addAction(remAct) self.menu.remAct = remAct # ROI menu may be requested when showing the handle context menu, so # return the menu but disable it if the ROI isn't removable self.menu.setEnabled(self.contextMenuEnabled()) return self.menu def removeClicked(self): ## Send remove event only after we have exited the menu event handler QtCore.QTimer.singleShot(0, lambda: self.sigRemoveRequested.emit(self)) def mouseDragEvent(self, ev): self.mouseDragHandler.mouseDragEvent(ev) def mouseClickEvent(self, ev): if ev.button() == QtCore.Qt.RightButton and self.isMoving: ev.accept() self.cancelMove() if ev.button() == QtCore.Qt.RightButton and self.contextMenuEnabled(): self.raiseContextMenu(ev) ev.accept() elif int(ev.button() & self.acceptedMouseButtons()) > 0: ev.accept() self.sigClicked.emit(self, ev) else: ev.ignore() def _moveStarted(self): self.isMoving = True self.preMoveState = self.getState() self.sigRegionChangeStarted.emit(self) def _moveFinished(self): if self.isMoving: self.stateChangeFinished() self.isMoving = False def cancelMove(self): self.isMoving = False self.setState(self.preMoveState) def checkPointMove(self, handle, pos, modifiers): """When handles move, they must ask the ROI if the move is acceptable. By default, this always returns True. Subclasses may wish override. """ return True def movePoint(self, handle, pos, modifiers=QtCore.Qt.KeyboardModifier(), finish=True, coords='parent'): ## called by Handles when they are moved. ## pos is the new position of the handle in scene coords, as requested by the handle. newState = self.stateCopy() index = self.indexOfHandle(handle) h = self.handles[index] p0 = self.mapToParent(h['pos'] * self.state['size']) p1 = Point(pos) if coords == 'parent': pass elif coords == 'scene': p1 = self.mapSceneToParent(p1) else: raise Exception("New point location must be given in either 'parent' or 'scene' coordinates.") ## Handles with a 'center' need to know their local position relative to the center point (lp0, lp1) if 'center' in h: c = h['center'] cs = c * self.state['size'] lp0 = self.mapFromParent(p0) - cs lp1 = self.mapFromParent(p1) - cs if h['type'] == 't': snap = True if (modifiers & QtCore.Qt.ControlModifier) else None self.translate(p1-p0, snap=snap, update=False) elif h['type'] == 'f': newPos = self.mapFromParent(p1) h['item'].setPos(newPos) h['pos'] = newPos self.freeHandleMoved = True elif h['type'] == 's': ## If a handle and its center have the same x or y value, we can't scale across that axis. if h['center'][0] == h['pos'][0]: lp1[0] = 0 if h['center'][1] == h['pos'][1]: lp1[1] = 0 ## snap if self.scaleSnap or (modifiers & QtCore.Qt.ControlModifier): lp1[0] = round(lp1[0] / self.scaleSnapSize) * self.scaleSnapSize lp1[1] = round(lp1[1] / self.scaleSnapSize) * self.scaleSnapSize ## preserve aspect ratio (this can override snapping) if h['lockAspect'] or (modifiers & QtCore.Qt.AltModifier): #arv = Point(self.preMoveState['size']) - lp1 = lp1.proj(lp0) ## determine scale factors and new size of ROI hs = h['pos'] - c if hs[0] == 0: hs[0] = 1 if hs[1] == 0: hs[1] = 1 newSize = lp1 / hs ## Perform some corrections and limit checks if newSize[0] == 0: newSize[0] = newState['size'][0] if newSize[1] == 0: newSize[1] = newState['size'][1] if not self.invertible: if newSize[0] < 0: newSize[0] = newState['size'][0] if newSize[1] < 0: newSize[1] = newState['size'][1] if self.aspectLocked: newSize[0] = newSize[1] ## Move ROI so the center point occupies the same scene location after the scale s0 = c * self.state['size'] s1 = c * newSize cc = self.mapToParent(s0 - s1) - self.mapToParent(Point(0, 0)) ## update state, do more boundary checks newState['size'] = newSize newState['pos'] = newState['pos'] + cc if self.maxBounds is not None: r = self.stateRect(newState) if not self.maxBounds.contains(r): return self.setPos(newState['pos'], update=False) self.setSize(newState['size'], update=False) elif h['type'] in ['r', 'rf']: if h['type'] == 'rf': self.freeHandleMoved = True if not self.rotatable: return ## If the handle is directly over its center point, we can't compute an angle. try: if lp1.length() == 0 or lp0.length() == 0: return except OverflowError: return ## determine new rotation angle, constrained if necessary ang = newState['angle'] - lp0.angle(lp1) if ang is None: ## this should never happen.. return if self.rotateSnap or (modifiers & QtCore.Qt.ControlModifier): ang = round(ang / self.rotateSnapAngle) * self.rotateSnapAngle ## create rotation transform tr = QtGui.QTransform() tr.rotate(ang) ## move ROI so that center point remains stationary after rotate cc = self.mapToParent(cs) - (tr.map(cs) + self.state['pos']) newState['angle'] = ang newState['pos'] = newState['pos'] + cc ## check boundaries, update if self.maxBounds is not None: r = self.stateRect(newState) if not self.maxBounds.contains(r): return self.setPos(newState['pos'], update=False) self.setAngle(ang, update=False) ## If this is a free-rotate handle, its distance from the center may change. if h['type'] == 'rf': h['item'].setPos(self.mapFromScene(p1)) ## changes ROI coordinates of handle h['pos'] = self.mapFromParent(p1) elif h['type'] == 'sr': if h['center'][0] == h['pos'][0]: scaleAxis = 1 nonScaleAxis=0 else: scaleAxis = 0 nonScaleAxis=1 try: if lp1.length() == 0 or lp0.length() == 0: return except OverflowError: return ang = newState['angle'] - lp0.angle(lp1) if ang is None: return if self.rotateSnap or (modifiers & QtCore.Qt.ControlModifier): ang = round(ang / self.rotateSnapAngle) * self.rotateSnapAngle hs = abs(h['pos'][scaleAxis] - c[scaleAxis]) newState['size'][scaleAxis] = lp1.length() / hs #if self.scaleSnap or (modifiers & QtCore.Qt.ControlModifier): if self.scaleSnap: ## use CTRL only for angular snap here. newState['size'][scaleAxis] = round(newState['size'][scaleAxis] / self.snapSize) * self.snapSize if newState['size'][scaleAxis] == 0: newState['size'][scaleAxis] = 1 if self.aspectLocked: newState['size'][nonScaleAxis] = newState['size'][scaleAxis] c1 = c * newState['size'] tr = QtGui.QTransform() tr.rotate(ang) cc = self.mapToParent(cs) - (tr.map(c1) + self.state['pos']) newState['angle'] = ang newState['pos'] = newState['pos'] + cc if self.maxBounds is not None: r = self.stateRect(newState) if not self.maxBounds.contains(r): return self.setState(newState, update=False) self.stateChanged(finish=finish) def stateChanged(self, finish=True): """Process changes to the state of the ROI. If there are any changes, then the positions of handles are updated accordingly and sigRegionChanged is emitted. If finish is True, then sigRegionChangeFinished will also be emitted.""" changed = False if self.lastState is None: changed = True else: state = self.getState() for k in list(state.keys()): if state[k] != self.lastState[k]: changed = True self.prepareGeometryChange() if changed: ## Move all handles to match the current configuration of the ROI for h in self.handles: if h['item'] in self.childItems(): p = h['pos'] h['item'].setPos(h['pos'] * self.state['size']) self.update() self.sigRegionChanged.emit(self) elif self.freeHandleMoved: self.sigRegionChanged.emit(self) self.freeHandleMoved = False self.lastState = self.getState() if finish: self.stateChangeFinished() self.informViewBoundsChanged() def stateChangeFinished(self): self.sigRegionChangeFinished.emit(self) def stateRect(self, state): r = QtCore.QRectF(0, 0, state['size'][0], state['size'][1]) tr = QtGui.QTransform() tr.rotate(-state['angle']) r = tr.mapRect(r) return r.adjusted(state['pos'][0], state['pos'][1], state['pos'][0], state['pos'][1]) def getSnapPosition(self, pos, snap=None): ## Given that pos has been requested, return the nearest snap-to position ## optionally, snap may be passed in to specify a rectangular snap grid. ## override this function for more interesting snap functionality.. if snap is None or snap is True: if self.snapSize is None: return pos snap = Point(self.snapSize, self.snapSize) return Point( round(pos[0] / snap[0]) * snap[0], round(pos[1] / snap[1]) * snap[1] ) def boundingRect(self): return QtCore.QRectF(0, 0, self.state['size'][0], self.state['size'][1]).normalized() def paint(self, p, opt, widget): # Note: don't use self.boundingRect here, because subclasses may need to redefine it. r = QtCore.QRectF(0, 0, self.state['size'][0], self.state['size'][1]).normalized() p.setRenderHint(QtGui.QPainter.Antialiasing) p.setPen(self.currentPen) p.translate(r.left(), r.top()) p.scale(r.width(), r.height()) p.drawRect(0, 0, 1, 1) def getArraySlice(self, data, img, axes=(0,1), returnSlice=True): """Return a tuple of slice objects that can be used to slice the region from *data* that is covered by the bounding rectangle of this ROI. Also returns the transform that maps the ROI into data coordinates. If returnSlice is set to False, the function returns a pair of tuples with the values that would have been used to generate the slice objects. ((ax0Start, ax0Stop), (ax1Start, ax1Stop)) If the slice cannot be computed (usually because the scene/transforms are not properly constructed yet), then the method returns None. """ ## Determine shape of array along ROI axes dShape = (data.shape[axes[0]], data.shape[axes[1]]) ## Determine transform that maps ROI bounding box to image coordinates try: tr = self.sceneTransform() * fn.invertQTransform(img.sceneTransform()) except np.linalg.linalg.LinAlgError: return None ## Modify transform to scale from image coords to data coords axisOrder = img.axisOrder if axisOrder == 'row-major': tr.scale(float(dShape[1]) / img.width(), float(dShape[0]) / img.height()) else: tr.scale(float(dShape[0]) / img.width(), float(dShape[1]) / img.height()) ## Transform ROI bounds into data bounds dataBounds = tr.mapRect(self.boundingRect()) ## Intersect transformed ROI bounds with data bounds if axisOrder == 'row-major': intBounds = dataBounds.intersected(QtCore.QRectF(0, 0, dShape[1], dShape[0])) else: intBounds = dataBounds.intersected(QtCore.QRectF(0, 0, dShape[0], dShape[1])) ## Determine index values to use when referencing the array. bounds = ( (int(min(intBounds.left(), intBounds.right())), int(1+max(intBounds.left(), intBounds.right()))), (int(min(intBounds.bottom(), intBounds.top())), int(1+max(intBounds.bottom(), intBounds.top()))) ) if axisOrder == 'row-major': bounds = bounds[::-1] if returnSlice: ## Create slice objects sl = [slice(None)] * data.ndim sl[axes[0]] = slice(*bounds[0]) sl[axes[1]] = slice(*bounds[1]) return tuple(sl), tr else: return bounds, tr def getArrayRegion(self, data, img, axes=(0,1), returnMappedCoords=False, **kwds): r"""Use the position and orientation of this ROI relative to an imageItem to pull a slice from an array. =================== ==================================================== **Arguments** data The array to slice from. Note that this array does *not* have to be the same data that is represented in *img*. img (ImageItem or other suitable QGraphicsItem) Used to determine the relationship between the ROI and the boundaries of *data*. axes (length-2 tuple) Specifies the axes in *data* that correspond to the (x, y) axes of *img*. If the image's axis order is set to 'row-major', then the axes are instead specified in (y, x) order. returnMappedCoords (bool) If True, the array slice is returned along with a corresponding array of coordinates that were used to extract data from the original array. \**kwds All keyword arguments are passed to :func:`affineSlice <pyqtgraph.affineSlice>`. =================== ==================================================== This method uses :func:`affineSlice <pyqtgraph.affineSlice>` to generate the slice from *data* and uses :func:`getAffineSliceParams <pyqtgraph.ROI.getAffineSliceParams>` to determine the parameters to pass to :func:`affineSlice <pyqtgraph.affineSlice>`. If *returnMappedCoords* is True, then the method returns a tuple (result, coords) such that coords is the set of coordinates used to interpolate values from the original data, mapped into the parent coordinate system of the image. This is useful, when slicing data from images that have been transformed, for determining the location of each value in the sliced data. All extra keyword arguments are passed to :func:`affineSlice <pyqtgraph.affineSlice>`. """ # this is a hidden argument for internal use fromBR = kwds.pop('fromBoundingRect', False) shape, vectors, origin = self.getAffineSliceParams(data, img, axes, fromBoundingRect=fromBR) if not returnMappedCoords: rgn = fn.affineSlice(data, shape=shape, vectors=vectors, origin=origin, axes=axes, **kwds) return rgn else: kwds['returnCoords'] = True result, coords = fn.affineSlice(data, shape=shape, vectors=vectors, origin=origin, axes=axes, **kwds) ### map coordinates and return mapped = fn.transformCoordinates(img.transform(), coords) return result, mapped def getAffineSliceParams(self, data, img, axes=(0,1), fromBoundingRect=False): """ Returns the parameters needed to use :func:`affineSlice <pyqtgraph.affineSlice>` (shape, vectors, origin) to extract a subset of *data* using this ROI and *img* to specify the subset. If *fromBoundingRect* is True, then the ROI's bounding rectangle is used rather than the shape of the ROI. See :func:`getArrayRegion <pyqtgraph.ROI.getArrayRegion>` for more information. """ if self.scene() is not img.scene(): raise Exception("ROI and target item must be members of the same scene.") origin = img.mapToData(self.mapToItem(img, QtCore.QPointF(0, 0))) ## vx and vy point in the directions of the slice axes, but must be scaled properly vx = img.mapToData(self.mapToItem(img, QtCore.QPointF(1, 0))) - origin vy = img.mapToData(self.mapToItem(img, QtCore.QPointF(0, 1))) - origin lvx = np.sqrt(vx.x()**2 + vx.y()**2) lvy = np.sqrt(vy.x()**2 + vy.y()**2) ##img.width is number of pixels, not width of item. ##need pxWidth and pxHeight instead of pxLen ? sx = 1.0 / lvx sy = 1.0 / lvy vectors = ((vx.x()*sx, vx.y()*sx), (vy.x()*sy, vy.y()*sy)) if fromBoundingRect is True: shape = self.boundingRect().width(), self.boundingRect().height() origin = img.mapToData(self.mapToItem(img, self.boundingRect().topLeft())) origin = (origin.x(), origin.y()) else: shape = self.state['size'] origin = (origin.x(), origin.y()) shape = [abs(shape[0]/sx), abs(shape[1]/sy)] if img.axisOrder == 'row-major': # transpose output vectors = vectors[::-1] shape = shape[::-1] return shape, vectors, origin def renderShapeMask(self, width, height): """Return an array of 0.0-1.0 into which the shape of the item has been drawn. This can be used to mask array selections. """ if width == 0 or height == 0: return np.empty((width, height), dtype=float) im = QtGui.QImage(width, height, QtGui.QImage.Format_ARGB32) im.fill(0x0) p = QtGui.QPainter(im) p.setPen(fn.mkPen(None)) p.setBrush(fn.mkBrush('w')) shape = self.shape() bounds = shape.boundingRect() p.scale(im.width() / bounds.width(), im.height() / bounds.height()) p.translate(-bounds.topLeft()) p.drawPath(shape) p.end() mask = fn.imageToArray(im, transpose=True)[:,:,0].astype(float) / 255. return mask def getGlobalTransform(self, relativeTo=None): """Return global transformation (rotation angle+translation) required to move from relative state to current state. If relative state isn't specified, then we use the state of the ROI when mouse is pressed.""" if relativeTo == None: relativeTo = self.preMoveState st = self.getState() ## this is only allowed because we will be comparing the two relativeTo['scale'] = relativeTo['size'] st['scale'] = st['size'] t1 = SRTTransform(relativeTo) t2 = SRTTransform(st) return t2/t1 def applyGlobalTransform(self, tr): st = self.getState() st['scale'] = st['size'] st = SRTTransform(st) st = (st * tr).saveState() st['size'] = st['scale'] self.setState(st) class Handle(UIGraphicsItem): """ Handle represents a single user-interactable point attached to an ROI. They are usually created by a call to one of the ROI.add___Handle() methods. Handles are represented as a square, diamond, or circle, and are drawn with fixed pixel size regardless of the scaling of the view they are displayed in. Handles may be dragged to change the position, size, orientation, or other properties of the ROI they are attached to. """ types = { ## defines number of sides, start angle for each handle type 't': (4, np.pi/4), 'f': (4, np.pi/4), 's': (4, 0), 'r': (12, 0), 'sr': (12, 0), 'rf': (12, 0), } sigClicked = QtCore.Signal(object, object) # self, event sigRemoveRequested = QtCore.Signal(object) # self def __init__(self, radius, typ=None, pen=(200, 200, 220), parent=None, deletable=False): self.rois = [] self.radius = radius self.typ = typ self.pen = fn.mkPen(pen) self.currentPen = self.pen self.pen.setWidth(0) self.pen.setCosmetic(True) self.isMoving = False self.sides, self.startAng = self.types[typ] self.buildPath() self._shape = None self.menu = self.buildMenu() UIGraphicsItem.__init__(self, parent=parent) self.setAcceptedMouseButtons(QtCore.Qt.NoButton) self.deletable = deletable if deletable: self.setAcceptedMouseButtons(QtCore.Qt.RightButton) self.setZValue(11) def connectROI(self, roi): ### roi is the "parent" roi, i is the index of the handle in roi.handles self.rois.append(roi) def disconnectROI(self, roi): self.rois.remove(roi) def setDeletable(self, b): self.deletable = b if b: self.setAcceptedMouseButtons(self.acceptedMouseButtons() | QtCore.Qt.RightButton) else: self.setAcceptedMouseButtons(self.acceptedMouseButtons() & ~QtCore.Qt.RightButton) def removeClicked(self): self.sigRemoveRequested.emit(self) def hoverEvent(self, ev): hover = False if not ev.isExit(): if ev.acceptDrags(QtCore.Qt.LeftButton): hover=True for btn in [QtCore.Qt.LeftButton, QtCore.Qt.RightButton, QtCore.Qt.MidButton]: if int(self.acceptedMouseButtons() & btn) > 0 and ev.acceptClicks(btn): hover=True if hover: self.currentPen = fn.mkPen(255, 255,0) else: self.currentPen = self.pen self.update() def mouseClickEvent(self, ev): ## right-click cancels drag if ev.button() == QtCore.Qt.RightButton and self.isMoving: self.isMoving = False ## prevents any further motion self.movePoint(self.startPos, finish=True) ev.accept() elif int(ev.button() & self.acceptedMouseButtons()) > 0: ev.accept() if ev.button() == QtCore.Qt.RightButton and self.deletable: self.raiseContextMenu(ev) self.sigClicked.emit(self, ev) else: ev.ignore() def buildMenu(self): menu = QtGui.QMenu() menu.setTitle("Handle") self.removeAction = menu.addAction("Remove handle", self.removeClicked) return menu def getMenu(self): return self.menu def raiseContextMenu(self, ev): menu = self.scene().addParentContextMenus(self, self.getMenu(), ev) ## Make sure it is still ok to remove this handle removeAllowed = all([r.checkRemoveHandle(self) for r in self.rois]) self.removeAction.setEnabled(removeAllowed) pos = ev.screenPos() menu.popup(QtCore.QPoint(pos.x(), pos.y())) def mouseDragEvent(self, ev): if ev.button() != QtCore.Qt.LeftButton: return ev.accept() ## Inform ROIs that a drag is happening ## note: the ROI is informed that the handle has moved using ROI.movePoint ## this is for other (more nefarious) purposes. #for r in self.roi: #r[0].pointDragEvent(r[1], ev) if ev.isFinish(): if self.isMoving: for r in self.rois: r.stateChangeFinished() self.isMoving = False elif ev.isStart(): for r in self.rois: r.handleMoveStarted() self.isMoving = True self.startPos = self.scenePos() self.cursorOffset = self.scenePos() - ev.buttonDownScenePos() if self.isMoving: ## note: isMoving may become False in mid-drag due to right-click. pos = ev.scenePos() + self.cursorOffset self.movePoint(pos, ev.modifiers(), finish=False) def movePoint(self, pos, modifiers=QtCore.Qt.KeyboardModifier(), finish=True): for r in self.rois: if not r.checkPointMove(self, pos, modifiers): return #print "point moved; inform %d ROIs" % len(self.roi) # A handle can be used by multiple ROIs; tell each to update its handle position for r in self.rois: r.movePoint(self, pos, modifiers, finish=finish, coords='scene') def buildPath(self): size = self.radius self.path = QtGui.QPainterPath() ang = self.startAng dt = 2*np.pi / self.sides for i in range(0, self.sides+1): x = size * cos(ang) y = size * sin(ang) ang += dt if i == 0: self.path.moveTo(x, y) else: self.path.lineTo(x, y) def paint(self, p, opt, widget): p.setRenderHints(p.Antialiasing, True) p.setPen(self.currentPen) p.drawPath(self.shape()) def shape(self): if self._shape is None: s = self.generateShape() if s is None: return self.path self._shape = s self.prepareGeometryChange() ## beware--this can cause the view to adjust, which would immediately invalidate the shape. return self._shape def boundingRect(self): s1 = self.shape() return self.shape().boundingRect() def generateShape(self): dt = self.deviceTransform() if dt is None: self._shape = self.path return None v = dt.map(QtCore.QPointF(1, 0)) - dt.map(QtCore.QPointF(0, 0)) va = np.arctan2(v.y(), v.x()) dti = fn.invertQTransform(dt) devPos = dt.map(QtCore.QPointF(0,0)) tr = QtGui.QTransform() tr.translate(devPos.x(), devPos.y()) tr.rotate(va * 180. / 3.1415926) return dti.map(tr.map(self.path)) def viewTransformChanged(self): GraphicsObject.viewTransformChanged(self) self._shape = None ## invalidate shape, recompute later if requested. self.update() class MouseDragHandler(object): """Implements default mouse drag behavior for ROI (not for ROI handles). """ def __init__(self, roi): self.roi = roi self.dragMode = None self.startState = None self.snapModifier = QtCore.Qt.ControlModifier self.translateModifier = QtCore.Qt.NoModifier self.rotateModifier = QtCore.Qt.AltModifier self.scaleModifier = QtCore.Qt.ShiftModifier self.rotateSpeed = 0.5 self.scaleSpeed = 1.01 def mouseDragEvent(self, ev): roi = self.roi if ev.isStart(): if ev.button() == QtCore.Qt.LeftButton: roi.setSelected(True) mods = ev.modifiers() & ~self.snapModifier if roi.translatable and mods == self.translateModifier: self.dragMode = 'translate' elif roi.rotatable and mods == self.rotateModifier: self.dragMode = 'rotate' elif roi.resizable and mods == self.scaleModifier: self.dragMode = 'scale' else: self.dragMode = None if self.dragMode is not None: roi._moveStarted() self.startPos = roi.mapToParent(ev.buttonDownPos()) self.startState = roi.saveState() self.cursorOffset = roi.pos() - self.startPos ev.accept() else: ev.ignore() else: self.dragMode = None ev.ignore() if ev.isFinish() and self.dragMode is not None: roi._moveFinished() return # roi.isMoving becomes False if the move was cancelled by right-click if not roi.isMoving or self.dragMode is None: return snap = True if (ev.modifiers() & self.snapModifier) else None pos = roi.mapToParent(ev.pos()) if self.dragMode == 'translate': newPos = pos + self.cursorOffset roi.translate(newPos - roi.pos(), snap=snap, finish=False) elif self.dragMode == 'rotate': diff = self.rotateSpeed * (ev.scenePos() - ev.buttonDownScenePos()).x() angle = self.startState['angle'] - diff roi.setAngle(angle, centerLocal=ev.buttonDownPos(), snap=snap, finish=False) elif self.dragMode == 'scale': diff = self.scaleSpeed ** -(ev.scenePos() - ev.buttonDownScenePos()).y() roi.setSize(Point(self.startState['size']) * diff, centerLocal=ev.buttonDownPos(), snap=snap, finish=False) class TestROI(ROI): def __init__(self, pos, size, **args): ROI.__init__(self, pos, size, **args) self.addTranslateHandle([0.5, 0.5]) self.addScaleHandle([1, 1], [0, 0]) self.addScaleHandle([0, 0], [1, 1]) self.addScaleRotateHandle([1, 0.5], [0.5, 0.5]) self.addScaleHandle([0.5, 1], [0.5, 0.5]) self.addRotateHandle([1, 0], [0, 0]) self.addRotateHandle([0, 1], [1, 1]) class RectROI(ROI): r""" Rectangular ROI subclass with a single scale handle at the top-right corner. ============== ============================================================= **Arguments** pos (length-2 sequence) The position of the ROI origin. See ROI(). size (length-2 sequence) The size of the ROI. See ROI(). centered (bool) If True, scale handles affect the ROI relative to its center, rather than its origin. sideScalers (bool) If True, extra scale handles are added at the top and right edges. \**args All extra keyword arguments are passed to ROI() ============== ============================================================= """ def __init__(self, pos, size, centered=False, sideScalers=False, **args): ROI.__init__(self, pos, size, **args) if centered: center = [0.5, 0.5] else: center = [0, 0] self.addScaleHandle([1, 1], center) if sideScalers: self.addScaleHandle([1, 0.5], [center[0], 0.5]) self.addScaleHandle([0.5, 1], [0.5, center[1]]) class LineROI(ROI): r""" Rectangular ROI subclass with scale-rotate handles on either side. This allows the ROI to be positioned as if moving the ends of a line segment. A third handle controls the width of the ROI orthogonal to its "line" axis. ============== ============================================================= **Arguments** pos1 (length-2 sequence) The position of the center of the ROI's left edge. pos2 (length-2 sequence) The position of the center of the ROI's right edge. width (float) The width of the ROI. \**args All extra keyword arguments are passed to ROI() ============== ============================================================= """ def __init__(self, pos1, pos2, width, **args): pos1 = Point(pos1) pos2 = Point(pos2) d = pos2-pos1 l = d.length() ang = Point(1, 0).angle(d) ra = ang * np.pi / 180. c = Point(-width/2. * sin(ra), -width/2. * cos(ra)) pos1 = pos1 + c ROI.__init__(self, pos1, size=Point(l, width), angle=ang, **args) self.addScaleRotateHandle([0, 0.5], [1, 0.5]) self.addScaleRotateHandle([1, 0.5], [0, 0.5]) self.addScaleHandle([0.5, 1], [0.5, 0.5]) class MultiRectROI(QtGui.QGraphicsObject): r""" Chain of rectangular ROIs connected by handles. This is generally used to mark a curved path through an image similarly to PolyLineROI. It differs in that each segment of the chain is rectangular instead of linear and thus has width. ============== ============================================================= **Arguments** points (list of length-2 sequences) The list of points in the path. width (float) The width of the ROIs orthogonal to the path. \**args All extra keyword arguments are passed to ROI() ============== ============================================================= """ sigRegionChangeFinished = QtCore.Signal(object) sigRegionChangeStarted = QtCore.Signal(object) sigRegionChanged = QtCore.Signal(object) def __init__(self, points, width, pen=None, **args): QtGui.QGraphicsObject.__init__(self) self.pen = pen self.roiArgs = args self.lines = [] if len(points) < 2: raise Exception("Must start with at least 2 points") ## create first segment self.addSegment(points[1], connectTo=points[0], scaleHandle=True) ## create remaining segments for p in points[2:]: self.addSegment(p) def paint(self, *args): pass def boundingRect(self): return QtCore.QRectF() def roiChangedEvent(self): w = self.lines[0].state['size'][1] for l in self.lines[1:]: w0 = l.state['size'][1] if w == w0: continue l.scale([1.0, w/w0], center=[0.5,0.5]) self.sigRegionChanged.emit(self) def roiChangeStartedEvent(self): self.sigRegionChangeStarted.emit(self) def roiChangeFinishedEvent(self): self.sigRegionChangeFinished.emit(self) def getHandlePositions(self): """Return the positions of all handles in local coordinates.""" pos = [self.mapFromScene(self.lines[0].getHandles()[0].scenePos())] for l in self.lines: pos.append(self.mapFromScene(l.getHandles()[1].scenePos())) return pos def getArrayRegion(self, arr, img=None, axes=(0,1), **kwds): rgns = [] for l in self.lines: rgn = l.getArrayRegion(arr, img, axes=axes, **kwds) if rgn is None: continue rgns.append(rgn) #print l.state['size'] ## make sure orthogonal axis is the same size ## (sometimes fp errors cause differences) if img.axisOrder == 'row-major': axes = axes[::-1] ms = min([r.shape[axes[1]] for r in rgns]) sl = [slice(None)] * rgns[0].ndim sl[axes[1]] = slice(0,ms) rgns = [r[tuple(sl)] for r in rgns] #print [r.shape for r in rgns], axes return np.concatenate(rgns, axis=axes[0]) def addSegment(self, pos=(0,0), scaleHandle=False, connectTo=None): """ Add a new segment to the ROI connecting from the previous endpoint to *pos*. (pos is specified in the parent coordinate system of the MultiRectROI) """ ## by default, connect to the previous endpoint if connectTo is None: connectTo = self.lines[-1].getHandles()[1] ## create new ROI newRoi = ROI((0,0), [1, 5], parent=self, pen=self.pen, **self.roiArgs) self.lines.append(newRoi) ## Add first SR handle if isinstance(connectTo, Handle): self.lines[-1].addScaleRotateHandle([0, 0.5], [1, 0.5], item=connectTo) newRoi.movePoint(connectTo, connectTo.scenePos(), coords='scene') else: h = self.lines[-1].addScaleRotateHandle([0, 0.5], [1, 0.5]) newRoi.movePoint(h, connectTo, coords='scene') ## add second SR handle h = self.lines[-1].addScaleRotateHandle([1, 0.5], [0, 0.5]) newRoi.movePoint(h, pos) ## optionally add scale handle (this MUST come after the two SR handles) if scaleHandle: newRoi.addScaleHandle([0.5, 1], [0.5, 0.5]) newRoi.translatable = False newRoi.sigRegionChanged.connect(self.roiChangedEvent) newRoi.sigRegionChangeStarted.connect(self.roiChangeStartedEvent) newRoi.sigRegionChangeFinished.connect(self.roiChangeFinishedEvent) self.sigRegionChanged.emit(self) def removeSegment(self, index=-1): """Remove a segment from the ROI.""" roi = self.lines[index] self.lines.pop(index) self.scene().removeItem(roi) roi.sigRegionChanged.disconnect(self.roiChangedEvent) roi.sigRegionChangeStarted.disconnect(self.roiChangeStartedEvent) roi.sigRegionChangeFinished.disconnect(self.roiChangeFinishedEvent) self.sigRegionChanged.emit(self) class MultiLineROI(MultiRectROI): def __init__(self, *args, **kwds): MultiRectROI.__init__(self, *args, **kwds) print("Warning: MultiLineROI has been renamed to MultiRectROI. (and MultiLineROI may be redefined in the future)") class EllipseROI(ROI): r""" Elliptical ROI subclass with one scale handle and one rotation handle. ============== ============================================================= **Arguments** pos (length-2 sequence) The position of the ROI's origin. size (length-2 sequence) The size of the ROI's bounding rectangle. \**args All extra keyword arguments are passed to ROI() ============== ============================================================= """ def __init__(self, pos, size, **args): self.path = None ROI.__init__(self, pos, size, **args) self.sigRegionChanged.connect(self._clearPath) self._addHandles() def _addHandles(self): self.addRotateHandle([1.0, 0.5], [0.5, 0.5]) self.addScaleHandle([0.5*2.**-0.5 + 0.5, 0.5*2.**-0.5 + 0.5], [0.5, 0.5]) def _clearPath(self): self.path = None def paint(self, p, opt, widget): r = self.boundingRect() p.setRenderHint(QtGui.QPainter.Antialiasing) p.setPen(self.currentPen) p.scale(r.width(), r.height())## workaround for GL bug r = QtCore.QRectF(r.x()/r.width(), r.y()/r.height(), 1,1) p.drawEllipse(r) def getArrayRegion(self, arr, img=None, axes=(0, 1), **kwds): """ Return the result of ROI.getArrayRegion() masked by the elliptical shape of the ROI. Regions outside the ellipse are set to 0. """ # Note: we could use the same method as used by PolyLineROI, but this # implementation produces a nicer mask. arr = ROI.getArrayRegion(self, arr, img, axes, **kwds) if arr is None or arr.shape[axes[0]] == 0 or arr.shape[axes[1]] == 0: return arr w = arr.shape[axes[0]] h = arr.shape[axes[1]] ## generate an ellipsoidal mask mask = np.fromfunction(lambda x,y: (((x+0.5)/(w/2.)-1)**2+ ((y+0.5)/(h/2.)-1)**2)**0.5 < 1, (w, h)) # reshape to match array axes if axes[0] > axes[1]: mask = mask.T shape = [(n if i in axes else 1) for i,n in enumerate(arr.shape)] mask = mask.reshape(shape) return arr * mask def shape(self): if self.path is None: path = QtGui.QPainterPath() # Note: Qt has a bug where very small ellipses (radius <0.001) do # not correctly intersect with mouse position (upper-left and # lower-right quadrants are not clickable). #path.addEllipse(self.boundingRect()) # Workaround: manually draw the path. br = self.boundingRect() center = br.center() r1 = br.width() / 2. r2 = br.height() / 2. theta = np.linspace(0, 2*np.pi, 24) x = center.x() + r1 * np.cos(theta) y = center.y() + r2 * np.sin(theta) path.moveTo(x[0], y[0]) for i in range(1, len(x)): path.lineTo(x[i], y[i]) self.path = path return self.path class CircleROI(EllipseROI): r""" Circular ROI subclass. Behaves exactly as EllipseROI, but may only be scaled proportionally to maintain its aspect ratio. ============== ============================================================= **Arguments** pos (length-2 sequence) The position of the ROI's origin. size (length-2 sequence) The size of the ROI's bounding rectangle. \**args All extra keyword arguments are passed to ROI() ============== ============================================================= """ def __init__(self, pos, size=None, radius=None, **args): if size is None: if radius is None: raise TypeError("Must provide either size or radius.") size = (radius*2, radius*2) EllipseROI.__init__(self, pos, size, **args) self.aspectLocked = True def _addHandles(self): self.addScaleHandle([0.5*2.**-0.5 + 0.5, 0.5*2.**-0.5 + 0.5], [0.5, 0.5]) class PolygonROI(ROI): ## deprecated. Use PloyLineROI instead. def __init__(self, positions, pos=None, **args): if pos is None: pos = [0,0] ROI.__init__(self, pos, [1,1], **args) for p in positions: self.addFreeHandle(p) self.setZValue(1000) print("Warning: PolygonROI is deprecated. Use PolyLineROI instead.") def listPoints(self): return [p['item'].pos() for p in self.handles] def paint(self, p, *args): p.setRenderHint(QtGui.QPainter.Antialiasing) p.setPen(self.currentPen) for i in range(len(self.handles)): h1 = self.handles[i]['item'].pos() h2 = self.handles[i-1]['item'].pos() p.drawLine(h1, h2) def boundingRect(self): r = QtCore.QRectF() for h in self.handles: r |= self.mapFromItem(h['item'], h['item'].boundingRect()).boundingRect() ## |= gives the union of the two QRectFs return r def shape(self): p = QtGui.QPainterPath() p.moveTo(self.handles[0]['item'].pos()) for i in range(len(self.handles)): p.lineTo(self.handles[i]['item'].pos()) return p def stateCopy(self): sc = {} sc['pos'] = Point(self.state['pos']) sc['size'] = Point(self.state['size']) sc['angle'] = self.state['angle'] return sc class PolyLineROI(ROI): r""" Container class for multiple connected LineSegmentROIs. This class allows the user to draw paths of multiple line segments. ============== ============================================================= **Arguments** positions (list of length-2 sequences) The list of points in the path. Note that, unlike the handle positions specified in other ROIs, these positions must be expressed in the normal coordinate system of the ROI, rather than (0 to 1) relative to the size of the ROI. closed (bool) if True, an extra LineSegmentROI is added connecting the beginning and end points. \**args All extra keyword arguments are passed to ROI() ============== ============================================================= """ def __init__(self, positions, closed=False, pos=None, **args): if pos is None: pos = [0,0] self.closed = closed self.segments = [] ROI.__init__(self, pos, size=[1,1], **args) self.setPoints(positions) def setPoints(self, points, closed=None): """ Set the complete sequence of points displayed by this ROI. ============= ========================================================= **Arguments** points List of (x,y) tuples specifying handle locations to set. closed If bool, then this will set whether the ROI is closed (the last point is connected to the first point). If None, then the closed mode is left unchanged. ============= ========================================================= """ if closed is not None: self.closed = closed self.clearPoints() for p in points: self.addFreeHandle(p) start = -1 if self.closed else 0 for i in range(start, len(self.handles)-1): self.addSegment(self.handles[i]['item'], self.handles[i+1]['item']) def clearPoints(self): """ Remove all handles and segments. """ while len(self.handles) > 0: self.removeHandle(self.handles[0]['item']) def getState(self): state = ROI.getState(self) state['closed'] = self.closed state['points'] = [Point(h.pos()) for h in self.getHandles()] return state def saveState(self): state = ROI.saveState(self) state['closed'] = self.closed state['points'] = [tuple(h.pos()) for h in self.getHandles()] return state def setState(self, state): ROI.setState(self, state) self.setPoints(state['points'], closed=state['closed']) def addSegment(self, h1, h2, index=None): seg = _PolyLineSegment(handles=(h1, h2), pen=self.pen, parent=self, movable=False) if index is None: self.segments.append(seg) else: self.segments.insert(index, seg) seg.sigClicked.connect(self.segmentClicked) seg.setAcceptedMouseButtons(QtCore.Qt.LeftButton) seg.setZValue(self.zValue()+1) for h in seg.handles: h['item'].setDeletable(True) h['item'].setAcceptedMouseButtons(h['item'].acceptedMouseButtons() | QtCore.Qt.LeftButton) ## have these handles take left clicks too, so that handles cannot be added on top of other handles def setMouseHover(self, hover): ## Inform all the ROI's segments that the mouse is(not) hovering over it ROI.setMouseHover(self, hover) for s in self.segments: s.setParentHover(hover) def addHandle(self, info, index=None): h = ROI.addHandle(self, info, index=index) h.sigRemoveRequested.connect(self.removeHandle) self.stateChanged(finish=True) return h def segmentClicked(self, segment, ev=None, pos=None): ## pos should be in this item's coordinate system if ev != None: pos = segment.mapToParent(ev.pos()) elif pos != None: pos = pos else: raise Exception("Either an event or a position must be given.") h1 = segment.handles[0]['item'] h2 = segment.handles[1]['item'] i = self.segments.index(segment) h3 = self.addFreeHandle(pos, index=self.indexOfHandle(h2)) self.addSegment(h3, h2, index=i+1) segment.replaceHandle(h2, h3) def removeHandle(self, handle, updateSegments=True): ROI.removeHandle(self, handle) handle.sigRemoveRequested.disconnect(self.removeHandle) if not updateSegments: return segments = handle.rois[:] if len(segments) == 1: self.removeSegment(segments[0]) elif len(segments) > 1: handles = [h['item'] for h in segments[1].handles] handles.remove(handle) segments[0].replaceHandle(handle, handles[0]) self.removeSegment(segments[1]) self.stateChanged(finish=True) def removeSegment(self, seg): for handle in seg.handles[:]: seg.removeHandle(handle['item']) self.segments.remove(seg) seg.sigClicked.disconnect(self.segmentClicked) self.scene().removeItem(seg) def checkRemoveHandle(self, h): ## called when a handle is about to display its context menu if self.closed: return len(self.handles) > 3 else: return len(self.handles) > 2 def paint(self, p, *args): pass def boundingRect(self): return self.shape().boundingRect() def shape(self): p = QtGui.QPainterPath() if len(self.handles) == 0: return p p.moveTo(self.handles[0]['item'].pos()) for i in range(len(self.handles)): p.lineTo(self.handles[i]['item'].pos()) p.lineTo(self.handles[0]['item'].pos()) return p def getArrayRegion(self, data, img, axes=(0,1), **kwds): """ Return the result of ROI.getArrayRegion(), masked by the shape of the ROI. Values outside the ROI shape are set to 0. """ br = self.boundingRect() if br.width() > 1000: raise Exception() sliced = ROI.getArrayRegion(self, data, img, axes=axes, fromBoundingRect=True, **kwds) if img.axisOrder == 'col-major': mask = self.renderShapeMask(sliced.shape[axes[0]], sliced.shape[axes[1]]) else: mask = self.renderShapeMask(sliced.shape[axes[1]], sliced.shape[axes[0]]) mask = mask.T # reshape mask to ensure it is applied to the correct data axes shape = [1] * data.ndim shape[axes[0]] = sliced.shape[axes[0]] shape[axes[1]] = sliced.shape[axes[1]] mask = mask.reshape(shape) return sliced * mask def setPen(self, *args, **kwds): ROI.setPen(self, *args, **kwds) for seg in self.segments: seg.setPen(*args, **kwds) class LineSegmentROI(ROI): r""" ROI subclass with two freely-moving handles defining a line. ============== ============================================================= **Arguments** positions (list of two length-2 sequences) The endpoints of the line segment. Note that, unlike the handle positions specified in other ROIs, these positions must be expressed in the normal coordinate system of the ROI, rather than (0 to 1) relative to the size of the ROI. \**args All extra keyword arguments are passed to ROI() ============== ============================================================= """ def __init__(self, positions=(None, None), pos=None, handles=(None,None), **args): if pos is None: pos = [0,0] ROI.__init__(self, pos, [1,1], **args) if len(positions) > 2: raise Exception("LineSegmentROI must be defined by exactly 2 positions. For more points, use PolyLineROI.") for i, p in enumerate(positions): self.addFreeHandle(p, item=handles[i]) @property def endpoints(self): # must not be cached because self.handles may change. return [h['item'] for h in self.handles] def listPoints(self): return [p['item'].pos() for p in self.handles] def paint(self, p, *args): p.setRenderHint(QtGui.QPainter.Antialiasing) p.setPen(self.currentPen) h1 = self.endpoints[0].pos() h2 = self.endpoints[1].pos() p.drawLine(h1, h2) def boundingRect(self): return self.shape().boundingRect() def shape(self): p = QtGui.QPainterPath() h1 = self.endpoints[0].pos() h2 = self.endpoints[1].pos() dh = h2-h1 if dh.length() == 0: return p pxv = self.pixelVectors(dh)[1] if pxv is None: return p pxv *= 4 p.moveTo(h1+pxv) p.lineTo(h2+pxv) p.lineTo(h2-pxv) p.lineTo(h1-pxv) p.lineTo(h1+pxv) return p def getArrayRegion(self, data, img, axes=(0,1), order=1, returnMappedCoords=False, **kwds): """ Use the position of this ROI relative to an imageItem to pull a slice from an array. Since this pulls 1D data from a 2D coordinate system, the return value will have ndim = data.ndim-1 See ROI.getArrayRegion() for a description of the arguments. """ imgPts = [self.mapToItem(img, h.pos()) for h in self.endpoints] rgns = [] coords = [] d = Point(imgPts[1] - imgPts[0]) o = Point(imgPts[0]) rgn = fn.affineSlice(data, shape=(int(d.length()),), vectors=[Point(d.norm())], origin=o, axes=axes, order=order, returnCoords=returnMappedCoords, **kwds) return rgn class _PolyLineSegment(LineSegmentROI): # Used internally by PolyLineROI def __init__(self, *args, **kwds): self._parentHovering = False LineSegmentROI.__init__(self, *args, **kwds) def setParentHover(self, hover): # set independently of own hover state if self._parentHovering != hover: self._parentHovering = hover self._updateHoverColor() def _makePen(self): if self.mouseHovering or self._parentHovering: return fn.mkPen(255, 255, 0) else: return self.pen def hoverEvent(self, ev): # accept drags even though we discard them to prevent competition with parent ROI # (unless parent ROI is not movable) if self.parentItem().translatable: ev.acceptDrags(QtCore.Qt.LeftButton) return LineSegmentROI.hoverEvent(self, ev) class CrosshairROI(ROI): """A crosshair ROI whose position is at the center of the crosshairs. By default, it is scalable, rotatable and translatable.""" def __init__(self, pos=None, size=None, **kargs): if size == None: size=[1,1] if pos == None: pos = [0,0] self._shape = None ROI.__init__(self, pos, size, **kargs) self.sigRegionChanged.connect(self.invalidate) self.addScaleRotateHandle(Point(1, 0), Point(0, 0)) self.aspectLocked = True def invalidate(self): self._shape = None self.prepareGeometryChange() def boundingRect(self): return self.shape().boundingRect() def shape(self): if self._shape is None: radius = self.getState()['size'][1] p = QtGui.QPainterPath() p.moveTo(Point(0, -radius)) p.lineTo(Point(0, radius)) p.moveTo(Point(-radius, 0)) p.lineTo(Point(radius, 0)) p = self.mapToDevice(p) stroker = QtGui.QPainterPathStroker() stroker.setWidth(10) outline = stroker.createStroke(p) self._shape = self.mapFromDevice(outline) return self._shape def paint(self, p, *args): radius = self.getState()['size'][1] p.setRenderHint(QtGui.QPainter.Antialiasing) p.setPen(self.currentPen) p.drawLine(Point(0, -radius), Point(0, radius)) p.drawLine(Point(-radius, 0), Point(radius, 0)) class RulerROI(LineSegmentROI): def paint(self, p, *args): LineSegmentROI.paint(self, p, *args) h1 = self.handles[0]['item'].pos() h2 = self.handles[1]['item'].pos() p1 = p.transform().map(h1) p2 = p.transform().map(h2) vec = Point(h2) - Point(h1) length = vec.length() angle = vec.angle(Point(1, 0)) pvec = p2 - p1 pvecT = Point(pvec.y(), -pvec.x()) pos = 0.5 * (p1 + p2) + pvecT * 40 / pvecT.length() p.resetTransform() txt = fn.siFormat(length, suffix='m') + '\n%0.1f deg' % angle p.drawText(QtCore.QRectF(pos.x()-50, pos.y()-50, 100, 100), QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter, txt) def boundingRect(self): r = LineSegmentROI.boundingRect(self) pxl = self.pixelLength(Point([1, 0])) if pxl is None: return r pxw = 50 * pxl return r.adjusted(-50, -50, 50, 50)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/ButtonItem.py
.py
1,637
59
from ..Qt import QtGui, QtCore from .GraphicsObject import GraphicsObject __all__ = ['ButtonItem'] class ButtonItem(GraphicsObject): """Button graphicsItem displaying an image.""" clicked = QtCore.Signal(object) def __init__(self, imageFile=None, width=None, parentItem=None, pixmap=None): self.enabled = True GraphicsObject.__init__(self) if imageFile is not None: self.setImageFile(imageFile) elif pixmap is not None: self.setPixmap(pixmap) if width is not None: s = float(width) / self.pixmap.width() self.scale(s, s) if parentItem is not None: self.setParentItem(parentItem) self.setOpacity(0.7) def setImageFile(self, imageFile): self.setPixmap(QtGui.QPixmap(imageFile)) def setPixmap(self, pixmap): self.pixmap = pixmap self.update() def mouseClickEvent(self, ev): if self.enabled: self.clicked.emit(self) def mouseHoverEvent(self, ev): if not self.enabled: return if ev.isEnter(): self.setOpacity(1.0) else: self.setOpacity(0.7) def disable(self): self.enabled = False self.setOpacity(0.4) def enable(self): self.enabled = True self.setOpacity(0.7) def paint(self, p, *args): p.setRenderHint(p.Antialiasing) p.drawPixmap(0, 0, self.pixmap) def boundingRect(self): return QtCore.QRectF(self.pixmap.rect())
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/LinearRegionItem.py
.py
12,087
298
# -*- coding: utf-8 -*- from ..Qt import QtGui, QtCore from .GraphicsObject import GraphicsObject from .InfiniteLine import InfiniteLine from .. import functions as fn from .. import debug as debug __all__ = ['LinearRegionItem'] class LinearRegionItem(GraphicsObject): """ **Bases:** :class:`GraphicsObject <pyqtgraph.GraphicsObject>` Used for marking a horizontal or vertical region in plots. The region can be dragged and is bounded by lines which can be dragged individually. =============================== ============================================================================= **Signals:** sigRegionChangeFinished(self) Emitted when the user has finished dragging the region (or one of its lines) and when the region is changed programatically. sigRegionChanged(self) Emitted while the user is dragging the region (or one of its lines) and when the region is changed programatically. =============================== ============================================================================= """ sigRegionChangeFinished = QtCore.Signal(object) sigRegionChanged = QtCore.Signal(object) Vertical = 0 Horizontal = 1 _orientation_axis = { Vertical: 0, Horizontal: 1, 'vertical': 0, 'horizontal': 1, } def __init__(self, values=(0, 1), orientation='vertical', brush=None, pen=None, hoverBrush=None, hoverPen=None, movable=True, bounds=None, span=(0, 1), swapMode='sort'): """Create a new LinearRegionItem. ============== ===================================================================== **Arguments:** values A list of the positions of the lines in the region. These are not limits; limits can be set by specifying bounds. orientation Options are 'vertical' or 'horizontal', indicating the The default is 'vertical', indicating that the brush Defines the brush that fills the region. Can be any arguments that are valid for :func:`mkBrush <pyqtgraph.mkBrush>`. Default is transparent blue. pen The pen to use when drawing the lines that bound the region. hoverBrush The brush to use when the mouse is hovering over the region. hoverPen The pen to use when the mouse is hovering over the region. movable If True, the region and individual lines are movable by the user; if False, they are static. bounds Optional [min, max] bounding values for the region span Optional [min, max] giving the range over the view to draw the region. For example, with a vertical line, use ``span=(0.5, 1)`` to draw only on the top half of the view. swapMode Sets the behavior of the region when the lines are moved such that their order reverses. "block" means the user cannot drag one line past the other. "push" causes both lines to be moved if one would cross the other. "sort" means that lines may trade places, but the output of getRegion always gives the line positions in ascending order. None means that no attempt is made to handle swapped line positions. The default is "sort". ============== ===================================================================== """ GraphicsObject.__init__(self) self.orientation = orientation self.bounds = QtCore.QRectF() self.blockLineSignal = False self.moving = False self.mouseHovering = False self.span = span self.swapMode = swapMode self._bounds = None # note LinearRegionItem.Horizontal and LinearRegionItem.Vertical # are kept for backward compatibility. lineKwds = dict( movable=movable, bounds=bounds, span=span, pen=pen, hoverPen=hoverPen, ) if orientation in ('horizontal', LinearRegionItem.Horizontal): self.lines = [ # rotate lines to 180 to preserve expected line orientation # with respect to region. This ensures that placing a '<|' # marker on lines[0] causes it to point left in vertical mode # and down in horizontal mode. InfiniteLine(QtCore.QPointF(0, values[0]), angle=0, **lineKwds), InfiniteLine(QtCore.QPointF(0, values[1]), angle=0, **lineKwds)] self.lines[0].scale(1, -1) self.lines[1].scale(1, -1) elif orientation in ('vertical', LinearRegionItem.Vertical): self.lines = [ InfiniteLine(QtCore.QPointF(values[0], 0), angle=90, **lineKwds), InfiniteLine(QtCore.QPointF(values[1], 0), angle=90, **lineKwds)] else: raise Exception("Orientation must be 'vertical' or 'horizontal'.") for l in self.lines: l.setParentItem(self) l.sigPositionChangeFinished.connect(self.lineMoveFinished) self.lines[0].sigPositionChanged.connect(lambda: self.lineMoved(0)) self.lines[1].sigPositionChanged.connect(lambda: self.lineMoved(1)) if brush is None: brush = QtGui.QBrush(QtGui.QColor(0, 0, 255, 50)) self.setBrush(brush) if hoverBrush is None: c = self.brush.color() c.setAlpha(min(c.alpha() * 2, 255)) hoverBrush = fn.mkBrush(c) self.setHoverBrush(hoverBrush) self.setMovable(movable) def getRegion(self): """Return the values at the edges of the region.""" r = (self.lines[0].value(), self.lines[1].value()) if self.swapMode == 'sort': return (min(r), max(r)) else: return r def setRegion(self, rgn): """Set the values for the edges of the region. ============== ============================================== **Arguments:** rgn A list or tuple of the lower and upper values. ============== ============================================== """ if self.lines[0].value() == rgn[0] and self.lines[1].value() == rgn[1]: return self.blockLineSignal = True self.lines[0].setValue(rgn[0]) self.blockLineSignal = False self.lines[1].setValue(rgn[1]) #self.blockLineSignal = False self.lineMoved(0) self.lineMoved(1) self.lineMoveFinished() def setBrush(self, *br, **kargs): """Set the brush that fills the region. Can have any arguments that are valid for :func:`mkBrush <pyqtgraph.mkBrush>`. """ self.brush = fn.mkBrush(*br, **kargs) self.currentBrush = self.brush def setHoverBrush(self, *br, **kargs): """Set the brush that fills the region when the mouse is hovering over. Can have any arguments that are valid for :func:`mkBrush <pyqtgraph.mkBrush>`. """ self.hoverBrush = fn.mkBrush(*br, **kargs) def setBounds(self, bounds): """Optional [min, max] bounding values for the region. To have no bounds on the region use [None, None]. Does not affect the current position of the region unless it is outside the new bounds. See :func:`setRegion <pyqtgraph.LinearRegionItem.setRegion>` to set the position of the region.""" for l in self.lines: l.setBounds(bounds) def setMovable(self, m): """Set lines to be movable by the user, or not. If lines are movable, they will also accept HoverEvents.""" for l in self.lines: l.setMovable(m) self.movable = m self.setAcceptHoverEvents(m) def setSpan(self, mn, mx): if self.span == (mn, mx): return self.span = (mn, mx) self.lines[0].setSpan(mn, mx) self.lines[1].setSpan(mn, mx) self.update() def boundingRect(self): br = self.viewRect() # bounds of containing ViewBox mapped to local coords. rng = self.getRegion() if self.orientation in ('vertical', LinearRegionItem.Vertical): br.setLeft(rng[0]) br.setRight(rng[1]) length = br.height() br.setBottom(br.top() + length * self.span[1]) br.setTop(br.top() + length * self.span[0]) else: br.setTop(rng[0]) br.setBottom(rng[1]) length = br.width() br.setRight(br.left() + length * self.span[1]) br.setLeft(br.left() + length * self.span[0]) br = br.normalized() if self._bounds != br: self._bounds = br self.prepareGeometryChange() return br def paint(self, p, *args): profiler = debug.Profiler() p.setBrush(self.currentBrush) p.setPen(fn.mkPen(None)) p.drawRect(self.boundingRect()) def dataBounds(self, axis, frac=1.0, orthoRange=None): if axis == self._orientation_axis[self.orientation]: return self.getRegion() else: return None def lineMoved(self, i): if self.blockLineSignal: return # lines swapped if self.lines[0].value() > self.lines[1].value(): if self.swapMode == 'block': self.lines[i].setValue(self.lines[1-i].value()) elif self.swapMode == 'push': self.lines[1-i].setValue(self.lines[i].value()) self.prepareGeometryChange() self.sigRegionChanged.emit(self) def lineMoveFinished(self): self.sigRegionChangeFinished.emit(self) def mouseDragEvent(self, ev): if not self.movable or int(ev.button() & QtCore.Qt.LeftButton) == 0: return ev.accept() if ev.isStart(): bdp = ev.buttonDownPos() self.cursorOffsets = [l.pos() - bdp for l in self.lines] self.startPositions = [l.pos() for l in self.lines] self.moving = True if not self.moving: return self.lines[0].blockSignals(True) # only want to update once for i, l in enumerate(self.lines): l.setPos(self.cursorOffsets[i] + ev.pos()) self.lines[0].blockSignals(False) self.prepareGeometryChange() if ev.isFinish(): self.moving = False self.sigRegionChangeFinished.emit(self) else: self.sigRegionChanged.emit(self) def mouseClickEvent(self, ev): if self.moving and ev.button() == QtCore.Qt.RightButton: ev.accept() for i, l in enumerate(self.lines): l.setPos(self.startPositions[i]) self.moving = False self.sigRegionChanged.emit(self) self.sigRegionChangeFinished.emit(self) def hoverEvent(self, ev): if self.movable and (not ev.isExit()) and ev.acceptDrags(QtCore.Qt.LeftButton): self.setMouseHover(True) else: self.setMouseHover(False) def setMouseHover(self, hover): ## Inform the item that the mouse is(not) hovering over it if self.mouseHovering == hover: return self.mouseHovering = hover if hover: self.currentBrush = self.hoverBrush else: self.currentBrush = self.brush self.update()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/ErrorBarItem.py
.py
5,126
153
from ..Qt import QtGui, QtCore from .GraphicsObject import GraphicsObject from .. import getConfigOption from .. import functions as fn __all__ = ['ErrorBarItem'] class ErrorBarItem(GraphicsObject): def __init__(self, **opts): """ All keyword arguments are passed to setData(). """ GraphicsObject.__init__(self) self.opts = dict( x=None, y=None, height=None, width=None, top=None, bottom=None, left=None, right=None, beam=None, pen=None ) self.setVisible(False) self.setData(**opts) def setData(self, **opts): """ Update the data in the item. All arguments are optional. Valid keyword options are: x, y, height, width, top, bottom, left, right, beam, pen * x and y must be numpy arrays specifying the coordinates of data points. * height, width, top, bottom, left, right, and beam may be numpy arrays, single values, or None to disable. All values should be positive. * top, bottom, left, and right specify the lengths of bars extending in each direction. * If height is specified, it overrides top and bottom. * If width is specified, it overrides left and right. * beam specifies the width of the beam at the end of each bar. * pen may be any single argument accepted by pg.mkPen(). This method was added in version 0.9.9. For prior versions, use setOpts. """ self.opts.update(opts) self.setVisible(all(self.opts[ax] is not None for ax in ['x', 'y'])) self.path = None self.update() self.prepareGeometryChange() self.informViewBoundsChanged() def setOpts(self, **opts): # for backward compatibility self.setData(**opts) def drawPath(self): p = QtGui.QPainterPath() x, y = self.opts['x'], self.opts['y'] if x is None or y is None: self.path = p return beam = self.opts['beam'] height, top, bottom = self.opts['height'], self.opts['top'], self.opts['bottom'] if height is not None or top is not None or bottom is not None: ## draw vertical error bars if height is not None: y1 = y - height/2. y2 = y + height/2. else: if bottom is None: y1 = y else: y1 = y - bottom if top is None: y2 = y else: y2 = y + top for i in range(len(x)): p.moveTo(x[i], y1[i]) p.lineTo(x[i], y2[i]) if beam is not None and beam > 0: x1 = x - beam/2. x2 = x + beam/2. if height is not None or top is not None: for i in range(len(x)): p.moveTo(x1[i], y2[i]) p.lineTo(x2[i], y2[i]) if height is not None or bottom is not None: for i in range(len(x)): p.moveTo(x1[i], y1[i]) p.lineTo(x2[i], y1[i]) width, right, left = self.opts['width'], self.opts['right'], self.opts['left'] if width is not None or right is not None or left is not None: ## draw vertical error bars if width is not None: x1 = x - width/2. x2 = x + width/2. else: if left is None: x1 = x else: x1 = x - left if right is None: x2 = x else: x2 = x + right for i in range(len(x)): p.moveTo(x1[i], y[i]) p.lineTo(x2[i], y[i]) if beam is not None and beam > 0: y1 = y - beam/2. y2 = y + beam/2. if width is not None or right is not None: for i in range(len(x)): p.moveTo(x2[i], y1[i]) p.lineTo(x2[i], y2[i]) if width is not None or left is not None: for i in range(len(x)): p.moveTo(x1[i], y1[i]) p.lineTo(x1[i], y2[i]) self.path = p self.prepareGeometryChange() def paint(self, p, *args): if self.path is None: self.drawPath() pen = self.opts['pen'] if pen is None: pen = getConfigOption('foreground') p.setPen(fn.mkPen(pen)) p.drawPath(self.path) def boundingRect(self): if self.path is None: self.drawPath() return self.path.boundingRect()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/PlotItem/plotConfigTemplate_pyside2.py
.py
10,668
170
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file './pyqtgraph/graphicsItems/PlotItem/plotConfigTemplate.ui' # # Created: Wed Mar 26 15:09:28 2014 # by: PyQt5 UI code generator 5.0.1 # # WARNING! All changes made in this file will be lost! from PySide2 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(481, 840) self.averageGroup = QtWidgets.QGroupBox(Form) self.averageGroup.setGeometry(QtCore.QRect(0, 640, 242, 182)) self.averageGroup.setCheckable(True) self.averageGroup.setChecked(False) self.averageGroup.setObjectName("averageGroup") self.gridLayout_5 = QtWidgets.QGridLayout(self.averageGroup) self.gridLayout_5.setContentsMargins(0, 0, 0, 0) self.gridLayout_5.setSpacing(0) self.gridLayout_5.setObjectName("gridLayout_5") self.avgParamList = QtWidgets.QListWidget(self.averageGroup) self.avgParamList.setObjectName("avgParamList") self.gridLayout_5.addWidget(self.avgParamList, 0, 0, 1, 1) self.decimateGroup = QtWidgets.QFrame(Form) self.decimateGroup.setGeometry(QtCore.QRect(10, 140, 191, 171)) self.decimateGroup.setObjectName("decimateGroup") self.gridLayout_4 = QtWidgets.QGridLayout(self.decimateGroup) self.gridLayout_4.setContentsMargins(0, 0, 0, 0) self.gridLayout_4.setSpacing(0) self.gridLayout_4.setObjectName("gridLayout_4") self.clipToViewCheck = QtWidgets.QCheckBox(self.decimateGroup) self.clipToViewCheck.setObjectName("clipToViewCheck") self.gridLayout_4.addWidget(self.clipToViewCheck, 7, 0, 1, 3) self.maxTracesCheck = QtWidgets.QCheckBox(self.decimateGroup) self.maxTracesCheck.setObjectName("maxTracesCheck") self.gridLayout_4.addWidget(self.maxTracesCheck, 8, 0, 1, 2) self.downsampleCheck = QtWidgets.QCheckBox(self.decimateGroup) self.downsampleCheck.setObjectName("downsampleCheck") self.gridLayout_4.addWidget(self.downsampleCheck, 0, 0, 1, 3) self.peakRadio = QtWidgets.QRadioButton(self.decimateGroup) self.peakRadio.setChecked(True) self.peakRadio.setObjectName("peakRadio") self.gridLayout_4.addWidget(self.peakRadio, 6, 1, 1, 2) self.maxTracesSpin = QtWidgets.QSpinBox(self.decimateGroup) self.maxTracesSpin.setObjectName("maxTracesSpin") self.gridLayout_4.addWidget(self.maxTracesSpin, 8, 2, 1, 1) self.forgetTracesCheck = QtWidgets.QCheckBox(self.decimateGroup) self.forgetTracesCheck.setObjectName("forgetTracesCheck") self.gridLayout_4.addWidget(self.forgetTracesCheck, 9, 0, 1, 3) self.meanRadio = QtWidgets.QRadioButton(self.decimateGroup) self.meanRadio.setObjectName("meanRadio") self.gridLayout_4.addWidget(self.meanRadio, 3, 1, 1, 2) self.subsampleRadio = QtWidgets.QRadioButton(self.decimateGroup) self.subsampleRadio.setObjectName("subsampleRadio") self.gridLayout_4.addWidget(self.subsampleRadio, 2, 1, 1, 2) self.autoDownsampleCheck = QtWidgets.QCheckBox(self.decimateGroup) self.autoDownsampleCheck.setChecked(True) self.autoDownsampleCheck.setObjectName("autoDownsampleCheck") self.gridLayout_4.addWidget(self.autoDownsampleCheck, 1, 2, 1, 1) spacerItem = QtWidgets.QSpacerItem(30, 20, QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Minimum) self.gridLayout_4.addItem(spacerItem, 2, 0, 1, 1) self.downsampleSpin = QtWidgets.QSpinBox(self.decimateGroup) self.downsampleSpin.setMinimum(1) self.downsampleSpin.setMaximum(100000) self.downsampleSpin.setProperty("value", 1) self.downsampleSpin.setObjectName("downsampleSpin") self.gridLayout_4.addWidget(self.downsampleSpin, 1, 1, 1, 1) self.transformGroup = QtWidgets.QFrame(Form) self.transformGroup.setGeometry(QtCore.QRect(0, 0, 154, 79)) self.transformGroup.setObjectName("transformGroup") self.gridLayout = QtWidgets.QGridLayout(self.transformGroup) self.gridLayout.setObjectName("gridLayout") self.fftCheck = QtWidgets.QCheckBox(self.transformGroup) self.fftCheck.setObjectName("fftCheck") self.gridLayout.addWidget(self.fftCheck, 0, 0, 1, 1) self.logXCheck = QtWidgets.QCheckBox(self.transformGroup) self.logXCheck.setObjectName("logXCheck") self.gridLayout.addWidget(self.logXCheck, 1, 0, 1, 1) self.logYCheck = QtWidgets.QCheckBox(self.transformGroup) self.logYCheck.setObjectName("logYCheck") self.gridLayout.addWidget(self.logYCheck, 2, 0, 1, 1) self.pointsGroup = QtWidgets.QGroupBox(Form) self.pointsGroup.setGeometry(QtCore.QRect(10, 550, 234, 58)) self.pointsGroup.setCheckable(True) self.pointsGroup.setObjectName("pointsGroup") self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.pointsGroup) self.verticalLayout_5.setObjectName("verticalLayout_5") self.autoPointsCheck = QtWidgets.QCheckBox(self.pointsGroup) self.autoPointsCheck.setChecked(True) self.autoPointsCheck.setObjectName("autoPointsCheck") self.verticalLayout_5.addWidget(self.autoPointsCheck) self.gridGroup = QtWidgets.QFrame(Form) self.gridGroup.setGeometry(QtCore.QRect(10, 460, 221, 81)) self.gridGroup.setObjectName("gridGroup") self.gridLayout_2 = QtWidgets.QGridLayout(self.gridGroup) self.gridLayout_2.setObjectName("gridLayout_2") self.xGridCheck = QtWidgets.QCheckBox(self.gridGroup) self.xGridCheck.setObjectName("xGridCheck") self.gridLayout_2.addWidget(self.xGridCheck, 0, 0, 1, 2) self.yGridCheck = QtWidgets.QCheckBox(self.gridGroup) self.yGridCheck.setObjectName("yGridCheck") self.gridLayout_2.addWidget(self.yGridCheck, 1, 0, 1, 2) self.gridAlphaSlider = QtWidgets.QSlider(self.gridGroup) self.gridAlphaSlider.setMaximum(255) self.gridAlphaSlider.setProperty("value", 128) self.gridAlphaSlider.setOrientation(QtCore.Qt.Horizontal) self.gridAlphaSlider.setObjectName("gridAlphaSlider") self.gridLayout_2.addWidget(self.gridAlphaSlider, 2, 1, 1, 1) self.label = QtWidgets.QLabel(self.gridGroup) self.label.setObjectName("label") self.gridLayout_2.addWidget(self.label, 2, 0, 1, 1) self.alphaGroup = QtWidgets.QGroupBox(Form) self.alphaGroup.setGeometry(QtCore.QRect(10, 390, 234, 60)) self.alphaGroup.setCheckable(True) self.alphaGroup.setObjectName("alphaGroup") self.horizontalLayout = QtWidgets.QHBoxLayout(self.alphaGroup) self.horizontalLayout.setObjectName("horizontalLayout") self.autoAlphaCheck = QtWidgets.QCheckBox(self.alphaGroup) self.autoAlphaCheck.setChecked(False) self.autoAlphaCheck.setObjectName("autoAlphaCheck") self.horizontalLayout.addWidget(self.autoAlphaCheck) self.alphaSlider = QtWidgets.QSlider(self.alphaGroup) self.alphaSlider.setMaximum(1000) self.alphaSlider.setProperty("value", 1000) self.alphaSlider.setOrientation(QtCore.Qt.Horizontal) self.alphaSlider.setObjectName("alphaSlider") self.horizontalLayout.addWidget(self.alphaSlider) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Form")) self.averageGroup.setToolTip(_translate("Form", "Display averages of the curves displayed in this plot. The parameter list allows you to choose parameters to average over (if any are available).")) self.averageGroup.setTitle(_translate("Form", "Average")) self.clipToViewCheck.setToolTip(_translate("Form", "Plot only the portion of each curve that is visible. This assumes X values are uniformly spaced.")) self.clipToViewCheck.setText(_translate("Form", "Clip to View")) self.maxTracesCheck.setToolTip(_translate("Form", "If multiple curves are displayed in this plot, check this box to limit the number of traces that are displayed.")) self.maxTracesCheck.setText(_translate("Form", "Max Traces:")) self.downsampleCheck.setText(_translate("Form", "Downsample")) self.peakRadio.setToolTip(_translate("Form", "Downsample by drawing a saw wave that follows the min and max of the original data. This method produces the best visual representation of the data but is slower.")) self.peakRadio.setText(_translate("Form", "Peak")) self.maxTracesSpin.setToolTip(_translate("Form", "If multiple curves are displayed in this plot, check \"Max Traces\" and set this value to limit the number of traces that are displayed.")) self.forgetTracesCheck.setToolTip(_translate("Form", "If MaxTraces is checked, remove curves from memory after they are hidden (saves memory, but traces can not be un-hidden).")) self.forgetTracesCheck.setText(_translate("Form", "Forget hidden traces")) self.meanRadio.setToolTip(_translate("Form", "Downsample by taking the mean of N samples.")) self.meanRadio.setText(_translate("Form", "Mean")) self.subsampleRadio.setToolTip(_translate("Form", "Downsample by taking the first of N samples. This method is fastest and least accurate.")) self.subsampleRadio.setText(_translate("Form", "Subsample")) self.autoDownsampleCheck.setToolTip(_translate("Form", "Automatically downsample data based on the visible range. This assumes X values are uniformly spaced.")) self.autoDownsampleCheck.setText(_translate("Form", "Auto")) self.downsampleSpin.setToolTip(_translate("Form", "Downsample data before plotting. (plot every Nth sample)")) self.downsampleSpin.setSuffix(_translate("Form", "x")) self.fftCheck.setText(_translate("Form", "Power Spectrum (FFT)")) self.logXCheck.setText(_translate("Form", "Log X")) self.logYCheck.setText(_translate("Form", "Log Y")) self.pointsGroup.setTitle(_translate("Form", "Points")) self.autoPointsCheck.setText(_translate("Form", "Auto")) self.xGridCheck.setText(_translate("Form", "Show X Grid")) self.yGridCheck.setText(_translate("Form", "Show Y Grid")) self.label.setText(_translate("Form", "Opacity")) self.alphaGroup.setTitle(_translate("Form", "Alpha")) self.autoAlphaCheck.setText(_translate("Form", "Auto"))
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/PlotItem/plotConfigTemplate_pyqt5.py
.py
10,666
170
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file './pyqtgraph/graphicsItems/PlotItem/plotConfigTemplate.ui' # # Created: Wed Mar 26 15:09:28 2014 # by: PyQt5 UI code generator 5.0.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(481, 840) self.averageGroup = QtWidgets.QGroupBox(Form) self.averageGroup.setGeometry(QtCore.QRect(0, 640, 242, 182)) self.averageGroup.setCheckable(True) self.averageGroup.setChecked(False) self.averageGroup.setObjectName("averageGroup") self.gridLayout_5 = QtWidgets.QGridLayout(self.averageGroup) self.gridLayout_5.setContentsMargins(0, 0, 0, 0) self.gridLayout_5.setSpacing(0) self.gridLayout_5.setObjectName("gridLayout_5") self.avgParamList = QtWidgets.QListWidget(self.averageGroup) self.avgParamList.setObjectName("avgParamList") self.gridLayout_5.addWidget(self.avgParamList, 0, 0, 1, 1) self.decimateGroup = QtWidgets.QFrame(Form) self.decimateGroup.setGeometry(QtCore.QRect(10, 140, 191, 171)) self.decimateGroup.setObjectName("decimateGroup") self.gridLayout_4 = QtWidgets.QGridLayout(self.decimateGroup) self.gridLayout_4.setContentsMargins(0, 0, 0, 0) self.gridLayout_4.setSpacing(0) self.gridLayout_4.setObjectName("gridLayout_4") self.clipToViewCheck = QtWidgets.QCheckBox(self.decimateGroup) self.clipToViewCheck.setObjectName("clipToViewCheck") self.gridLayout_4.addWidget(self.clipToViewCheck, 7, 0, 1, 3) self.maxTracesCheck = QtWidgets.QCheckBox(self.decimateGroup) self.maxTracesCheck.setObjectName("maxTracesCheck") self.gridLayout_4.addWidget(self.maxTracesCheck, 8, 0, 1, 2) self.downsampleCheck = QtWidgets.QCheckBox(self.decimateGroup) self.downsampleCheck.setObjectName("downsampleCheck") self.gridLayout_4.addWidget(self.downsampleCheck, 0, 0, 1, 3) self.peakRadio = QtWidgets.QRadioButton(self.decimateGroup) self.peakRadio.setChecked(True) self.peakRadio.setObjectName("peakRadio") self.gridLayout_4.addWidget(self.peakRadio, 6, 1, 1, 2) self.maxTracesSpin = QtWidgets.QSpinBox(self.decimateGroup) self.maxTracesSpin.setObjectName("maxTracesSpin") self.gridLayout_4.addWidget(self.maxTracesSpin, 8, 2, 1, 1) self.forgetTracesCheck = QtWidgets.QCheckBox(self.decimateGroup) self.forgetTracesCheck.setObjectName("forgetTracesCheck") self.gridLayout_4.addWidget(self.forgetTracesCheck, 9, 0, 1, 3) self.meanRadio = QtWidgets.QRadioButton(self.decimateGroup) self.meanRadio.setObjectName("meanRadio") self.gridLayout_4.addWidget(self.meanRadio, 3, 1, 1, 2) self.subsampleRadio = QtWidgets.QRadioButton(self.decimateGroup) self.subsampleRadio.setObjectName("subsampleRadio") self.gridLayout_4.addWidget(self.subsampleRadio, 2, 1, 1, 2) self.autoDownsampleCheck = QtWidgets.QCheckBox(self.decimateGroup) self.autoDownsampleCheck.setChecked(True) self.autoDownsampleCheck.setObjectName("autoDownsampleCheck") self.gridLayout_4.addWidget(self.autoDownsampleCheck, 1, 2, 1, 1) spacerItem = QtWidgets.QSpacerItem(30, 20, QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Minimum) self.gridLayout_4.addItem(spacerItem, 2, 0, 1, 1) self.downsampleSpin = QtWidgets.QSpinBox(self.decimateGroup) self.downsampleSpin.setMinimum(1) self.downsampleSpin.setMaximum(100000) self.downsampleSpin.setProperty("value", 1) self.downsampleSpin.setObjectName("downsampleSpin") self.gridLayout_4.addWidget(self.downsampleSpin, 1, 1, 1, 1) self.transformGroup = QtWidgets.QFrame(Form) self.transformGroup.setGeometry(QtCore.QRect(0, 0, 154, 79)) self.transformGroup.setObjectName("transformGroup") self.gridLayout = QtWidgets.QGridLayout(self.transformGroup) self.gridLayout.setObjectName("gridLayout") self.fftCheck = QtWidgets.QCheckBox(self.transformGroup) self.fftCheck.setObjectName("fftCheck") self.gridLayout.addWidget(self.fftCheck, 0, 0, 1, 1) self.logXCheck = QtWidgets.QCheckBox(self.transformGroup) self.logXCheck.setObjectName("logXCheck") self.gridLayout.addWidget(self.logXCheck, 1, 0, 1, 1) self.logYCheck = QtWidgets.QCheckBox(self.transformGroup) self.logYCheck.setObjectName("logYCheck") self.gridLayout.addWidget(self.logYCheck, 2, 0, 1, 1) self.pointsGroup = QtWidgets.QGroupBox(Form) self.pointsGroup.setGeometry(QtCore.QRect(10, 550, 234, 58)) self.pointsGroup.setCheckable(True) self.pointsGroup.setObjectName("pointsGroup") self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.pointsGroup) self.verticalLayout_5.setObjectName("verticalLayout_5") self.autoPointsCheck = QtWidgets.QCheckBox(self.pointsGroup) self.autoPointsCheck.setChecked(True) self.autoPointsCheck.setObjectName("autoPointsCheck") self.verticalLayout_5.addWidget(self.autoPointsCheck) self.gridGroup = QtWidgets.QFrame(Form) self.gridGroup.setGeometry(QtCore.QRect(10, 460, 221, 81)) self.gridGroup.setObjectName("gridGroup") self.gridLayout_2 = QtWidgets.QGridLayout(self.gridGroup) self.gridLayout_2.setObjectName("gridLayout_2") self.xGridCheck = QtWidgets.QCheckBox(self.gridGroup) self.xGridCheck.setObjectName("xGridCheck") self.gridLayout_2.addWidget(self.xGridCheck, 0, 0, 1, 2) self.yGridCheck = QtWidgets.QCheckBox(self.gridGroup) self.yGridCheck.setObjectName("yGridCheck") self.gridLayout_2.addWidget(self.yGridCheck, 1, 0, 1, 2) self.gridAlphaSlider = QtWidgets.QSlider(self.gridGroup) self.gridAlphaSlider.setMaximum(255) self.gridAlphaSlider.setProperty("value", 128) self.gridAlphaSlider.setOrientation(QtCore.Qt.Horizontal) self.gridAlphaSlider.setObjectName("gridAlphaSlider") self.gridLayout_2.addWidget(self.gridAlphaSlider, 2, 1, 1, 1) self.label = QtWidgets.QLabel(self.gridGroup) self.label.setObjectName("label") self.gridLayout_2.addWidget(self.label, 2, 0, 1, 1) self.alphaGroup = QtWidgets.QGroupBox(Form) self.alphaGroup.setGeometry(QtCore.QRect(10, 390, 234, 60)) self.alphaGroup.setCheckable(True) self.alphaGroup.setObjectName("alphaGroup") self.horizontalLayout = QtWidgets.QHBoxLayout(self.alphaGroup) self.horizontalLayout.setObjectName("horizontalLayout") self.autoAlphaCheck = QtWidgets.QCheckBox(self.alphaGroup) self.autoAlphaCheck.setChecked(False) self.autoAlphaCheck.setObjectName("autoAlphaCheck") self.horizontalLayout.addWidget(self.autoAlphaCheck) self.alphaSlider = QtWidgets.QSlider(self.alphaGroup) self.alphaSlider.setMaximum(1000) self.alphaSlider.setProperty("value", 1000) self.alphaSlider.setOrientation(QtCore.Qt.Horizontal) self.alphaSlider.setObjectName("alphaSlider") self.horizontalLayout.addWidget(self.alphaSlider) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Form")) self.averageGroup.setToolTip(_translate("Form", "Display averages of the curves displayed in this plot. The parameter list allows you to choose parameters to average over (if any are available).")) self.averageGroup.setTitle(_translate("Form", "Average")) self.clipToViewCheck.setToolTip(_translate("Form", "Plot only the portion of each curve that is visible. This assumes X values are uniformly spaced.")) self.clipToViewCheck.setText(_translate("Form", "Clip to View")) self.maxTracesCheck.setToolTip(_translate("Form", "If multiple curves are displayed in this plot, check this box to limit the number of traces that are displayed.")) self.maxTracesCheck.setText(_translate("Form", "Max Traces:")) self.downsampleCheck.setText(_translate("Form", "Downsample")) self.peakRadio.setToolTip(_translate("Form", "Downsample by drawing a saw wave that follows the min and max of the original data. This method produces the best visual representation of the data but is slower.")) self.peakRadio.setText(_translate("Form", "Peak")) self.maxTracesSpin.setToolTip(_translate("Form", "If multiple curves are displayed in this plot, check \"Max Traces\" and set this value to limit the number of traces that are displayed.")) self.forgetTracesCheck.setToolTip(_translate("Form", "If MaxTraces is checked, remove curves from memory after they are hidden (saves memory, but traces can not be un-hidden).")) self.forgetTracesCheck.setText(_translate("Form", "Forget hidden traces")) self.meanRadio.setToolTip(_translate("Form", "Downsample by taking the mean of N samples.")) self.meanRadio.setText(_translate("Form", "Mean")) self.subsampleRadio.setToolTip(_translate("Form", "Downsample by taking the first of N samples. This method is fastest and least accurate.")) self.subsampleRadio.setText(_translate("Form", "Subsample")) self.autoDownsampleCheck.setToolTip(_translate("Form", "Automatically downsample data based on the visible range. This assumes X values are uniformly spaced.")) self.autoDownsampleCheck.setText(_translate("Form", "Auto")) self.downsampleSpin.setToolTip(_translate("Form", "Downsample data before plotting. (plot every Nth sample)")) self.downsampleSpin.setSuffix(_translate("Form", "x")) self.fftCheck.setText(_translate("Form", "Power Spectrum (FFT)")) self.logXCheck.setText(_translate("Form", "Log X")) self.logYCheck.setText(_translate("Form", "Log Y")) self.pointsGroup.setTitle(_translate("Form", "Points")) self.autoPointsCheck.setText(_translate("Form", "Auto")) self.xGridCheck.setText(_translate("Form", "Show X Grid")) self.yGridCheck.setText(_translate("Form", "Show Y Grid")) self.label.setText(_translate("Form", "Opacity")) self.alphaGroup.setTitle(_translate("Form", "Alpha")) self.autoAlphaCheck.setText(_translate("Form", "Auto"))
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/PlotItem/plotConfigTemplate_pyqt.py
.py
11,402
183
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file './pyqtgraph/graphicsItems/PlotItem/plotConfigTemplate.ui' # # Created: Mon Dec 23 10:10:51 2013 # by: PyQt4 UI code generator 4.10 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(481, 840) self.averageGroup = QtGui.QGroupBox(Form) self.averageGroup.setGeometry(QtCore.QRect(0, 640, 242, 182)) self.averageGroup.setCheckable(True) self.averageGroup.setChecked(False) self.averageGroup.setObjectName(_fromUtf8("averageGroup")) self.gridLayout_5 = QtGui.QGridLayout(self.averageGroup) self.gridLayout_5.setMargin(0) self.gridLayout_5.setSpacing(0) self.gridLayout_5.setObjectName(_fromUtf8("gridLayout_5")) self.avgParamList = QtGui.QListWidget(self.averageGroup) self.avgParamList.setObjectName(_fromUtf8("avgParamList")) self.gridLayout_5.addWidget(self.avgParamList, 0, 0, 1, 1) self.decimateGroup = QtGui.QFrame(Form) self.decimateGroup.setGeometry(QtCore.QRect(10, 140, 191, 171)) self.decimateGroup.setObjectName(_fromUtf8("decimateGroup")) self.gridLayout_4 = QtGui.QGridLayout(self.decimateGroup) self.gridLayout_4.setMargin(0) self.gridLayout_4.setSpacing(0) self.gridLayout_4.setObjectName(_fromUtf8("gridLayout_4")) self.clipToViewCheck = QtGui.QCheckBox(self.decimateGroup) self.clipToViewCheck.setObjectName(_fromUtf8("clipToViewCheck")) self.gridLayout_4.addWidget(self.clipToViewCheck, 7, 0, 1, 3) self.maxTracesCheck = QtGui.QCheckBox(self.decimateGroup) self.maxTracesCheck.setObjectName(_fromUtf8("maxTracesCheck")) self.gridLayout_4.addWidget(self.maxTracesCheck, 8, 0, 1, 2) self.downsampleCheck = QtGui.QCheckBox(self.decimateGroup) self.downsampleCheck.setObjectName(_fromUtf8("downsampleCheck")) self.gridLayout_4.addWidget(self.downsampleCheck, 0, 0, 1, 3) self.peakRadio = QtGui.QRadioButton(self.decimateGroup) self.peakRadio.setChecked(True) self.peakRadio.setObjectName(_fromUtf8("peakRadio")) self.gridLayout_4.addWidget(self.peakRadio, 6, 1, 1, 2) self.maxTracesSpin = QtGui.QSpinBox(self.decimateGroup) self.maxTracesSpin.setObjectName(_fromUtf8("maxTracesSpin")) self.gridLayout_4.addWidget(self.maxTracesSpin, 8, 2, 1, 1) self.forgetTracesCheck = QtGui.QCheckBox(self.decimateGroup) self.forgetTracesCheck.setObjectName(_fromUtf8("forgetTracesCheck")) self.gridLayout_4.addWidget(self.forgetTracesCheck, 9, 0, 1, 3) self.meanRadio = QtGui.QRadioButton(self.decimateGroup) self.meanRadio.setObjectName(_fromUtf8("meanRadio")) self.gridLayout_4.addWidget(self.meanRadio, 3, 1, 1, 2) self.subsampleRadio = QtGui.QRadioButton(self.decimateGroup) self.subsampleRadio.setObjectName(_fromUtf8("subsampleRadio")) self.gridLayout_4.addWidget(self.subsampleRadio, 2, 1, 1, 2) self.autoDownsampleCheck = QtGui.QCheckBox(self.decimateGroup) self.autoDownsampleCheck.setChecked(True) self.autoDownsampleCheck.setObjectName(_fromUtf8("autoDownsampleCheck")) self.gridLayout_4.addWidget(self.autoDownsampleCheck, 1, 2, 1, 1) spacerItem = QtGui.QSpacerItem(30, 20, QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Minimum) self.gridLayout_4.addItem(spacerItem, 2, 0, 1, 1) self.downsampleSpin = QtGui.QSpinBox(self.decimateGroup) self.downsampleSpin.setMinimum(1) self.downsampleSpin.setMaximum(100000) self.downsampleSpin.setProperty("value", 1) self.downsampleSpin.setObjectName(_fromUtf8("downsampleSpin")) self.gridLayout_4.addWidget(self.downsampleSpin, 1, 1, 1, 1) self.transformGroup = QtGui.QFrame(Form) self.transformGroup.setGeometry(QtCore.QRect(0, 0, 154, 79)) self.transformGroup.setObjectName(_fromUtf8("transformGroup")) self.gridLayout = QtGui.QGridLayout(self.transformGroup) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.fftCheck = QtGui.QCheckBox(self.transformGroup) self.fftCheck.setObjectName(_fromUtf8("fftCheck")) self.gridLayout.addWidget(self.fftCheck, 0, 0, 1, 1) self.logXCheck = QtGui.QCheckBox(self.transformGroup) self.logXCheck.setObjectName(_fromUtf8("logXCheck")) self.gridLayout.addWidget(self.logXCheck, 1, 0, 1, 1) self.logYCheck = QtGui.QCheckBox(self.transformGroup) self.logYCheck.setObjectName(_fromUtf8("logYCheck")) self.gridLayout.addWidget(self.logYCheck, 2, 0, 1, 1) self.pointsGroup = QtGui.QGroupBox(Form) self.pointsGroup.setGeometry(QtCore.QRect(10, 550, 234, 58)) self.pointsGroup.setCheckable(True) self.pointsGroup.setObjectName(_fromUtf8("pointsGroup")) self.verticalLayout_5 = QtGui.QVBoxLayout(self.pointsGroup) self.verticalLayout_5.setObjectName(_fromUtf8("verticalLayout_5")) self.autoPointsCheck = QtGui.QCheckBox(self.pointsGroup) self.autoPointsCheck.setChecked(True) self.autoPointsCheck.setObjectName(_fromUtf8("autoPointsCheck")) self.verticalLayout_5.addWidget(self.autoPointsCheck) self.gridGroup = QtGui.QFrame(Form) self.gridGroup.setGeometry(QtCore.QRect(10, 460, 221, 81)) self.gridGroup.setObjectName(_fromUtf8("gridGroup")) self.gridLayout_2 = QtGui.QGridLayout(self.gridGroup) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.xGridCheck = QtGui.QCheckBox(self.gridGroup) self.xGridCheck.setObjectName(_fromUtf8("xGridCheck")) self.gridLayout_2.addWidget(self.xGridCheck, 0, 0, 1, 2) self.yGridCheck = QtGui.QCheckBox(self.gridGroup) self.yGridCheck.setObjectName(_fromUtf8("yGridCheck")) self.gridLayout_2.addWidget(self.yGridCheck, 1, 0, 1, 2) self.gridAlphaSlider = QtGui.QSlider(self.gridGroup) self.gridAlphaSlider.setMaximum(255) self.gridAlphaSlider.setProperty("value", 128) self.gridAlphaSlider.setOrientation(QtCore.Qt.Horizontal) self.gridAlphaSlider.setObjectName(_fromUtf8("gridAlphaSlider")) self.gridLayout_2.addWidget(self.gridAlphaSlider, 2, 1, 1, 1) self.label = QtGui.QLabel(self.gridGroup) self.label.setObjectName(_fromUtf8("label")) self.gridLayout_2.addWidget(self.label, 2, 0, 1, 1) self.alphaGroup = QtGui.QGroupBox(Form) self.alphaGroup.setGeometry(QtCore.QRect(10, 390, 234, 60)) self.alphaGroup.setCheckable(True) self.alphaGroup.setObjectName(_fromUtf8("alphaGroup")) self.horizontalLayout = QtGui.QHBoxLayout(self.alphaGroup) self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.autoAlphaCheck = QtGui.QCheckBox(self.alphaGroup) self.autoAlphaCheck.setChecked(False) self.autoAlphaCheck.setObjectName(_fromUtf8("autoAlphaCheck")) self.horizontalLayout.addWidget(self.autoAlphaCheck) self.alphaSlider = QtGui.QSlider(self.alphaGroup) self.alphaSlider.setMaximum(1000) self.alphaSlider.setProperty("value", 1000) self.alphaSlider.setOrientation(QtCore.Qt.Horizontal) self.alphaSlider.setObjectName(_fromUtf8("alphaSlider")) self.horizontalLayout.addWidget(self.alphaSlider) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(_translate("Form", "Form", None)) self.averageGroup.setToolTip(_translate("Form", "Display averages of the curves displayed in this plot. The parameter list allows you to choose parameters to average over (if any are available).", None)) self.averageGroup.setTitle(_translate("Form", "Average", None)) self.clipToViewCheck.setToolTip(_translate("Form", "Plot only the portion of each curve that is visible. This assumes X values are uniformly spaced.", None)) self.clipToViewCheck.setText(_translate("Form", "Clip to View", None)) self.maxTracesCheck.setToolTip(_translate("Form", "If multiple curves are displayed in this plot, check this box to limit the number of traces that are displayed.", None)) self.maxTracesCheck.setText(_translate("Form", "Max Traces:", None)) self.downsampleCheck.setText(_translate("Form", "Downsample", None)) self.peakRadio.setToolTip(_translate("Form", "Downsample by drawing a saw wave that follows the min and max of the original data. This method produces the best visual representation of the data but is slower.", None)) self.peakRadio.setText(_translate("Form", "Peak", None)) self.maxTracesSpin.setToolTip(_translate("Form", "If multiple curves are displayed in this plot, check \"Max Traces\" and set this value to limit the number of traces that are displayed.", None)) self.forgetTracesCheck.setToolTip(_translate("Form", "If MaxTraces is checked, remove curves from memory after they are hidden (saves memory, but traces can not be un-hidden).", None)) self.forgetTracesCheck.setText(_translate("Form", "Forget hidden traces", None)) self.meanRadio.setToolTip(_translate("Form", "Downsample by taking the mean of N samples.", None)) self.meanRadio.setText(_translate("Form", "Mean", None)) self.subsampleRadio.setToolTip(_translate("Form", "Downsample by taking the first of N samples. This method is fastest and least accurate.", None)) self.subsampleRadio.setText(_translate("Form", "Subsample", None)) self.autoDownsampleCheck.setToolTip(_translate("Form", "Automatically downsample data based on the visible range. This assumes X values are uniformly spaced.", None)) self.autoDownsampleCheck.setText(_translate("Form", "Auto", None)) self.downsampleSpin.setToolTip(_translate("Form", "Downsample data before plotting. (plot every Nth sample)", None)) self.downsampleSpin.setSuffix(_translate("Form", "x", None)) self.fftCheck.setText(_translate("Form", "Power Spectrum (FFT)", None)) self.logXCheck.setText(_translate("Form", "Log X", None)) self.logYCheck.setText(_translate("Form", "Log Y", None)) self.pointsGroup.setTitle(_translate("Form", "Points", None)) self.autoPointsCheck.setText(_translate("Form", "Auto", None)) self.xGridCheck.setText(_translate("Form", "Show X Grid", None)) self.yGridCheck.setText(_translate("Form", "Show Y Grid", None)) self.label.setText(_translate("Form", "Opacity", None)) self.alphaGroup.setTitle(_translate("Form", "Alpha", None)) self.autoAlphaCheck.setText(_translate("Form", "Auto", None))
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/PlotItem/__init__.py
.py
31
2
from .PlotItem import PlotItem
Python