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/graphicsItems/PlotItem/PlotItem.py | .py | 47,182 | 1,210 | # -*- coding: utf-8 -*-
import sys
import weakref
import numpy as np
import os
from ...Qt import QtGui, QtCore, QT_LIB
from ... import pixmaps
from ... import functions as fn
from ...widgets.FileDialog import FileDialog
from .. PlotDataItem import PlotDataItem
from .. ViewBox import ViewBox
from .. AxisItem import AxisItem
from .. LabelItem import LabelItem
from .. LegendItem import LegendItem
from .. GraphicsWidget import GraphicsWidget
from .. ButtonItem import ButtonItem
from .. InfiniteLine import InfiniteLine
from ...WidgetGroup import WidgetGroup
from ...python2_3 import basestring
if QT_LIB == 'PyQt4':
from .plotConfigTemplate_pyqt import *
elif QT_LIB == 'PySide':
from .plotConfigTemplate_pyside import *
elif QT_LIB == 'PyQt5':
from .plotConfigTemplate_pyqt5 import *
elif QT_LIB == 'PySide2':
from .plotConfigTemplate_pyside2 import *
__all__ = ['PlotItem']
try:
from metaarray import *
HAVE_METAARRAY = True
except:
HAVE_METAARRAY = False
class PlotItem(GraphicsWidget):
"""GraphicsWidget implementing a standard 2D plotting area with axes.
**Bases:** :class:`GraphicsWidget <pyqtgraph.GraphicsWidget>`
This class provides the ViewBox-plus-axes that appear when using
:func:`pg.plot() <pyqtgraph.plot>`, :class:`PlotWidget <pyqtgraph.PlotWidget>`,
and :func:`GraphicsLayoutWidget.addPlot() <pyqtgraph.GraphicsLayoutWidget.addPlot>`.
It's main functionality is:
- Manage placement of ViewBox, AxisItems, and LabelItems
- Create and manage a list of PlotDataItems displayed inside the ViewBox
- Implement a context menu with commonly used display and analysis options
Use :func:`plot() <pyqtgraph.PlotItem.plot>` to create a new PlotDataItem and
add it to the view. Use :func:`addItem() <pyqtgraph.PlotItem.addItem>` to
add any QGraphicsItem to the view.
This class wraps several methods from its internal ViewBox:
: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:`setAutoPan <pyqtgraph.ViewBox.setAutoPan>`,
:func:`setAutoVisible <pyqtgraph.ViewBox.setAutoVisible>`,
:func:`setLimits <pyqtgraph.ViewBox.setLimits>`,
:func:`viewRect <pyqtgraph.ViewBox.viewRect>`,
:func:`viewRange <pyqtgraph.ViewBox.viewRange>`,
:func:`setMouseEnabled <pyqtgraph.ViewBox.setMouseEnabled>`,
:func:`enableAutoRange <pyqtgraph.ViewBox.enableAutoRange>`,
:func:`disableAutoRange <pyqtgraph.ViewBox.disableAutoRange>`,
:func:`setAspectLocked <pyqtgraph.ViewBox.setAspectLocked>`,
:func:`invertY <pyqtgraph.ViewBox.invertY>`,
:func:`invertX <pyqtgraph.ViewBox.invertX>`,
:func:`register <pyqtgraph.ViewBox.register>`,
:func:`unregister <pyqtgraph.ViewBox.unregister>`
The ViewBox itself can be accessed by calling :func:`getViewBox() <pyqtgraph.PlotItem.getViewBox>`
==================== =======================================================================
**Signals:**
sigYRangeChanged wrapped from :class:`ViewBox <pyqtgraph.ViewBox>`
sigXRangeChanged wrapped from :class:`ViewBox <pyqtgraph.ViewBox>`
sigRangeChanged wrapped from :class:`ViewBox <pyqtgraph.ViewBox>`
==================== =======================================================================
"""
sigRangeChanged = QtCore.Signal(object, object) ## Emitted when the ViewBox range has changed
sigYRangeChanged = QtCore.Signal(object, object) ## Emitted when the ViewBox Y range has changed
sigXRangeChanged = QtCore.Signal(object, object) ## Emitted when the ViewBox X range has changed
lastFileDir = None
def __init__(self, parent=None, name=None, labels=None, title=None, viewBox=None, axisItems=None, enableMenu=True, **kargs):
"""
Create a new PlotItem. All arguments are optional.
Any extra keyword arguments are passed to :func:`PlotItem.plot() <pyqtgraph.PlotItem.plot>`.
============== ==========================================================================================
**Arguments:**
*title* Title to display at the top of the item. Html is allowed.
*labels* A dictionary specifying the axis labels to display::
{'left': (args), 'bottom': (args), ...}
The name of each axis and the corresponding arguments are passed to
:func:`PlotItem.setLabel() <pyqtgraph.PlotItem.setLabel>`
Optionally, PlotItem my also be initialized with the keyword arguments left,
right, top, or bottom to achieve the same effect.
*name* Registers a name for this view so that others may link to it
*viewBox* If specified, the PlotItem will be constructed with this as its ViewBox.
*axisItems* Optional dictionary instructing the PlotItem to use pre-constructed items
for its axes. The dict keys must be axis names ('left', 'bottom', 'right', 'top')
and the values must be instances of AxisItem (or at least compatible with AxisItem).
============== ==========================================================================================
"""
GraphicsWidget.__init__(self, parent)
self.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
## Set up control buttons
path = os.path.dirname(__file__)
self.autoBtn = ButtonItem(pixmaps.getPixmap('auto'), 14, self)
self.autoBtn.mode = 'auto'
self.autoBtn.clicked.connect(self.autoBtnClicked)
self.buttonsHidden = False ## whether the user has requested buttons to be hidden
self.mouseHovering = False
self.layout = QtGui.QGraphicsGridLayout()
self.layout.setContentsMargins(1,1,1,1)
self.setLayout(self.layout)
self.layout.setHorizontalSpacing(0)
self.layout.setVerticalSpacing(0)
if viewBox is None:
viewBox = ViewBox(parent=self)
self.vb = viewBox
self.vb.sigStateChanged.connect(self.viewStateChanged)
self.setMenuEnabled(enableMenu, enableMenu) ## en/disable plotitem and viewbox menus
if name is not None:
self.vb.register(name)
self.vb.sigRangeChanged.connect(self.sigRangeChanged)
self.vb.sigXRangeChanged.connect(self.sigXRangeChanged)
self.vb.sigYRangeChanged.connect(self.sigYRangeChanged)
self.layout.addItem(self.vb, 2, 1)
self.alpha = 1.0
self.autoAlpha = True
self.spectrumMode = False
self.legend = None
# Initialize axis items
self.axes = {}
self.setAxisItems(axisItems)
self.titleLabel = LabelItem('', size='11pt', parent=self)
self.layout.addItem(self.titleLabel, 0, 1)
self.setTitle(None) ## hide
for i in range(4):
self.layout.setRowPreferredHeight(i, 0)
self.layout.setRowMinimumHeight(i, 0)
self.layout.setRowSpacing(i, 0)
self.layout.setRowStretchFactor(i, 1)
for i in range(3):
self.layout.setColumnPreferredWidth(i, 0)
self.layout.setColumnMinimumWidth(i, 0)
self.layout.setColumnSpacing(i, 0)
self.layout.setColumnStretchFactor(i, 1)
self.layout.setRowStretchFactor(2, 100)
self.layout.setColumnStretchFactor(1, 100)
self.items = []
self.curves = []
self.itemMeta = weakref.WeakKeyDictionary()
self.dataItems = []
self.paramList = {}
self.avgCurves = {}
### Set up context menu
w = QtGui.QWidget()
self.ctrl = c = Ui_Form()
c.setupUi(w)
dv = QtGui.QDoubleValidator(self)
menuItems = [
('Transforms', c.transformGroup),
('Downsample', c.decimateGroup),
('Average', c.averageGroup),
('Alpha', c.alphaGroup),
('Grid', c.gridGroup),
('Points', c.pointsGroup),
]
self.ctrlMenu = QtGui.QMenu()
self.ctrlMenu.setTitle('Plot Options')
self.subMenus = []
for name, grp in menuItems:
sm = QtGui.QMenu(name)
act = QtGui.QWidgetAction(self)
act.setDefaultWidget(grp)
sm.addAction(act)
self.subMenus.append(sm)
self.ctrlMenu.addMenu(sm)
self.stateGroup = WidgetGroup()
for name, w in menuItems:
self.stateGroup.autoAdd(w)
self.fileDialog = None
c.alphaGroup.toggled.connect(self.updateAlpha)
c.alphaSlider.valueChanged.connect(self.updateAlpha)
c.autoAlphaCheck.toggled.connect(self.updateAlpha)
c.xGridCheck.toggled.connect(self.updateGrid)
c.yGridCheck.toggled.connect(self.updateGrid)
c.gridAlphaSlider.valueChanged.connect(self.updateGrid)
c.fftCheck.toggled.connect(self.updateSpectrumMode)
c.logXCheck.toggled.connect(self.updateLogMode)
c.logYCheck.toggled.connect(self.updateLogMode)
c.downsampleSpin.valueChanged.connect(self.updateDownsampling)
c.downsampleCheck.toggled.connect(self.updateDownsampling)
c.autoDownsampleCheck.toggled.connect(self.updateDownsampling)
c.subsampleRadio.toggled.connect(self.updateDownsampling)
c.meanRadio.toggled.connect(self.updateDownsampling)
c.clipToViewCheck.toggled.connect(self.updateDownsampling)
self.ctrl.avgParamList.itemClicked.connect(self.avgParamListClicked)
self.ctrl.averageGroup.toggled.connect(self.avgToggled)
self.ctrl.maxTracesCheck.toggled.connect(self.updateDecimation)
self.ctrl.maxTracesSpin.valueChanged.connect(self.updateDecimation)
if labels is None:
labels = {}
for label in list(self.axes.keys()):
if label in kargs:
labels[label] = kargs[label]
del kargs[label]
for k in labels:
if isinstance(labels[k], basestring):
labels[k] = (labels[k],)
self.setLabel(k, *labels[k])
if title is not None:
self.setTitle(title)
if len(kargs) > 0:
self.plot(**kargs)
def implements(self, interface=None):
return interface in ['ViewBoxWrapper']
def getViewBox(self):
"""Return the :class:`ViewBox <pyqtgraph.ViewBox>` contained within."""
return self.vb
## Wrap a few methods from viewBox.
#Important: don't use a settattr(m, getattr(self.vb, m)) as we'd be leaving the viebox alive
#because we had a reference to an instance method (creating wrapper methods at runtime instead).
for m in ['setXRange', 'setYRange', 'setXLink', 'setYLink', 'setAutoPan', # NOTE:
'setAutoVisible', 'setRange', 'autoRange', 'viewRect', 'viewRange', # If you update this list, please
'setMouseEnabled', 'setLimits', 'enableAutoRange', 'disableAutoRange', # update the class docstring
'setAspectLocked', 'invertY', 'invertX', 'register', 'unregister']: # as well.
def _create_method(name):
def method(self, *args, **kwargs):
return getattr(self.vb, name)(*args, **kwargs)
method.__name__ = name
return method
locals()[m] = _create_method(m)
del _create_method
def setAxisItems(self, axisItems=None):
"""
Place axis items as given by `axisItems`. Initializes non-existing axis items.
============== ==========================================================================================
**Arguments:**
*axisItems* Optional dictionary instructing the PlotItem to use pre-constructed items
for its axes. The dict keys must be axis names ('left', 'bottom', 'right', 'top')
and the values must be instances of AxisItem (or at least compatible with AxisItem).
============== ==========================================================================================
"""
if axisItems is None:
axisItems = {}
# Array containing visible axis items
# Also containing potentially hidden axes, but they are not touched so it does not matter
visibleAxes = ['left', 'bottom']
visibleAxes.append(axisItems.keys()) # Note that it does not matter that this adds
# some values to visibleAxes a second time
for k, pos in (('top', (1,1)), ('bottom', (3,1)), ('left', (2,0)), ('right', (2,2))):
if k in self.axes:
if k not in axisItems:
continue # Nothing to do here
# Remove old axis
oldAxis = self.axes[k]['item']
self.layout.removeItem(oldAxis)
oldAxis.scene().removeItem(oldAxis)
oldAxis.unlinkFromView()
# Create new axis
if k in axisItems:
axis = axisItems[k]
if axis.scene() is not None:
if axis != self.axes[k]["item"]:
raise RuntimeError("Can't add an axis to multiple plots.")
else:
axis = AxisItem(orientation=k, parent=self)
# Set up new axis
axis.linkToView(self.vb)
self.axes[k] = {'item': axis, 'pos': pos}
self.layout.addItem(axis, *pos)
axis.setZValue(-1000)
axis.setFlag(axis.ItemNegativeZStacksBehindParent)
axisVisible = k in visibleAxes
self.showAxis(k, axisVisible)
def setLogMode(self, x=None, y=None):
"""
Set log scaling for x and/or y axes.
This informs PlotDataItems to transform logarithmically and switches
the axes to use log ticking.
Note that *no other items* in the scene will be affected by
this; there is (currently) no generic way to redisplay a GraphicsItem
with log coordinates.
"""
if x is not None:
self.ctrl.logXCheck.setChecked(x)
if y is not None:
self.ctrl.logYCheck.setChecked(y)
def showGrid(self, x=None, y=None, alpha=None):
"""
Show or hide the grid for either axis.
============== =====================================
**Arguments:**
x (bool) Whether to show the X grid
y (bool) Whether to show the Y grid
alpha (0.0-1.0) Opacity of the grid
============== =====================================
"""
if x is None and y is None and alpha is None:
raise Exception("Must specify at least one of x, y, or alpha.") ## prevent people getting confused if they just call showGrid()
if x is not None:
self.ctrl.xGridCheck.setChecked(x)
if y is not None:
self.ctrl.yGridCheck.setChecked(y)
if alpha is not None:
v = np.clip(alpha, 0, 1)*self.ctrl.gridAlphaSlider.maximum()
self.ctrl.gridAlphaSlider.setValue(v)
def close(self):
## Most of this crap is needed to avoid PySide trouble.
## The problem seems to be whenever scene.clear() leads to deletion of widgets (either through proxies or qgraphicswidgets)
## the solution is to manually remove all widgets before scene.clear() is called
if self.ctrlMenu is None: ## already shut down
return
self.ctrlMenu.setParent(None)
self.ctrlMenu = None
self.autoBtn.setParent(None)
self.autoBtn = None
for k in self.axes:
i = self.axes[k]['item']
i.close()
self.axes = None
self.scene().removeItem(self.vb)
self.vb = None
def registerPlot(self, name): ## for backward compatibility
self.vb.register(name)
def updateGrid(self, *args):
alpha = self.ctrl.gridAlphaSlider.value()
x = alpha if self.ctrl.xGridCheck.isChecked() else False
y = alpha if self.ctrl.yGridCheck.isChecked() else False
self.getAxis('top').setGrid(x)
self.getAxis('bottom').setGrid(x)
self.getAxis('left').setGrid(y)
self.getAxis('right').setGrid(y)
def viewGeometry(self):
"""Return the screen geometry of the viewbox"""
v = self.scene().views()[0]
b = self.vb.mapRectToScene(self.vb.boundingRect())
wr = v.mapFromScene(b).boundingRect()
pos = v.mapToGlobal(v.pos())
wr.adjust(pos.x(), pos.y(), pos.x(), pos.y())
return wr
def avgToggled(self, b):
if b:
self.recomputeAverages()
for k in self.avgCurves:
self.avgCurves[k][1].setVisible(b)
def avgParamListClicked(self, item):
name = str(item.text())
self.paramList[name] = (item.checkState() == QtCore.Qt.Checked)
self.recomputeAverages()
def recomputeAverages(self):
if not self.ctrl.averageGroup.isChecked():
return
for k in self.avgCurves:
self.removeItem(self.avgCurves[k][1])
self.avgCurves = {}
for c in self.curves:
self.addAvgCurve(c)
self.replot()
def addAvgCurve(self, curve):
## Add a single curve into the pool of curves averaged together
## If there are plot parameters, then we need to determine which to average together.
remKeys = []
addKeys = []
if self.ctrl.avgParamList.count() > 0:
### First determine the key of the curve to which this new data should be averaged
for i in range(self.ctrl.avgParamList.count()):
item = self.ctrl.avgParamList.item(i)
if item.checkState() == QtCore.Qt.Checked:
remKeys.append(str(item.text()))
else:
addKeys.append(str(item.text()))
if len(remKeys) < 1: ## In this case, there would be 1 average plot for each data plot; not useful.
return
p = self.itemMeta.get(curve,{}).copy()
for k in p:
if type(k) is tuple:
p['.'.join(k)] = p[k]
del p[k]
for rk in remKeys:
if rk in p:
del p[rk]
for ak in addKeys:
if ak not in p:
p[ak] = None
key = tuple(p.items())
### Create a new curve if needed
if key not in self.avgCurves:
plot = PlotDataItem()
plot.setPen(fn.mkPen([0, 200, 0]))
plot.setShadowPen(fn.mkPen([0, 0, 0, 100], width=3))
plot.setAlpha(1.0, False)
plot.setZValue(100)
self.addItem(plot, skipAverage=True)
self.avgCurves[key] = [0, plot]
self.avgCurves[key][0] += 1
(n, plot) = self.avgCurves[key]
### Average data together
(x, y) = curve.getData()
stepMode = curve.opts['stepMode']
if plot.yData is not None and y.shape == plot.yData.shape:
# note that if shapes do not match, then the average resets.
newData = plot.yData * (n-1) / float(n) + y * 1.0 / float(n)
plot.setData(plot.xData, newData, stepMode=stepMode)
else:
plot.setData(x, y, stepMode=stepMode)
def autoBtnClicked(self):
if self.autoBtn.mode == 'auto':
self.enableAutoRange()
self.autoBtn.hide()
else:
self.disableAutoRange()
def viewStateChanged(self):
self.updateButtons()
def enableAutoScale(self):
"""
Enable auto-scaling. The plot will continuously scale to fit the boundaries of its data.
"""
print("Warning: enableAutoScale is deprecated. Use enableAutoRange(axis, enable) instead.")
self.vb.enableAutoRange(self.vb.XYAxes)
def addItem(self, item, *args, **kargs):
"""
Add a graphics item to the view box.
If the item has plot data (PlotDataItem, PlotCurveItem, ScatterPlotItem), it may
be included in analysis performed by the PlotItem.
"""
self.items.append(item)
vbargs = {}
if 'ignoreBounds' in kargs:
vbargs['ignoreBounds'] = kargs['ignoreBounds']
self.vb.addItem(item, *args, **vbargs)
name = None
if hasattr(item, 'implements') and item.implements('plotData'):
name = item.name()
self.dataItems.append(item)
#self.plotChanged()
params = kargs.get('params', {})
self.itemMeta[item] = params
#item.setMeta(params)
self.curves.append(item)
#self.addItem(c)
if hasattr(item, 'setLogMode'):
item.setLogMode(self.ctrl.logXCheck.isChecked(), self.ctrl.logYCheck.isChecked())
if isinstance(item, PlotDataItem):
## configure curve for this plot
(alpha, auto) = self.alphaState()
item.setAlpha(alpha, auto)
item.setFftMode(self.ctrl.fftCheck.isChecked())
item.setDownsampling(*self.downsampleMode())
item.setClipToView(self.clipToViewMode())
item.setPointMode(self.pointMode())
## Hide older plots if needed
self.updateDecimation()
## Add to average if needed
self.updateParamList()
if self.ctrl.averageGroup.isChecked() and 'skipAverage' not in kargs:
self.addAvgCurve(item)
#c.connect(c, QtCore.SIGNAL('plotChanged'), self.plotChanged)
#item.sigPlotChanged.connect(self.plotChanged)
#self.plotChanged()
#name = kargs.get('name', getattr(item, 'opts', {}).get('name', None))
if name is not None and hasattr(self, 'legend') and self.legend is not None:
self.legend.addItem(item, name=name)
def addDataItem(self, item, *args):
print("PlotItem.addDataItem is deprecated. Use addItem instead.")
self.addItem(item, *args)
def listDataItems(self):
"""Return a list of all data items (PlotDataItem, PlotCurveItem, ScatterPlotItem, etc)
contained in this PlotItem."""
return self.dataItems[:]
def addCurve(self, c, params=None):
print("PlotItem.addCurve is deprecated. Use addItem instead.")
self.addItem(c, params)
def addLine(self, x=None, y=None, z=None, **kwds):
"""
Create an InfiniteLine and add to the plot.
If *x* is specified,
the line will be vertical. If *y* is specified, the line will be
horizontal. All extra keyword arguments are passed to
:func:`InfiniteLine.__init__() <pyqtgraph.InfiniteLine.__init__>`.
Returns the item created.
"""
kwds['pos'] = kwds.get('pos', x if x is not None else y)
kwds['angle'] = kwds.get('angle', 0 if x is None else 90)
line = InfiniteLine(**kwds)
self.addItem(line)
if z is not None:
line.setZValue(z)
return line
def removeItem(self, item):
"""
Remove an item from the internal ViewBox.
"""
if not item in self.items:
return
self.items.remove(item)
if item in self.dataItems:
self.dataItems.remove(item)
self.vb.removeItem(item)
if item in self.curves:
self.curves.remove(item)
self.updateDecimation()
self.updateParamList()
if self.legend is not None:
self.legend.removeItem(item)
def clear(self):
"""
Remove all items from the ViewBox.
"""
for i in self.items[:]:
self.removeItem(i)
self.avgCurves = {}
def clearPlots(self):
for i in self.curves[:]:
self.removeItem(i)
self.avgCurves = {}
def plot(self, *args, **kargs):
"""
Add and return a new plot.
See :func:`PlotDataItem.__init__ <pyqtgraph.PlotDataItem.__init__>` for data arguments
Extra allowed arguments are:
clear - clear all plots before displaying new data
params - meta-parameters to associate with this data
"""
clear = kargs.get('clear', False)
params = kargs.get('params', None)
if clear:
self.clear()
item = PlotDataItem(*args, **kargs)
if params is None:
params = {}
self.addItem(item, params=params)
return item
def addLegend(self, size=None, offset=(30, 30)):
"""
Create a new LegendItem and anchor it over the internal ViewBox.
Plots will be automatically displayed in the legend if they
are created with the 'name' argument.
If a LegendItem has already been created using this method, that
item will be returned rather than creating a new one.
"""
if self.legend is None:
self.legend = LegendItem(size, offset)
self.legend.setParentItem(self.vb)
return self.legend
def scatterPlot(self, *args, **kargs):
if 'pen' in kargs:
kargs['symbolPen'] = kargs['pen']
kargs['pen'] = None
if 'brush' in kargs:
kargs['symbolBrush'] = kargs['brush']
del kargs['brush']
if 'size' in kargs:
kargs['symbolSize'] = kargs['size']
del kargs['size']
return self.plot(*args, **kargs)
def replot(self):
self.update()
def updateParamList(self):
self.ctrl.avgParamList.clear()
## Check to see that each parameter for each curve is present in the list
for c in self.curves:
for p in list(self.itemMeta.get(c, {}).keys()):
if type(p) is tuple:
p = '.'.join(p)
## If the parameter is not in the list, add it.
matches = self.ctrl.avgParamList.findItems(p, QtCore.Qt.MatchExactly)
if len(matches) == 0:
i = QtGui.QListWidgetItem(p)
if p in self.paramList and self.paramList[p] is True:
i.setCheckState(QtCore.Qt.Checked)
else:
i.setCheckState(QtCore.Qt.Unchecked)
self.ctrl.avgParamList.addItem(i)
else:
i = matches[0]
self.paramList[p] = (i.checkState() == QtCore.Qt.Checked)
def writeSvgCurves(self, fileName=None):
if fileName is None:
self._chooseFilenameDialog(handler=self.writeSvg)
return
if isinstance(fileName, tuple):
raise Exception("Not implemented yet..")
fileName = str(fileName)
PlotItem.lastFileDir = os.path.dirname(fileName)
rect = self.vb.viewRect()
xRange = rect.left(), rect.right()
svg = ""
dx = max(rect.right(),0) - min(rect.left(),0)
ymn = min(rect.top(), rect.bottom())
ymx = max(rect.top(), rect.bottom())
dy = max(ymx,0) - min(ymn,0)
sx = 1.
sy = 1.
while dx*sx < 10:
sx *= 1000
while dy*sy < 10:
sy *= 1000
sy *= -1
with open(fileName, 'w') as fh:
# fh.write('<svg viewBox="%f %f %f %f">\n' % (rect.left() * sx,
# rect.top() * sx,
# rect.width() * sy,
# rect.height()*sy))
fh.write('<svg>\n')
fh.write('<path fill="none" stroke="#000000" stroke-opacity="0.5" '
'stroke-width="1" d="M%f,0 L%f,0"/>\n' % (
rect.left() * sx, rect.right() * sx))
fh.write('<path fill="none" stroke="#000000" stroke-opacity="0.5" '
'stroke-width="1" d="M0,%f L0,%f"/>\n' % (
rect.top() * sy, rect.bottom() * sy))
for item in self.curves:
if isinstance(item, PlotCurveItem):
color = fn.colorStr(item.pen.color())
opacity = item.pen.color().alpha() / 255.
color = color[:6]
x, y = item.getData()
mask = (x > xRange[0]) * (x < xRange[1])
mask[:-1] += mask[1:]
m2 = mask.copy()
mask[1:] += m2[:-1]
x = x[mask]
y = y[mask]
x *= sx
y *= sy
# fh.write('<g fill="none" stroke="#%s" '
# 'stroke-opacity="1" stroke-width="1">\n' % (
# color, ))
fh.write('<path fill="none" stroke="#%s" '
'stroke-opacity="%f" stroke-width="1" '
'd="M%f,%f ' % (color, opacity, x[0], y[0]))
for i in range(1, len(x)):
fh.write('L%f,%f ' % (x[i], y[i]))
fh.write('"/>')
# fh.write("</g>")
for item in self.dataItems:
if isinstance(item, ScatterPlotItem):
pRect = item.boundingRect()
vRect = pRect.intersected(rect)
for point in item.points():
pos = point.pos()
if not rect.contains(pos):
continue
color = fn.colorStr(point.brush.color())
opacity = point.brush.color().alpha() / 255.
color = color[:6]
x = pos.x() * sx
y = pos.y() * sy
fh.write('<circle cx="%f" cy="%f" r="1" fill="#%s" '
'stroke="none" fill-opacity="%f"/>\n' % (
x, y, color, opacity))
fh.write("</svg>\n")
def writeSvg(self, fileName=None):
if fileName is None:
self._chooseFilenameDialog(handler=self.writeSvg)
return
fileName = str(fileName)
PlotItem.lastFileDir = os.path.dirname(fileName)
from ...exporters import SVGExporter
ex = SVGExporter(self)
ex.export(fileName)
def writeImage(self, fileName=None):
if fileName is None:
self._chooseFilenameDialog(handler=self.writeImage)
return
from ...exporters import ImageExporter
ex = ImageExporter(self)
ex.export(fileName)
def writeCsv(self, fileName=None):
if fileName is None:
self._chooseFilenameDialog(handler=self.writeCsv)
return
fileName = str(fileName)
PlotItem.lastFileDir = os.path.dirname(fileName)
data = [c.getData() for c in self.curves]
with open(fileName, 'w') as fd:
i = 0
while True:
done = True
for d in data:
if i < len(d[0]):
fd.write('%g,%g,' % (d[0][i], d[1][i]))
done = False
else:
fd.write(' , ,')
fd.write('\n')
if done:
break
i += 1
def saveState(self):
state = self.stateGroup.state()
state['paramList'] = self.paramList.copy()
state['view'] = self.vb.getState()
return state
def restoreState(self, state):
if 'paramList' in state:
self.paramList = state['paramList'].copy()
self.stateGroup.setState(state)
self.updateSpectrumMode()
self.updateDownsampling()
self.updateAlpha()
self.updateDecimation()
if 'powerSpectrumGroup' in state:
state['fftCheck'] = state['powerSpectrumGroup']
if 'gridGroup' in state:
state['xGridCheck'] = state['gridGroup']
state['yGridCheck'] = state['gridGroup']
self.stateGroup.setState(state)
self.updateParamList()
if 'view' not in state:
r = [[float(state['xMinText']), float(state['xMaxText'])], [float(state['yMinText']), float(state['yMaxText'])]]
state['view'] = {
'autoRange': [state['xAutoRadio'], state['yAutoRadio']],
'linkedViews': [state['xLinkCombo'], state['yLinkCombo']],
'targetRange': r,
'viewRange': r,
}
self.vb.setState(state['view'])
def widgetGroupInterface(self):
return (None, PlotItem.saveState, PlotItem.restoreState)
def updateSpectrumMode(self, b=None):
if b is None:
b = self.ctrl.fftCheck.isChecked()
for c in self.curves:
c.setFftMode(b)
self.enableAutoRange()
self.recomputeAverages()
def updateLogMode(self):
x = self.ctrl.logXCheck.isChecked()
y = self.ctrl.logYCheck.isChecked()
for i in self.items:
if hasattr(i, 'setLogMode'):
i.setLogMode(x,y)
self.getAxis('bottom').setLogMode(x)
self.getAxis('top').setLogMode(x)
self.getAxis('left').setLogMode(y)
self.getAxis('right').setLogMode(y)
self.enableAutoRange()
self.recomputeAverages()
def setDownsampling(self, ds=None, auto=None, mode=None):
"""Change the default downsampling mode for all PlotDataItems managed by this plot.
=============== =================================================================
**Arguments:**
ds (int) Reduce visible plot samples by this factor, or
(bool) To enable/disable downsampling without changing the value.
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.
=============== =================================================================
"""
if ds is not None:
if ds is False:
self.ctrl.downsampleCheck.setChecked(False)
elif ds is True:
self.ctrl.downsampleCheck.setChecked(True)
else:
self.ctrl.downsampleCheck.setChecked(True)
self.ctrl.downsampleSpin.setValue(ds)
if auto is not None:
if auto and ds is not False:
self.ctrl.downsampleCheck.setChecked(True)
self.ctrl.autoDownsampleCheck.setChecked(auto)
if mode is not None:
if mode == 'subsample':
self.ctrl.subsampleRadio.setChecked(True)
elif mode == 'mean':
self.ctrl.meanRadio.setChecked(True)
elif mode == 'peak':
self.ctrl.peakRadio.setChecked(True)
else:
raise ValueError("mode argument must be 'subsample', 'mean', or 'peak'.")
def updateDownsampling(self):
ds, auto, method = self.downsampleMode()
clip = self.ctrl.clipToViewCheck.isChecked()
for c in self.curves:
c.setDownsampling(ds, auto, method)
c.setClipToView(clip)
self.recomputeAverages()
def downsampleMode(self):
if self.ctrl.downsampleCheck.isChecked():
ds = self.ctrl.downsampleSpin.value()
else:
ds = 1
auto = self.ctrl.downsampleCheck.isChecked() and self.ctrl.autoDownsampleCheck.isChecked()
if self.ctrl.subsampleRadio.isChecked():
method = 'subsample'
elif self.ctrl.meanRadio.isChecked():
method = 'mean'
elif self.ctrl.peakRadio.isChecked():
method = 'peak'
return ds, auto, method
def setClipToView(self, clip):
"""Set the default clip-to-view mode for all PlotDataItems managed by this plot.
If *clip* is True, then PlotDataItems will attempt to draw only points within the visible
range of the ViewBox."""
self.ctrl.clipToViewCheck.setChecked(clip)
def clipToViewMode(self):
return self.ctrl.clipToViewCheck.isChecked()
def updateDecimation(self):
if self.ctrl.maxTracesCheck.isChecked():
numCurves = self.ctrl.maxTracesSpin.value()
else:
numCurves = -1
curves = self.curves[:]
split = len(curves) - numCurves
for curve in curves[split:]:
if numCurves != -1:
if self.ctrl.forgetTracesCheck.isChecked():
curve.clear()
self.removeItem(curves[i])
else:
curve.hide()
def updateAlpha(self, *args):
(alpha, auto) = self.alphaState()
for c in self.curves:
c.setAlpha(alpha**2, auto)
def alphaState(self):
enabled = self.ctrl.alphaGroup.isChecked()
auto = self.ctrl.autoAlphaCheck.isChecked()
alpha = float(self.ctrl.alphaSlider.value()) / self.ctrl.alphaSlider.maximum()
if auto:
alpha = 1.0 ## should be 1/number of overlapping plots
if not enabled:
auto = False
alpha = 1.0
return (alpha, auto)
def pointMode(self):
if self.ctrl.pointsGroup.isChecked():
if self.ctrl.autoPointsCheck.isChecked():
mode = None
else:
mode = True
else:
mode = False
return mode
def resizeEvent(self, ev):
if self.autoBtn is None: ## already closed down
return
btnRect = self.mapRectFromItem(self.autoBtn, self.autoBtn.boundingRect())
y = self.size().height() - btnRect.height()
self.autoBtn.setPos(0, y)
def getMenu(self):
return self.ctrlMenu
def getContextMenus(self, event):
## called when another item is displaying its context menu; we get to add extras to the end of the menu.
if self.menuEnabled():
return self.ctrlMenu
else:
return None
def setMenuEnabled(self, enableMenu=True, enableViewBoxMenu='same'):
"""
Enable or disable the context menu for this PlotItem.
By default, the ViewBox's context menu will also be affected.
(use enableViewBoxMenu=None to leave the ViewBox unchanged)
"""
self._menuEnabled = enableMenu
if enableViewBoxMenu is None:
return
if enableViewBoxMenu == 'same':
enableViewBoxMenu = enableMenu
self.vb.setMenuEnabled(enableViewBoxMenu)
def menuEnabled(self):
return self._menuEnabled
def hoverEvent(self, ev):
if ev.enter:
self.mouseHovering = True
if ev.exit:
self.mouseHovering = False
self.updateButtons()
def getLabel(self, key):
pass
def _checkScaleKey(self, key):
if key not in self.axes:
raise Exception("Scale '%s' not found. Scales are: %s" % (key, str(list(self.axes.keys()))))
def getScale(self, key):
return self.getAxis(key)
def getAxis(self, name):
"""Return the specified AxisItem.
*name* should be 'left', 'bottom', 'top', or 'right'."""
self._checkScaleKey(name)
return self.axes[name]['item']
def setLabel(self, axis, text=None, units=None, unitPrefix=None, **args):
"""
Set the label for an axis. Basic HTML formatting is allowed.
============== =================================================================
**Arguments:**
axis must be one of 'left', 'bottom', 'right', or 'top'
text text to display along the axis. HTML allowed.
units units to display after the title. If units are given,
then an SI prefix will be automatically appended
and the axis values will be scaled accordingly.
(ie, use 'V' instead of 'mV'; 'm' will be added automatically)
============== =================================================================
"""
self.getAxis(axis).setLabel(text=text, units=units, **args)
self.showAxis(axis)
def setLabels(self, **kwds):
"""
Convenience function allowing multiple labels and/or title to be set in one call.
Keyword arguments can be 'title', 'left', 'bottom', 'right', or 'top'.
Values may be strings or a tuple of arguments to pass to setLabel.
"""
for k,v in kwds.items():
if k == 'title':
self.setTitle(v)
else:
if isinstance(v, basestring):
v = (v,)
self.setLabel(k, *v)
def showLabel(self, axis, show=True):
"""
Show or hide one of the plot's axis labels (the axis itself will be unaffected).
axis must be one of 'left', 'bottom', 'right', or 'top'
"""
self.getScale(axis).showLabel(show)
def setTitle(self, title=None, **args):
"""
Set the title of the plot. Basic HTML formatting is allowed.
If title is None, then the title will be hidden.
"""
if title is None:
self.titleLabel.setVisible(False)
self.layout.setRowFixedHeight(0, 0)
self.titleLabel.setMaximumHeight(0)
else:
self.titleLabel.setMaximumHeight(30)
self.layout.setRowFixedHeight(0, 30)
self.titleLabel.setVisible(True)
self.titleLabel.setText(title, **args)
def showAxis(self, axis, show=True):
"""
Show or hide one of the plot's axes.
axis must be one of 'left', 'bottom', 'right', or 'top'
"""
s = self.getScale(axis)
p = self.axes[axis]['pos']
if show:
s.show()
else:
s.hide()
def hideAxis(self, axis):
"""Hide one of the PlotItem's axes. ('left', 'bottom', 'right', or 'top')"""
self.showAxis(axis, False)
def showScale(self, *args, **kargs):
print("Deprecated. use showAxis() instead")
return self.showAxis(*args, **kargs)
def hideButtons(self):
"""Causes auto-scale button ('A' in lower-left corner) to be hidden for this PlotItem"""
#self.ctrlBtn.hide()
self.buttonsHidden = True
self.updateButtons()
def showButtons(self):
"""Causes auto-scale button ('A' in lower-left corner) to be visible for this PlotItem"""
#self.ctrlBtn.hide()
self.buttonsHidden = False
self.updateButtons()
def updateButtons(self):
try:
if self._exportOpts is False and self.mouseHovering and not self.buttonsHidden and not all(self.vb.autoRangeEnabled()):
self.autoBtn.show()
else:
self.autoBtn.hide()
except RuntimeError:
pass # this can happen if the plot has been deleted.
def _plotArray(self, arr, x=None, **kargs):
if arr.ndim != 1:
raise Exception("Array must be 1D to plot (shape is %s)" % arr.shape)
if x is None:
x = np.arange(arr.shape[0])
if x.ndim != 1:
raise Exception("X array must be 1D to plot (shape is %s)" % x.shape)
c = PlotCurveItem(arr, x=x, **kargs)
return c
def _plotMetaArray(self, arr, x=None, autoLabel=True, **kargs):
inf = arr.infoCopy()
if arr.ndim != 1:
raise Exception('can only automatically plot 1 dimensional arrays.')
## create curve
try:
xv = arr.xvals(0)
except:
if x is None:
xv = np.arange(arr.shape[0])
else:
xv = x
c = PlotCurveItem(**kargs)
c.setData(x=xv, y=arr.view(np.ndarray))
if autoLabel:
name = arr._info[0].get('name', None)
units = arr._info[0].get('units', None)
self.setLabel('bottom', text=name, units=units)
name = arr._info[1].get('name', None)
units = arr._info[1].get('units', None)
self.setLabel('left', text=name, units=units)
return c
def setExportMode(self, export, opts=None):
GraphicsWidget.setExportMode(self, export, opts)
self.updateButtons()
def _chooseFilenameDialog(self, handler):
self.fileDialog = FileDialog()
if PlotItem.lastFileDir is not None:
self.fileDialog.setDirectory(PlotItem.lastFileDir)
self.fileDialog.setFileMode(QtGui.QFileDialog.AnyFile)
self.fileDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
self.fileDialog.show()
self.fileDialog.fileSelected.connect(handler)
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/PlotItem/plotConfigTemplate_pyside.py | .py | 12,205 | 169 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './pyqtgraph/graphicsItems/PlotItem/plotConfigTemplate.ui'
#
# Created: Mon Dec 23 10:10:52 2013
# by: pyside-uic 0.2.14 running on PySide 1.1.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(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("averageGroup")
self.gridLayout_5 = QtGui.QGridLayout(self.averageGroup)
self.gridLayout_5.setContentsMargins(0, 0, 0, 0)
self.gridLayout_5.setSpacing(0)
self.gridLayout_5.setObjectName("gridLayout_5")
self.avgParamList = QtGui.QListWidget(self.averageGroup)
self.avgParamList.setObjectName("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("decimateGroup")
self.gridLayout_4 = QtGui.QGridLayout(self.decimateGroup)
self.gridLayout_4.setContentsMargins(0, 0, 0, 0)
self.gridLayout_4.setSpacing(0)
self.gridLayout_4.setObjectName("gridLayout_4")
self.clipToViewCheck = QtGui.QCheckBox(self.decimateGroup)
self.clipToViewCheck.setObjectName("clipToViewCheck")
self.gridLayout_4.addWidget(self.clipToViewCheck, 7, 0, 1, 3)
self.maxTracesCheck = QtGui.QCheckBox(self.decimateGroup)
self.maxTracesCheck.setObjectName("maxTracesCheck")
self.gridLayout_4.addWidget(self.maxTracesCheck, 8, 0, 1, 2)
self.downsampleCheck = QtGui.QCheckBox(self.decimateGroup)
self.downsampleCheck.setObjectName("downsampleCheck")
self.gridLayout_4.addWidget(self.downsampleCheck, 0, 0, 1, 3)
self.peakRadio = QtGui.QRadioButton(self.decimateGroup)
self.peakRadio.setChecked(True)
self.peakRadio.setObjectName("peakRadio")
self.gridLayout_4.addWidget(self.peakRadio, 6, 1, 1, 2)
self.maxTracesSpin = QtGui.QSpinBox(self.decimateGroup)
self.maxTracesSpin.setObjectName("maxTracesSpin")
self.gridLayout_4.addWidget(self.maxTracesSpin, 8, 2, 1, 1)
self.forgetTracesCheck = QtGui.QCheckBox(self.decimateGroup)
self.forgetTracesCheck.setObjectName("forgetTracesCheck")
self.gridLayout_4.addWidget(self.forgetTracesCheck, 9, 0, 1, 3)
self.meanRadio = QtGui.QRadioButton(self.decimateGroup)
self.meanRadio.setObjectName("meanRadio")
self.gridLayout_4.addWidget(self.meanRadio, 3, 1, 1, 2)
self.subsampleRadio = QtGui.QRadioButton(self.decimateGroup)
self.subsampleRadio.setObjectName("subsampleRadio")
self.gridLayout_4.addWidget(self.subsampleRadio, 2, 1, 1, 2)
self.autoDownsampleCheck = QtGui.QCheckBox(self.decimateGroup)
self.autoDownsampleCheck.setChecked(True)
self.autoDownsampleCheck.setObjectName("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("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("transformGroup")
self.gridLayout = QtGui.QGridLayout(self.transformGroup)
self.gridLayout.setObjectName("gridLayout")
self.fftCheck = QtGui.QCheckBox(self.transformGroup)
self.fftCheck.setObjectName("fftCheck")
self.gridLayout.addWidget(self.fftCheck, 0, 0, 1, 1)
self.logXCheck = QtGui.QCheckBox(self.transformGroup)
self.logXCheck.setObjectName("logXCheck")
self.gridLayout.addWidget(self.logXCheck, 1, 0, 1, 1)
self.logYCheck = QtGui.QCheckBox(self.transformGroup)
self.logYCheck.setObjectName("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("pointsGroup")
self.verticalLayout_5 = QtGui.QVBoxLayout(self.pointsGroup)
self.verticalLayout_5.setObjectName("verticalLayout_5")
self.autoPointsCheck = QtGui.QCheckBox(self.pointsGroup)
self.autoPointsCheck.setChecked(True)
self.autoPointsCheck.setObjectName("autoPointsCheck")
self.verticalLayout_5.addWidget(self.autoPointsCheck)
self.gridGroup = QtGui.QFrame(Form)
self.gridGroup.setGeometry(QtCore.QRect(10, 460, 221, 81))
self.gridGroup.setObjectName("gridGroup")
self.gridLayout_2 = QtGui.QGridLayout(self.gridGroup)
self.gridLayout_2.setObjectName("gridLayout_2")
self.xGridCheck = QtGui.QCheckBox(self.gridGroup)
self.xGridCheck.setObjectName("xGridCheck")
self.gridLayout_2.addWidget(self.xGridCheck, 0, 0, 1, 2)
self.yGridCheck = QtGui.QCheckBox(self.gridGroup)
self.yGridCheck.setObjectName("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("gridAlphaSlider")
self.gridLayout_2.addWidget(self.gridAlphaSlider, 2, 1, 1, 1)
self.label = QtGui.QLabel(self.gridGroup)
self.label.setObjectName("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("alphaGroup")
self.horizontalLayout = QtGui.QHBoxLayout(self.alphaGroup)
self.horizontalLayout.setObjectName("horizontalLayout")
self.autoAlphaCheck = QtGui.QCheckBox(self.alphaGroup)
self.autoAlphaCheck.setChecked(False)
self.autoAlphaCheck.setObjectName("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("alphaSlider")
self.horizontalLayout.addWidget(self.alphaSlider)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8))
self.averageGroup.setToolTip(QtGui.QApplication.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, QtGui.QApplication.UnicodeUTF8))
self.averageGroup.setTitle(QtGui.QApplication.translate("Form", "Average", None, QtGui.QApplication.UnicodeUTF8))
self.clipToViewCheck.setToolTip(QtGui.QApplication.translate("Form", "Plot only the portion of each curve that is visible. This assumes X values are uniformly spaced.", None, QtGui.QApplication.UnicodeUTF8))
self.clipToViewCheck.setText(QtGui.QApplication.translate("Form", "Clip to View", None, QtGui.QApplication.UnicodeUTF8))
self.maxTracesCheck.setToolTip(QtGui.QApplication.translate("Form", "If multiple curves are displayed in this plot, check this box to limit the number of traces that are displayed.", None, QtGui.QApplication.UnicodeUTF8))
self.maxTracesCheck.setText(QtGui.QApplication.translate("Form", "Max Traces:", None, QtGui.QApplication.UnicodeUTF8))
self.downsampleCheck.setText(QtGui.QApplication.translate("Form", "Downsample", None, QtGui.QApplication.UnicodeUTF8))
self.peakRadio.setToolTip(QtGui.QApplication.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, QtGui.QApplication.UnicodeUTF8))
self.peakRadio.setText(QtGui.QApplication.translate("Form", "Peak", None, QtGui.QApplication.UnicodeUTF8))
self.maxTracesSpin.setToolTip(QtGui.QApplication.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, QtGui.QApplication.UnicodeUTF8))
self.forgetTracesCheck.setToolTip(QtGui.QApplication.translate("Form", "If MaxTraces is checked, remove curves from memory after they are hidden (saves memory, but traces can not be un-hidden).", None, QtGui.QApplication.UnicodeUTF8))
self.forgetTracesCheck.setText(QtGui.QApplication.translate("Form", "Forget hidden traces", None, QtGui.QApplication.UnicodeUTF8))
self.meanRadio.setToolTip(QtGui.QApplication.translate("Form", "Downsample by taking the mean of N samples.", None, QtGui.QApplication.UnicodeUTF8))
self.meanRadio.setText(QtGui.QApplication.translate("Form", "Mean", None, QtGui.QApplication.UnicodeUTF8))
self.subsampleRadio.setToolTip(QtGui.QApplication.translate("Form", "Downsample by taking the first of N samples. This method is fastest and least accurate.", None, QtGui.QApplication.UnicodeUTF8))
self.subsampleRadio.setText(QtGui.QApplication.translate("Form", "Subsample", None, QtGui.QApplication.UnicodeUTF8))
self.autoDownsampleCheck.setToolTip(QtGui.QApplication.translate("Form", "Automatically downsample data based on the visible range. This assumes X values are uniformly spaced.", None, QtGui.QApplication.UnicodeUTF8))
self.autoDownsampleCheck.setText(QtGui.QApplication.translate("Form", "Auto", None, QtGui.QApplication.UnicodeUTF8))
self.downsampleSpin.setToolTip(QtGui.QApplication.translate("Form", "Downsample data before plotting. (plot every Nth sample)", None, QtGui.QApplication.UnicodeUTF8))
self.downsampleSpin.setSuffix(QtGui.QApplication.translate("Form", "x", None, QtGui.QApplication.UnicodeUTF8))
self.fftCheck.setText(QtGui.QApplication.translate("Form", "Power Spectrum (FFT)", None, QtGui.QApplication.UnicodeUTF8))
self.logXCheck.setText(QtGui.QApplication.translate("Form", "Log X", None, QtGui.QApplication.UnicodeUTF8))
self.logYCheck.setText(QtGui.QApplication.translate("Form", "Log Y", None, QtGui.QApplication.UnicodeUTF8))
self.pointsGroup.setTitle(QtGui.QApplication.translate("Form", "Points", None, QtGui.QApplication.UnicodeUTF8))
self.autoPointsCheck.setText(QtGui.QApplication.translate("Form", "Auto", None, QtGui.QApplication.UnicodeUTF8))
self.xGridCheck.setText(QtGui.QApplication.translate("Form", "Show X Grid", None, QtGui.QApplication.UnicodeUTF8))
self.yGridCheck.setText(QtGui.QApplication.translate("Form", "Show Y Grid", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("Form", "Opacity", None, QtGui.QApplication.UnicodeUTF8))
self.alphaGroup.setTitle(QtGui.QApplication.translate("Form", "Alpha", None, QtGui.QApplication.UnicodeUTF8))
self.autoAlphaCheck.setText(QtGui.QApplication.translate("Form", "Auto", None, QtGui.QApplication.UnicodeUTF8))
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/ViewBox/axisCtrlTemplate_pyqt5.py | .py | 5,579 | 90 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './pyqtgraph/graphicsItems/ViewBox/axisCtrlTemplate.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(186, 154)
Form.setMaximumSize(QtCore.QSize(200, 16777215))
self.gridLayout = QtWidgets.QGridLayout(Form)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setSpacing(0)
self.gridLayout.setObjectName("gridLayout")
self.label = QtWidgets.QLabel(Form)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 7, 0, 1, 2)
self.linkCombo = QtWidgets.QComboBox(Form)
self.linkCombo.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)
self.linkCombo.setObjectName("linkCombo")
self.gridLayout.addWidget(self.linkCombo, 7, 2, 1, 2)
self.autoPercentSpin = QtWidgets.QSpinBox(Form)
self.autoPercentSpin.setEnabled(True)
self.autoPercentSpin.setMinimum(1)
self.autoPercentSpin.setMaximum(100)
self.autoPercentSpin.setSingleStep(1)
self.autoPercentSpin.setProperty("value", 100)
self.autoPercentSpin.setObjectName("autoPercentSpin")
self.gridLayout.addWidget(self.autoPercentSpin, 2, 2, 1, 2)
self.autoRadio = QtWidgets.QRadioButton(Form)
self.autoRadio.setChecked(True)
self.autoRadio.setObjectName("autoRadio")
self.gridLayout.addWidget(self.autoRadio, 2, 0, 1, 2)
self.manualRadio = QtWidgets.QRadioButton(Form)
self.manualRadio.setObjectName("manualRadio")
self.gridLayout.addWidget(self.manualRadio, 1, 0, 1, 2)
self.minText = QtWidgets.QLineEdit(Form)
self.minText.setObjectName("minText")
self.gridLayout.addWidget(self.minText, 1, 2, 1, 1)
self.maxText = QtWidgets.QLineEdit(Form)
self.maxText.setObjectName("maxText")
self.gridLayout.addWidget(self.maxText, 1, 3, 1, 1)
self.invertCheck = QtWidgets.QCheckBox(Form)
self.invertCheck.setObjectName("invertCheck")
self.gridLayout.addWidget(self.invertCheck, 5, 0, 1, 4)
self.mouseCheck = QtWidgets.QCheckBox(Form)
self.mouseCheck.setChecked(True)
self.mouseCheck.setObjectName("mouseCheck")
self.gridLayout.addWidget(self.mouseCheck, 6, 0, 1, 4)
self.visibleOnlyCheck = QtWidgets.QCheckBox(Form)
self.visibleOnlyCheck.setObjectName("visibleOnlyCheck")
self.gridLayout.addWidget(self.visibleOnlyCheck, 3, 2, 1, 2)
self.autoPanCheck = QtWidgets.QCheckBox(Form)
self.autoPanCheck.setObjectName("autoPanCheck")
self.gridLayout.addWidget(self.autoPanCheck, 4, 2, 1, 2)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.label.setText(_translate("Form", "Link Axis:"))
self.linkCombo.setToolTip(_translate("Form", "<html><head/><body><p>Links this axis with another view. When linked, both views will display the same data range.</p></body></html>"))
self.autoPercentSpin.setToolTip(_translate("Form", "<html><head/><body><p>Percent of data to be visible when auto-scaling. It may be useful to decrease this value for data with spiky noise.</p></body></html>"))
self.autoPercentSpin.setSuffix(_translate("Form", "%"))
self.autoRadio.setToolTip(_translate("Form", "<html><head/><body><p>Automatically resize this axis whenever the displayed data is changed.</p></body></html>"))
self.autoRadio.setText(_translate("Form", "Auto"))
self.manualRadio.setToolTip(_translate("Form", "<html><head/><body><p>Set the range for this axis manually. This disables automatic scaling. </p></body></html>"))
self.manualRadio.setText(_translate("Form", "Manual"))
self.minText.setToolTip(_translate("Form", "<html><head/><body><p>Minimum value to display for this axis.</p></body></html>"))
self.minText.setText(_translate("Form", "0"))
self.maxText.setToolTip(_translate("Form", "<html><head/><body><p>Maximum value to display for this axis.</p></body></html>"))
self.maxText.setText(_translate("Form", "0"))
self.invertCheck.setToolTip(_translate("Form", "<html><head/><body><p>Inverts the display of this axis. (+y points downward instead of upward)</p></body></html>"))
self.invertCheck.setText(_translate("Form", "Invert Axis"))
self.mouseCheck.setToolTip(_translate("Form", "<html><head/><body><p>Enables mouse interaction (panning, scaling) for this axis.</p></body></html>"))
self.mouseCheck.setText(_translate("Form", "Mouse Enabled"))
self.visibleOnlyCheck.setToolTip(_translate("Form", "<html><head/><body><p>When checked, the axis will only auto-scale to data that is visible along the orthogonal axis.</p></body></html>"))
self.visibleOnlyCheck.setText(_translate("Form", "Visible Data Only"))
self.autoPanCheck.setToolTip(_translate("Form", "<html><head/><body><p>When checked, the axis will automatically pan to center on the current data, but the scale along this axis will not change.</p></body></html>"))
self.autoPanCheck.setText(_translate("Form", "Auto Pan Only"))
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/ViewBox/ViewBox.py | .py | 68,062 | 1,714 | # -*- coding: utf-8 -*-
import weakref
import sys
from copy import deepcopy
import numpy as np
from ...Qt import QtGui, QtCore
from ...python2_3 import basestring
from ...Point import Point
from ... import functions as fn
from .. ItemGroup import ItemGroup
from .. GraphicsWidget import GraphicsWidget
from ... import debug as debug
from ... import getConfigOption
from ...Qt import isQObjectAlive
__all__ = ['ViewBox']
class WeakList(object):
def __init__(self):
self._items = []
def append(self, obj):
#Add backwards to iterate backwards (to make iterating more efficient on removal).
self._items.insert(0, weakref.ref(obj))
def __iter__(self):
i = len(self._items)-1
while i >= 0:
ref = self._items[i]
d = ref()
if d is None:
del self._items[i]
else:
yield d
i -= 1
class ChildGroup(ItemGroup):
def __init__(self, parent):
ItemGroup.__init__(self, parent)
self.setFlag(self.ItemClipsChildrenToShape)
# Used as callback to inform ViewBox when items are added/removed from
# the group.
# Note 1: We would prefer to override itemChange directly on the
# ViewBox, but this causes crashes on PySide.
# Note 2: We might also like to use a signal rather than this callback
# mechanism, but this causes a different PySide crash.
self.itemsChangedListeners = WeakList()
# excempt from telling view when transform changes
self._GraphicsObject__inform_view_on_change = False
def itemChange(self, change, value):
ret = ItemGroup.itemChange(self, change, value)
if change == self.ItemChildAddedChange or change == self.ItemChildRemovedChange:
try:
itemsChangedListeners = self.itemsChangedListeners
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:
for listener in itemsChangedListeners:
listener.itemsChanged()
return ret
def shape(self):
return self.mapFromParent(self.parentItem().shape())
def boundingRect(self):
return self.mapRectFromParent(self.parentItem().boundingRect())
class ViewBox(GraphicsWidget):
"""
**Bases:** :class:`GraphicsWidget <pyqtgraph.GraphicsWidget>`
Box that allows internal scaling/panning of children by mouse drag.
This class is usually created automatically as part of a :class:`PlotItem <pyqtgraph.PlotItem>` or :class:`Canvas <pyqtgraph.canvas.Canvas>` or with :func:`GraphicsLayout.addViewBox() <pyqtgraph.GraphicsLayout.addViewBox>`.
Features:
* Scaling contents by mouse or auto-scale when contents change
* View linking--multiple views display the same data ranges
* Configurable by context menu
* Item coordinate mapping methods
"""
sigYRangeChanged = QtCore.Signal(object, object)
sigXRangeChanged = QtCore.Signal(object, object)
sigRangeChangedManually = QtCore.Signal(object)
sigRangeChanged = QtCore.Signal(object, object)
sigStateChanged = QtCore.Signal(object)
sigTransformChanged = QtCore.Signal(object)
sigResized = QtCore.Signal(object)
## mouse modes
PanMode = 3
RectMode = 1
## axes
XAxis = 0
YAxis = 1
XYAxes = 2
## for linking views together
NamedViews = weakref.WeakValueDictionary() # name: ViewBox
AllViews = weakref.WeakKeyDictionary() # ViewBox: None
def __init__(self, parent=None, border=None, lockAspect=False, enableMouse=True, invertY=False, enableMenu=True, name=None, invertX=False):
"""
============== =============================================================
**Arguments:**
*parent* (QGraphicsWidget) Optional parent widget
*border* (QPen) Do draw a border around the view, give any
single argument accepted by :func:`mkPen <pyqtgraph.mkPen>`
*lockAspect* (False or float) The aspect ratio to lock the view
coorinates to. (or False to allow the ratio to change)
*enableMouse* (bool) Whether mouse can be used to scale/pan the view
*invertY* (bool) See :func:`invertY <pyqtgraph.ViewBox.invertY>`
*invertX* (bool) See :func:`invertX <pyqtgraph.ViewBox.invertX>`
*enableMenu* (bool) Whether to display a context menu when
right-clicking on the ViewBox background.
*name* (str) Used to register this ViewBox so that it appears
in the "Link axis" dropdown inside other ViewBox
context menus. This allows the user to manually link
the axes of any other view to this one.
============== =============================================================
"""
GraphicsWidget.__init__(self, parent)
self.name = None
self.linksBlocked = False
self.addedItems = []
self._matrixNeedsUpdate = True ## indicates that range has changed, but matrix update was deferred
self._autoRangeNeedsUpdate = True ## indicates auto-range needs to be recomputed.
self._lastScene = None ## stores reference to the last known scene this view was a part of.
self.state = {
## separating targetRange and viewRange allows the view to be resized
## while keeping all previously viewed contents visible
'targetRange': [[0,1], [0,1]], ## child coord. range visible [[xmin, xmax], [ymin, ymax]]
'viewRange': [[0,1], [0,1]], ## actual range viewed
'yInverted': invertY,
'xInverted': invertX,
'aspectLocked': False, ## False if aspect is unlocked, otherwise float specifies the locked ratio.
'autoRange': [True, True], ## False if auto range is disabled,
## otherwise float gives the fraction of data that is visible
'autoPan': [False, False], ## whether to only pan (do not change scaling) when auto-range is enabled
'autoVisibleOnly': [False, False], ## whether to auto-range only to the visible portion of a plot
'linkedViews': [None, None], ## may be None, "viewName", or weakref.ref(view)
## a name string indicates that the view *should* link to another, but no view with that name exists yet.
'mouseEnabled': [enableMouse, enableMouse],
'mouseMode': ViewBox.PanMode if getConfigOption('leftButtonPan') else ViewBox.RectMode,
'enableMenu': enableMenu,
'wheelScaleFactor': -1.0 / 8.0,
'background': None,
# Limits
'limits': {
'xLimits': [None, None], # Maximum and minimum visible X values
'yLimits': [None, None], # Maximum and minimum visible Y values
'xRange': [None, None], # Maximum and minimum X range
'yRange': [None, None], # Maximum and minimum Y range
}
}
self._updatingRange = False ## Used to break recursive loops. See updateAutoRange.
self._itemBoundsCache = weakref.WeakKeyDictionary()
self.locateGroup = None ## items displayed when using ViewBox.locate(item)
self.setFlag(self.ItemClipsChildrenToShape)
self.setFlag(self.ItemIsFocusable, True) ## so we can receive key presses
## childGroup is required so that ViewBox has local coordinates similar to device coordinates.
## this is a workaround for a Qt + OpenGL bug that causes improper clipping
## https://bugreports.qt.nokia.com/browse/QTBUG-23723
self.childGroup = ChildGroup(self)
self.childGroup.itemsChangedListeners.append(self)
self.background = QtGui.QGraphicsRectItem(self.rect())
self.background.setParentItem(self)
self.background.setZValue(-1e6)
self.background.setPen(fn.mkPen(None))
self.updateBackground()
self.border = fn.mkPen(border)
self.borderRect = QtGui.QGraphicsRectItem(self.rect())
self.borderRect.setParentItem(self)
self.borderRect.setZValue(1e3)
self.borderRect.setPen(self.border)
## Make scale box that is shown when dragging on the view
self.rbScaleBox = QtGui.QGraphicsRectItem(0, 0, 1, 1)
self.rbScaleBox.setPen(fn.mkPen((255,255,100), width=1))
self.rbScaleBox.setBrush(fn.mkBrush(255,255,0,100))
self.rbScaleBox.setZValue(1e9)
self.rbScaleBox.hide()
self.addItem(self.rbScaleBox, ignoreBounds=True)
## show target rect for debugging
self.target = QtGui.QGraphicsRectItem(0, 0, 1, 1)
self.target.setPen(fn.mkPen('r'))
self.target.setParentItem(self)
self.target.hide()
self.axHistory = [] # maintain a history of zoom locations
self.axHistoryPointer = -1 # pointer into the history. Allows forward/backward movement, not just "undo"
self.setZValue(-100)
self.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding))
self.setAspectLocked(lockAspect)
if enableMenu:
self.menu = ViewBoxMenu(self)
else:
self.menu = None
self.register(name)
if name is None:
self.updateViewLists()
def register(self, name):
"""
Add this ViewBox to the registered list of views.
This allows users to manually link the axes of any other ViewBox to
this one. The specified *name* will appear in the drop-down lists for
axis linking in the context menus of all other views.
The same can be accomplished by initializing the ViewBox with the *name* attribute.
"""
ViewBox.AllViews[self] = None
if self.name is not None:
del ViewBox.NamedViews[self.name]
self.name = name
if name is not None:
ViewBox.NamedViews[name] = self
ViewBox.updateAllViewLists()
sid = id(self)
self.destroyed.connect(lambda: ViewBox.forgetView(sid, name) if (ViewBox is not None and 'sid' in locals() and 'name' in locals()) else None)
def unregister(self):
"""
Remove this ViewBox from the list of linkable views. (see :func:`register() <pyqtgraph.ViewBox.register>`)
"""
del ViewBox.AllViews[self]
if self.name is not None:
del ViewBox.NamedViews[self.name]
def close(self):
self.clear()
self.unregister()
def implements(self, interface):
return interface == 'ViewBox'
# removed due to https://bugreports.qt-project.org/browse/PYSIDE-86
#def itemChange(self, change, value):
## Note: Calling QWidget.itemChange causes segv in python 3 + PyQt
##ret = QtGui.QGraphicsItem.itemChange(self, change, value)
#ret = GraphicsWidget.itemChange(self, change, value)
#if change == self.ItemSceneChange:
#scene = self.scene()
#if scene is not None and hasattr(scene, 'sigPrepareForPaint'):
#scene.sigPrepareForPaint.disconnect(self.prepareForPaint)
#elif change == self.ItemSceneHasChanged:
#scene = self.scene()
#if scene is not None and hasattr(scene, 'sigPrepareForPaint'):
#scene.sigPrepareForPaint.connect(self.prepareForPaint)
#return ret
def update(self, *args, **kwargs):
self.prepareForPaint()
GraphicsWidget.update(self, *args, **kwargs)
def prepareForPaint(self):
#autoRangeEnabled = (self.state['autoRange'][0] is not False) or (self.state['autoRange'][1] is not False)
# don't check whether auto range is enabled here--only check when setting dirty flag.
if self._autoRangeNeedsUpdate: # and autoRangeEnabled:
self.updateAutoRange()
self.updateMatrix()
def getState(self, copy=True):
"""Return the current state of the ViewBox.
Linked views are always converted to view names in the returned state."""
state = self.state.copy()
views = []
for v in state['linkedViews']:
if isinstance(v, weakref.ref):
v = v()
if v is None or isinstance(v, basestring):
views.append(v)
else:
views.append(v.name)
state['linkedViews'] = views
if copy:
return deepcopy(state)
else:
return state
def setState(self, state):
"""Restore the state of this ViewBox.
(see also getState)"""
state = state.copy()
self.setXLink(state['linkedViews'][0])
self.setYLink(state['linkedViews'][1])
del state['linkedViews']
self.state.update(state)
self._applyMenuEnabled()
self.updateViewRange()
self.sigStateChanged.emit(self)
def setBackgroundColor(self, color):
"""
Set the background color of the ViewBox.
If color is None, then no background will be drawn.
Added in version 0.9.9
"""
self.background.setVisible(color is not None)
self.state['background'] = color
self.updateBackground()
def setMouseMode(self, mode):
"""
Set the mouse interaction mode. *mode* must be either ViewBox.PanMode or ViewBox.RectMode.
In PanMode, the left mouse button pans the view and the right button scales.
In RectMode, the left button draws a rectangle which updates the visible region (this mode is more suitable for single-button mice)
"""
if mode not in [ViewBox.PanMode, ViewBox.RectMode]:
raise Exception("Mode must be ViewBox.PanMode or ViewBox.RectMode")
self.state['mouseMode'] = mode
self.sigStateChanged.emit(self)
def setLeftButtonAction(self, mode='rect'): ## for backward compatibility
if mode.lower() == 'rect':
self.setMouseMode(ViewBox.RectMode)
elif mode.lower() == 'pan':
self.setMouseMode(ViewBox.PanMode)
else:
raise Exception('graphicsItems:ViewBox:setLeftButtonAction: unknown mode = %s (Options are "pan" and "rect")' % mode)
def innerSceneItem(self):
return self.childGroup
def setMouseEnabled(self, x=None, y=None):
"""
Set whether each axis is enabled for mouse interaction. *x*, *y* arguments must be True or False.
This allows the user to pan/scale one axis of the view while leaving the other axis unchanged.
"""
if x is not None:
self.state['mouseEnabled'][0] = x
if y is not None:
self.state['mouseEnabled'][1] = y
self.sigStateChanged.emit(self)
def mouseEnabled(self):
return self.state['mouseEnabled'][:]
def setMenuEnabled(self, enableMenu=True):
self.state['enableMenu'] = enableMenu
self._applyMenuEnabled()
self.sigStateChanged.emit(self)
def menuEnabled(self):
return self.state.get('enableMenu', True)
def _applyMenuEnabled(self):
enableMenu = self.state.get("enableMenu", True)
if enableMenu and self.menu is None:
self.menu = ViewBoxMenu(self)
self.updateViewLists()
elif not enableMenu and self.menu is not None:
self.menu.setParent(None)
self.menu = None
def addItem(self, item, ignoreBounds=False):
"""
Add a QGraphicsItem to this view. The view will include this item when determining how to set its range
automatically unless *ignoreBounds* is True.
"""
if item.zValue() < self.zValue():
item.setZValue(self.zValue()+1)
scene = self.scene()
if scene is not None and scene is not item.scene():
scene.addItem(item) ## Necessary due to Qt bug: https://bugreports.qt-project.org/browse/QTBUG-18616
item.setParentItem(self.childGroup)
if not ignoreBounds:
self.addedItems.append(item)
self.updateAutoRange()
def removeItem(self, item):
"""Remove an item from this view."""
try:
self.addedItems.remove(item)
except:
pass
scene = self.scene()
if scene is not None:
scene.removeItem(item)
item.setParentItem(None)
self.updateAutoRange()
def clear(self):
for i in self.addedItems[:]:
self.removeItem(i)
for ch in self.childGroup.childItems():
ch.setParentItem(None)
def resizeEvent(self, ev):
self._matrixNeedsUpdate = True
self.updateMatrix()
self.linkedXChanged()
self.linkedYChanged()
self.updateAutoRange()
self.updateViewRange()
self._matrixNeedsUpdate = True
self.updateMatrix()
self.background.setRect(self.rect())
self.borderRect.setRect(self.rect())
self.sigStateChanged.emit(self)
self.sigResized.emit(self)
self.childGroup.prepareGeometryChange()
def viewRange(self):
"""Return a the view's visible range as a list: [[xmin, xmax], [ymin, ymax]]"""
return [x[:] for x in self.state['viewRange']] ## return copy
def viewRect(self):
"""Return a QRectF bounding the region visible within the ViewBox"""
try:
vr0 = self.state['viewRange'][0]
vr1 = self.state['viewRange'][1]
return QtCore.QRectF(vr0[0], vr1[0], vr0[1]-vr0[0], vr1[1] - vr1[0])
except:
print("make qrectf failed:", self.state['viewRange'])
raise
def targetRange(self):
return [x[:] for x in self.state['targetRange']] ## return copy
def targetRect(self):
"""
Return the region which has been requested to be visible.
(this is not necessarily the same as the region that is *actually* visible--
resizing and aspect ratio constraints can cause targetRect() and viewRect() to differ)
"""
try:
tr0 = self.state['targetRange'][0]
tr1 = self.state['targetRange'][1]
return QtCore.QRectF(tr0[0], tr1[0], tr0[1]-tr0[0], tr1[1] - tr1[0])
except:
print("make qrectf failed:", self.state['targetRange'])
raise
def _resetTarget(self):
# Reset target range to exactly match current view range.
# This is used during mouse interaction to prevent unpredictable
# behavior (because the user is unaware of targetRange).
if self.state['aspectLocked'] is False: # (interferes with aspect locking)
self.state['targetRange'] = [self.state['viewRange'][0][:], self.state['viewRange'][1][:]]
def setRange(self, rect=None, xRange=None, yRange=None, padding=None, update=True, disableAutoRange=True):
"""
Set the visible range of the ViewBox.
Must specify at least one of *rect*, *xRange*, or *yRange*.
================== =====================================================================
**Arguments:**
*rect* (QRectF) The full range that should be visible in the view box.
*xRange* (min,max) The range that should be visible along the x-axis.
*yRange* (min,max) The range that should be visible along the y-axis.
*padding* (float) Expand the view by a fraction of the requested range.
By default, this value is set between 0.02 and 0.1 depending on
the size of the ViewBox.
*update* (bool) If True, update the range of the ViewBox immediately.
Otherwise, the update is deferred until before the next render.
*disableAutoRange* (bool) If True, auto-ranging is diabled. Otherwise, it is left
unchanged.
================== =====================================================================
"""
#print self.name, "ViewBox.setRange", rect, xRange, yRange, padding
#import traceback
#traceback.print_stack()
changes = {} # axes
setRequested = [False, False]
if rect is not None:
changes = {0: [rect.left(), rect.right()], 1: [rect.top(), rect.bottom()]}
setRequested = [True, True]
if xRange is not None:
changes[0] = xRange
setRequested[0] = True
if yRange is not None:
changes[1] = yRange
setRequested[1] = True
if len(changes) == 0:
print(rect)
raise Exception("Must specify at least one of rect, xRange, or yRange. (gave rect=%s)" % str(type(rect)))
# Update axes one at a time
changed = [False, False]
# Disable auto-range for each axis that was requested to be set
if disableAutoRange:
xOff = False if setRequested[0] else None
yOff = False if setRequested[1] else None
self.enableAutoRange(x=xOff, y=yOff)
changed.append(True)
for ax, range in changes.items():
mn = min(range)
mx = max(range)
# If we requested 0 range, try to preserve previous scale.
# Otherwise just pick an arbitrary scale.
if mn == mx:
dy = self.state['viewRange'][ax][1] - self.state['viewRange'][ax][0]
if dy == 0:
dy = 1
mn -= dy*0.5
mx += dy*0.5
xpad = 0.0
# Make sure no nan/inf get through
if not all(np.isfinite([mn, mx])):
raise Exception("Cannot set range [%s, %s]" % (str(mn), str(mx)))
# Apply padding
if padding is None:
xpad = self.suggestPadding(ax)
else:
xpad = padding
p = (mx-mn) * xpad
mn -= p
mx += p
# Set target range
if self.state['targetRange'][ax] != [mn, mx]:
self.state['targetRange'][ax] = [mn, mx]
changed[ax] = True
# Update viewRange to match targetRange as closely as possible while
# accounting for aspect ratio constraint
lockX, lockY = setRequested
if lockX and lockY:
lockX = False
lockY = False
self.updateViewRange(lockX, lockY)
# If nothing has changed, we are done.
if any(changed):
# Update target rect for debugging
if self.target.isVisible():
self.target.setRect(self.mapRectFromItem(self.childGroup, self.targetRect()))
# If ortho axes have auto-visible-only, update them now
# Note that aspect ratio constraints and auto-visible probably do not work together..
if changed[0] and self.state['autoVisibleOnly'][1] and (self.state['autoRange'][0] is not False):
self._autoRangeNeedsUpdate = True
elif changed[1] and self.state['autoVisibleOnly'][0] and (self.state['autoRange'][1] is not False):
self._autoRangeNeedsUpdate = True
self.sigStateChanged.emit(self)
def setYRange(self, min, max, padding=None, update=True):
"""
Set the visible Y range of the view to [*min*, *max*].
The *padding* argument causes the range to be set larger by the fraction specified.
(by default, this value is between 0.02 and 0.1 depending on the size of the ViewBox)
"""
self.setRange(yRange=[min, max], update=update, padding=padding)
def setXRange(self, min, max, padding=None, update=True):
"""
Set the visible X range of the view to [*min*, *max*].
The *padding* argument causes the range to be set larger by the fraction specified.
(by default, this value is between 0.02 and 0.1 depending on the size of the ViewBox)
"""
self.setRange(xRange=[min, max], update=update, padding=padding)
def autoRange(self, padding=None, items=None, item=None):
"""
Set the range of the view box to make all children visible.
Note that this is not the same as enableAutoRange, which causes the view to
automatically auto-range whenever its contents are changed.
============== ============================================================
**Arguments:**
padding The fraction of the total data range to add on to the final
visible range. By default, this value is set between 0.02
and 0.1 depending on the size of the ViewBox.
items If specified, this is a list of items to consider when
determining the visible range.
============== ============================================================
"""
if item is None:
bounds = self.childrenBoundingRect(items=items)
else:
print("Warning: ViewBox.autoRange(item=__) is deprecated. Use 'items' argument instead.")
bounds = self.mapFromItemToView(item, item.boundingRect()).boundingRect()
if bounds is not None:
self.setRange(bounds, padding=padding)
def suggestPadding(self, axis):
l = self.width() if axis==0 else self.height()
if l > 0:
padding = np.clip(1./(l**0.5), 0.02, 0.1)
else:
padding = 0.02
return padding
def setLimits(self, **kwds):
"""
Set limits that constrain the possible view ranges.
**Panning limits**. The following arguments define the region within the
viewbox coordinate system that may be accessed by panning the view.
=========== ============================================================
xMin Minimum allowed x-axis value
xMax Maximum allowed x-axis value
yMin Minimum allowed y-axis value
yMax Maximum allowed y-axis value
=========== ============================================================
**Scaling limits**. These arguments prevent the view being zoomed in or
out too far.
=========== ============================================================
minXRange Minimum allowed left-to-right span across the view.
maxXRange Maximum allowed left-to-right span across the view.
minYRange Minimum allowed top-to-bottom span across the view.
maxYRange Maximum allowed top-to-bottom span across the view.
=========== ============================================================
Added in version 0.9.9
"""
update = False
allowed = ['xMin', 'xMax', 'yMin', 'yMax', 'minXRange', 'maxXRange', 'minYRange', 'maxYRange']
for kwd in kwds:
if kwd not in allowed:
raise ValueError("Invalid keyword argument '%s'." % kwd)
for axis in [0,1]:
for mnmx in [0,1]:
kwd = [['xMin', 'xMax'], ['yMin', 'yMax']][axis][mnmx]
lname = ['xLimits', 'yLimits'][axis]
if kwd in kwds and self.state['limits'][lname][mnmx] != kwds[kwd]:
self.state['limits'][lname][mnmx] = kwds[kwd]
update = True
kwd = [['minXRange', 'maxXRange'], ['minYRange', 'maxYRange']][axis][mnmx]
lname = ['xRange', 'yRange'][axis]
if kwd in kwds and self.state['limits'][lname][mnmx] != kwds[kwd]:
self.state['limits'][lname][mnmx] = kwds[kwd]
update = True
if update:
self.updateViewRange()
def scaleBy(self, s=None, center=None, x=None, y=None):
"""
Scale by *s* around given center point (or center of view).
*s* may be a Point or tuple (x, y).
Optionally, x or y may be specified individually. This allows the other
axis to be left unaffected (note that using a scale factor of 1.0 may
cause slight changes due to floating-point error).
"""
if s is not None:
x, y = s[0], s[1]
affect = [x is not None, y is not None]
if not any(affect):
return
scale = Point([1.0 if x is None else x, 1.0 if y is None else y])
if self.state['aspectLocked'] is not False:
scale[0] = scale[1]
vr = self.targetRect()
if center is None:
center = Point(vr.center())
else:
center = Point(center)
tl = center + (vr.topLeft()-center) * scale
br = center + (vr.bottomRight()-center) * scale
if not affect[0]:
self.setYRange(tl.y(), br.y(), padding=0)
elif not affect[1]:
self.setXRange(tl.x(), br.x(), padding=0)
else:
self.setRange(QtCore.QRectF(tl, br), padding=0)
def translateBy(self, t=None, x=None, y=None):
"""
Translate the view by *t*, which may be a Point or tuple (x, y).
Alternately, x or y may be specified independently, leaving the other
axis unchanged (note that using a translation of 0 may still cause
small changes due to floating-point error).
"""
vr = self.targetRect()
if t is not None:
t = Point(t)
self.setRange(vr.translated(t), padding=0)
else:
if x is not None:
x = vr.left()+x, vr.right()+x
if y is not None:
y = vr.top()+y, vr.bottom()+y
if x is not None or y is not None:
self.setRange(xRange=x, yRange=y, padding=0)
def enableAutoRange(self, axis=None, enable=True, x=None, y=None):
"""
Enable (or disable) auto-range for *axis*, which may be ViewBox.XAxis, ViewBox.YAxis, or ViewBox.XYAxes for both
(if *axis* is omitted, both axes will be changed).
When enabled, the axis will automatically rescale when items are added/removed or change their shape.
The argument *enable* may optionally be a float (0.0-1.0) which indicates the fraction of the data that should
be visible (this only works with items implementing a dataRange method, such as PlotDataItem).
"""
# support simpler interface:
if x is not None or y is not None:
if x is not None:
self.enableAutoRange(ViewBox.XAxis, x)
if y is not None:
self.enableAutoRange(ViewBox.YAxis, y)
return
if enable is True:
enable = 1.0
if axis is None:
axis = ViewBox.XYAxes
needAutoRangeUpdate = False
if axis == ViewBox.XYAxes or axis == 'xy':
axes = [0, 1]
elif axis == ViewBox.XAxis or axis == 'x':
axes = [0]
elif axis == ViewBox.YAxis or axis == 'y':
axes = [1]
else:
raise Exception('axis argument must be ViewBox.XAxis, ViewBox.YAxis, or ViewBox.XYAxes.')
for ax in axes:
if self.state['autoRange'][ax] != enable:
# If we are disabling, do one last auto-range to make sure that
# previously scheduled auto-range changes are enacted
if enable is False and self._autoRangeNeedsUpdate:
self.updateAutoRange()
self.state['autoRange'][ax] = enable
self._autoRangeNeedsUpdate |= (enable is not False)
self.update()
self.sigStateChanged.emit(self)
def disableAutoRange(self, axis=None):
"""Disables auto-range. (See enableAutoRange)"""
self.enableAutoRange(axis, enable=False)
def autoRangeEnabled(self):
return self.state['autoRange'][:]
def setAutoPan(self, x=None, y=None):
"""Set whether automatic range will only pan (not scale) the view.
"""
if x is not None:
self.state['autoPan'][0] = x
if y is not None:
self.state['autoPan'][1] = y
if None not in [x,y]:
self.updateAutoRange()
def setAutoVisible(self, x=None, y=None):
"""Set whether automatic range uses only visible data when determining
the range to show.
"""
if x is not None:
self.state['autoVisibleOnly'][0] = x
if x is True:
self.state['autoVisibleOnly'][1] = False
if y is not None:
self.state['autoVisibleOnly'][1] = y
if y is True:
self.state['autoVisibleOnly'][0] = False
if x is not None or y is not None:
self.updateAutoRange()
def updateAutoRange(self):
## Break recursive loops when auto-ranging.
## This is needed because some items change their size in response
## to a view change.
if self._updatingRange:
return
self._updatingRange = True
try:
targetRect = self.viewRange()
if not any(self.state['autoRange']):
return
fractionVisible = self.state['autoRange'][:]
for i in [0,1]:
if type(fractionVisible[i]) is bool:
fractionVisible[i] = 1.0
childRange = None
order = [0,1]
if self.state['autoVisibleOnly'][0] is True:
order = [1,0]
args = {}
for ax in order:
if self.state['autoRange'][ax] is False:
continue
if self.state['autoVisibleOnly'][ax]:
oRange = [None, None]
oRange[ax] = targetRect[1-ax]
childRange = self.childrenBounds(frac=fractionVisible, orthoRange=oRange)
else:
if childRange is None:
childRange = self.childrenBounds(frac=fractionVisible)
## Make corrections to range
xr = childRange[ax]
if xr is not None:
if self.state['autoPan'][ax]:
x = sum(xr) * 0.5
w2 = (targetRect[ax][1]-targetRect[ax][0]) / 2.
childRange[ax] = [x-w2, x+w2]
else:
padding = self.suggestPadding(ax)
wp = (xr[1] - xr[0]) * padding
childRange[ax][0] -= wp
childRange[ax][1] += wp
targetRect[ax] = childRange[ax]
args['xRange' if ax == 0 else 'yRange'] = targetRect[ax]
# check for and ignore bad ranges
for k in ['xRange', 'yRange']:
if k in args:
if not np.all(np.isfinite(args[k])):
r = args.pop(k)
#print("Warning: %s is invalid: %s" % (k, str(r))
if len(args) == 0:
return
args['padding'] = 0
args['disableAutoRange'] = False
self.setRange(**args)
finally:
self._autoRangeNeedsUpdate = False
self._updatingRange = False
def setXLink(self, view):
"""Link this view's X axis to another view. (see LinkView)"""
self.linkView(self.XAxis, view)
def setYLink(self, view):
"""Link this view's Y axis to another view. (see LinkView)"""
self.linkView(self.YAxis, view)
def linkView(self, axis, view):
"""
Link X or Y axes of two views and unlink any previously connected axes. *axis* must be ViewBox.XAxis or ViewBox.YAxis.
If view is None, the axis is left unlinked.
"""
if isinstance(view, basestring):
if view == '':
view = None
else:
view = ViewBox.NamedViews.get(view, view) ## convert view name to ViewBox if possible
if hasattr(view, 'implements') and view.implements('ViewBoxWrapper'):
view = view.getViewBox()
## used to connect/disconnect signals between a pair of views
if axis == ViewBox.XAxis:
signal = 'sigXRangeChanged'
slot = self.linkedXChanged
else:
signal = 'sigYRangeChanged'
slot = self.linkedYChanged
oldLink = self.linkedView(axis)
if oldLink is not None:
try:
getattr(oldLink, signal).disconnect(slot)
oldLink.sigResized.disconnect(slot)
except (TypeError, RuntimeError):
## This can occur if the view has been deleted already
pass
if view is None or isinstance(view, basestring):
self.state['linkedViews'][axis] = view
else:
self.state['linkedViews'][axis] = weakref.ref(view)
getattr(view, signal).connect(slot)
view.sigResized.connect(slot)
if view.autoRangeEnabled()[axis] is not False:
self.enableAutoRange(axis, False)
slot()
else:
if self.autoRangeEnabled()[axis] is False:
slot()
self.sigStateChanged.emit(self)
def blockLink(self, b):
self.linksBlocked = b ## prevents recursive plot-change propagation
def linkedXChanged(self):
## called when x range of linked view has changed
view = self.linkedView(0)
self.linkedViewChanged(view, ViewBox.XAxis)
def linkedYChanged(self):
## called when y range of linked view has changed
view = self.linkedView(1)
self.linkedViewChanged(view, ViewBox.YAxis)
def linkedView(self, ax):
## Return the linked view for axis *ax*.
## this method _always_ returns either a ViewBox or None.
v = self.state['linkedViews'][ax]
if v is None or isinstance(v, basestring):
return None
else:
return v() ## dereference weakref pointer. If the reference is dead, this returns None
def linkedViewChanged(self, view, axis):
if self.linksBlocked or view is None:
return
#print self.name, "ViewBox.linkedViewChanged", axis, view.viewRange()[axis]
vr = view.viewRect()
vg = view.screenGeometry()
sg = self.screenGeometry()
if vg is None or sg is None:
return
view.blockLink(True)
try:
if axis == ViewBox.XAxis:
overlap = min(sg.right(), vg.right()) - max(sg.left(), vg.left())
if overlap < min(vg.width()/3, sg.width()/3): ## if less than 1/3 of views overlap,
## then just replicate the view
x1 = vr.left()
x2 = vr.right()
else: ## views overlap; line them up
upp = float(vr.width()) / vg.width()
if self.xInverted():
x1 = vr.left() + (sg.right()-vg.right()) * upp
else:
x1 = vr.left() + (sg.x()-vg.x()) * upp
x2 = x1 + sg.width() * upp
self.enableAutoRange(ViewBox.XAxis, False)
self.setXRange(x1, x2, padding=0)
else:
overlap = min(sg.bottom(), vg.bottom()) - max(sg.top(), vg.top())
if overlap < min(vg.height()/3, sg.height()/3): ## if less than 1/3 of views overlap,
## then just replicate the view
y1 = vr.top()
y2 = vr.bottom()
else: ## views overlap; line them up
upp = float(vr.height()) / vg.height()
if self.yInverted():
y2 = vr.bottom() + (sg.bottom()-vg.bottom()) * upp
else:
y2 = vr.bottom() + (sg.top()-vg.top()) * upp
y1 = y2 - sg.height() * upp
self.enableAutoRange(ViewBox.YAxis, False)
self.setYRange(y1, y2, padding=0)
finally:
view.blockLink(False)
def screenGeometry(self):
"""return the screen geometry of the viewbox"""
v = self.getViewWidget()
if v is None:
return None
b = self.sceneBoundingRect()
wr = v.mapFromScene(b).boundingRect()
pos = v.mapToGlobal(v.pos())
wr.adjust(pos.x(), pos.y(), pos.x(), pos.y())
return wr
def itemsChanged(self):
## called when items are added/removed from self.childGroup
self.updateAutoRange()
def itemBoundsChanged(self, item):
self._itemBoundsCache.pop(item, None)
if (self.state['autoRange'][0] is not False) or (self.state['autoRange'][1] is not False):
self._autoRangeNeedsUpdate = True
self.update()
#self.updateAutoRange()
def _invertAxis(self, ax, inv):
key = 'xy'[ax] + 'Inverted'
if self.state[key] == inv:
return
self.state[key] = inv
self._matrixNeedsUpdate = True # updateViewRange won't detect this for us
self.updateViewRange()
self.update()
self.sigStateChanged.emit(self)
if ax:
self.sigYRangeChanged.emit(self, tuple(self.state['viewRange'][ax]))
else:
self.sigXRangeChanged.emit(self, tuple(self.state['viewRange'][ax]))
def invertY(self, b=True):
"""
By default, the positive y-axis points upward on the screen. Use invertY(True) to reverse the y-axis.
"""
self._invertAxis(1, b)
def yInverted(self):
return self.state['yInverted']
def invertX(self, b=True):
"""
By default, the positive x-axis points rightward on the screen. Use invertX(True) to reverse the x-axis.
"""
self._invertAxis(0, b)
def xInverted(self):
return self.state['xInverted']
def setBorder(self, *args, **kwds):
"""
Set the pen used to draw border around the view
If border is None, then no border will be drawn.
Added in version 0.9.10
See :func:`mkPen <pyqtgraph.mkPen>` for arguments.
"""
self.border = fn.mkPen(*args, **kwds)
self.borderRect.setPen(self.border)
def setAspectLocked(self, lock=True, ratio=1):
"""
If the aspect ratio is locked, view scaling must always preserve the aspect ratio.
By default, the ratio is set to 1; x and y both have the same scaling.
This ratio can be overridden (xScale/yScale), or use None to lock in the current ratio.
"""
if not lock:
if self.state['aspectLocked'] == False:
return
self.state['aspectLocked'] = False
else:
rect = self.rect()
vr = self.viewRect()
if rect.height() == 0 or vr.width() == 0 or vr.height() == 0:
currentRatio = 1.0
else:
currentRatio = (rect.width()/float(rect.height())) / (vr.width()/vr.height())
if ratio is None:
ratio = currentRatio
if self.state['aspectLocked'] == ratio: # nothing to change
return
self.state['aspectLocked'] = ratio
if ratio != currentRatio: ## If this would change the current range, do that now
self.updateViewRange()
self.updateAutoRange()
self.updateViewRange()
self.sigStateChanged.emit(self)
def childTransform(self):
"""
Return the transform that maps from child(item in the childGroup) coordinates to local coordinates.
(This maps from inside the viewbox to outside)
"""
self.updateMatrix()
m = self.childGroup.transform()
return m
def mapToView(self, obj):
"""Maps from the local coordinates of the ViewBox to the coordinate system displayed inside the ViewBox"""
self.updateMatrix()
m = fn.invertQTransform(self.childTransform())
return m.map(obj)
def mapFromView(self, obj):
"""Maps from the coordinate system displayed inside the ViewBox to the local coordinates of the ViewBox"""
self.updateMatrix()
m = self.childTransform()
return m.map(obj)
def mapSceneToView(self, obj):
"""Maps from scene coordinates to the coordinate system displayed inside the ViewBox"""
self.updateMatrix()
return self.mapToView(self.mapFromScene(obj))
def mapViewToScene(self, obj):
"""Maps from the coordinate system displayed inside the ViewBox to scene coordinates"""
self.updateMatrix()
return self.mapToScene(self.mapFromView(obj))
def mapFromItemToView(self, item, obj):
"""Maps *obj* from the local coordinate system of *item* to the view coordinates"""
self.updateMatrix()
return self.childGroup.mapFromItem(item, obj)
#return self.mapSceneToView(item.mapToScene(obj))
def mapFromViewToItem(self, item, obj):
"""Maps *obj* from view coordinates to the local coordinate system of *item*."""
self.updateMatrix()
return self.childGroup.mapToItem(item, obj)
def mapViewToDevice(self, obj):
self.updateMatrix()
return self.mapToDevice(self.mapFromView(obj))
def mapDeviceToView(self, obj):
self.updateMatrix()
return self.mapToView(self.mapFromDevice(obj))
def viewPixelSize(self):
"""Return the (width, height) of a screen pixel in view coordinates."""
o = self.mapToView(Point(0,0))
px, py = [Point(self.mapToView(v) - o) for v in self.pixelVectors()]
return (px.length(), py.length())
def itemBoundingRect(self, item):
"""Return the bounding rect of the item in view coordinates"""
return self.mapSceneToView(item.sceneBoundingRect()).boundingRect()
def wheelEvent(self, ev, axis=None):
if axis in (0, 1):
mask = [False, False]
mask[axis] = self.state['mouseEnabled'][axis]
else:
mask = self.state['mouseEnabled'][:]
s = 1.02 ** (ev.delta() * self.state['wheelScaleFactor']) # actual scaling factor
s = [(None if m is False else s) for m in mask]
center = Point(fn.invertQTransform(self.childGroup.transform()).map(ev.pos()))
self._resetTarget()
self.scaleBy(s, center)
ev.accept()
self.sigRangeChangedManually.emit(mask)
def mouseClickEvent(self, ev):
if ev.button() == QtCore.Qt.RightButton and self.menuEnabled():
ev.accept()
self.raiseContextMenu(ev)
def raiseContextMenu(self, ev):
menu = self.getMenu(ev)
if menu is not None:
self.scene().addParentContextMenus(self, menu, ev)
menu.popup(ev.screenPos().toPoint())
def getMenu(self, ev):
return self.menu
def getContextMenus(self, event):
return self.menu.actions() if self.menuEnabled() else []
def mouseDragEvent(self, ev, axis=None):
## if axis is specified, event will only affect that axis.
ev.accept() ## we accept all buttons
pos = ev.pos()
lastPos = ev.lastPos()
dif = pos - lastPos
dif = dif * -1
## Ignore axes if mouse is disabled
mouseEnabled = np.array(self.state['mouseEnabled'], dtype=np.float)
mask = mouseEnabled.copy()
if axis is not None:
mask[1-axis] = 0.0
## Scale or translate based on mouse button
if ev.button() & (QtCore.Qt.LeftButton | QtCore.Qt.MidButton):
if self.state['mouseMode'] == ViewBox.RectMode:
if ev.isFinish(): ## This is the final move in the drag; change the view scale now
#print "finish"
self.rbScaleBox.hide()
ax = QtCore.QRectF(Point(ev.buttonDownPos(ev.button())), Point(pos))
ax = self.childGroup.mapRectFromParent(ax)
self.showAxRect(ax)
self.axHistoryPointer += 1
self.axHistory = self.axHistory[:self.axHistoryPointer] + [ax]
else:
## update shape of scale box
self.updateScaleBox(ev.buttonDownPos(), ev.pos())
else:
tr = dif*mask
tr = self.mapToView(tr) - self.mapToView(Point(0,0))
x = tr.x() if mask[0] == 1 else None
y = tr.y() if mask[1] == 1 else None
self._resetTarget()
if x is not None or y is not None:
self.translateBy(x=x, y=y)
self.sigRangeChangedManually.emit(self.state['mouseEnabled'])
elif ev.button() & QtCore.Qt.RightButton:
#print "vb.rightDrag"
if self.state['aspectLocked'] is not False:
mask[0] = 0
dif = ev.screenPos() - ev.lastScreenPos()
dif = np.array([dif.x(), dif.y()])
dif[0] *= -1
s = ((mask * 0.02) + 1) ** dif
tr = self.childGroup.transform()
tr = fn.invertQTransform(tr)
x = s[0] if mouseEnabled[0] == 1 else None
y = s[1] if mouseEnabled[1] == 1 else None
center = Point(tr.map(ev.buttonDownPos(QtCore.Qt.RightButton)))
self._resetTarget()
self.scaleBy(x=x, y=y, center=center)
self.sigRangeChangedManually.emit(self.state['mouseEnabled'])
def keyPressEvent(self, ev):
"""
This routine should capture key presses in the current view box.
Key presses are used only when mouse mode is RectMode
The following events are implemented:
ctrl-A : zooms out to the default "full" view of the plot
ctrl-+ : moves forward in the zooming stack (if it exists)
ctrl-- : moves backward in the zooming stack (if it exists)
"""
ev.accept()
if ev.text() == '-':
self.scaleHistory(-1)
elif ev.text() in ['+', '=']:
self.scaleHistory(1)
elif ev.key() == QtCore.Qt.Key_Backspace:
self.scaleHistory(len(self.axHistory))
else:
ev.ignore()
def scaleHistory(self, d):
if len(self.axHistory) == 0:
return
ptr = max(0, min(len(self.axHistory)-1, self.axHistoryPointer+d))
if ptr != self.axHistoryPointer:
self.axHistoryPointer = ptr
self.showAxRect(self.axHistory[ptr])
def updateScaleBox(self, p1, p2):
r = QtCore.QRectF(p1, p2)
r = self.childGroup.mapRectFromParent(r)
self.rbScaleBox.setPos(r.topLeft())
self.rbScaleBox.resetTransform()
self.rbScaleBox.scale(r.width(), r.height())
self.rbScaleBox.show()
def showAxRect(self, ax, **kwargs):
"""Set the visible range to the given rectangle
Passes keyword arguments to setRange
"""
self.setRange(ax.normalized(), **kwargs) # be sure w, h are correct coordinates
self.sigRangeChangedManually.emit(self.state['mouseEnabled'])
def allChildren(self, item=None):
"""Return a list of all children and grandchildren of this ViewBox"""
if item is None:
item = self.childGroup
children = [item]
for ch in item.childItems():
children.extend(self.allChildren(ch))
return children
def childrenBounds(self, frac=None, orthoRange=(None,None), items=None):
"""Return the bounding range of all children.
[[xmin, xmax], [ymin, ymax]]
Values may be None if there are no specific bounds for an axis.
"""
profiler = debug.Profiler()
if items is None:
items = self.addedItems
## measure pixel dimensions in view box
px, py = [v.length() if v is not None else 0 for v in self.childGroup.pixelVectors()]
## First collect all boundary information
itemBounds = []
for item in items:
if not item.isVisible() or not item.scene() is self.scene():
continue
useX = True
useY = True
if hasattr(item, 'dataBounds'):
if frac is None:
frac = (1.0, 1.0)
xr = item.dataBounds(0, frac=frac[0], orthoRange=orthoRange[0])
yr = item.dataBounds(1, frac=frac[1], orthoRange=orthoRange[1])
pxPad = 0 if not hasattr(item, 'pixelPadding') else item.pixelPadding()
if xr is None or (xr[0] is None and xr[1] is None) or np.isnan(xr).any() or np.isinf(xr).any():
useX = False
xr = (0,0)
if yr is None or (yr[0] is None and yr[1] is None) or np.isnan(yr).any() or np.isinf(yr).any():
useY = False
yr = (0,0)
bounds = QtCore.QRectF(xr[0], yr[0], xr[1]-xr[0], yr[1]-yr[0])
bounds = self.mapFromItemToView(item, bounds).boundingRect()
if not any([useX, useY]):
continue
## If we are ignoring only one axis, we need to check for rotations
if useX != useY: ## != means xor
ang = round(item.transformAngle())
if ang == 0 or ang == 180:
pass
elif ang == 90 or ang == 270:
useX, useY = useY, useX
else:
## Item is rotated at non-orthogonal angle, ignore bounds entirely.
## Not really sure what is the expected behavior in this case.
continue ## need to check for item rotations and decide how best to apply this boundary.
itemBounds.append((bounds, useX, useY, pxPad))
else:
if int(item.flags() & item.ItemHasNoContents) > 0:
continue
else:
bounds = item.boundingRect()
bounds = self.mapFromItemToView(item, bounds).boundingRect()
itemBounds.append((bounds, True, True, 0))
## determine tentative new range
range = [None, None]
for bounds, useX, useY, px in itemBounds:
if useY:
if range[1] is not None:
range[1] = [min(bounds.top(), range[1][0]), max(bounds.bottom(), range[1][1])]
else:
range[1] = [bounds.top(), bounds.bottom()]
if useX:
if range[0] is not None:
range[0] = [min(bounds.left(), range[0][0]), max(bounds.right(), range[0][1])]
else:
range[0] = [bounds.left(), bounds.right()]
profiler()
## Now expand any bounds that have a pixel margin
## This must be done _after_ we have a good estimate of the new range
## to ensure that the pixel size is roughly accurate.
w = self.width()
h = self.height()
if w > 0 and range[0] is not None:
pxSize = (range[0][1] - range[0][0]) / w
for bounds, useX, useY, px in itemBounds:
if px == 0 or not useX:
continue
range[0][0] = min(range[0][0], bounds.left() - px*pxSize)
range[0][1] = max(range[0][1], bounds.right() + px*pxSize)
if h > 0 and range[1] is not None:
pxSize = (range[1][1] - range[1][0]) / h
for bounds, useX, useY, px in itemBounds:
if px == 0 or not useY:
continue
range[1][0] = min(range[1][0], bounds.top() - px*pxSize)
range[1][1] = max(range[1][1], bounds.bottom() + px*pxSize)
return range
def childrenBoundingRect(self, *args, **kwds):
range = self.childrenBounds(*args, **kwds)
tr = self.targetRange()
if range[0] is None:
range[0] = tr[0]
if range[1] is None:
range[1] = tr[1]
bounds = QtCore.QRectF(range[0][0], range[1][0], range[0][1]-range[0][0], range[1][1]-range[1][0])
return bounds
def updateViewRange(self, forceX=False, forceY=False):
## Update viewRange to match targetRange as closely as possible, given
## aspect ratio constraints. The *force* arguments are used to indicate
## which axis (if any) should be unchanged when applying constraints.
viewRange = [self.state['targetRange'][0][:], self.state['targetRange'][1][:]]
changed = [False, False]
#-------- Make correction for aspect ratio constraint ----------
# aspect is (widget w/h) / (view range w/h)
aspect = self.state['aspectLocked'] # size ratio / view ratio
tr = self.targetRect()
bounds = self.rect()
if aspect is not False and 0 not in [aspect, tr.height(), bounds.height(), bounds.width()]:
## This is the view range aspect ratio we have requested
targetRatio = tr.width() / tr.height() if tr.height() != 0 else 1
## This is the view range aspect ratio we need to obey aspect constraint
viewRatio = (bounds.width() / bounds.height() if bounds.height() != 0 else 1) / aspect
viewRatio = 1 if viewRatio == 0 else viewRatio
# Decide which range to keep unchanged
#print self.name, "aspect:", aspect, "changed:", changed, "auto:", self.state['autoRange']
if forceX:
ax = 0
elif forceY:
ax = 1
else:
# if we are not required to keep a particular axis unchanged,
# then make the entire target range visible
ax = 0 if targetRatio > viewRatio else 1
if ax == 0:
## view range needs to be taller than target
dy = 0.5 * (tr.width() / viewRatio - tr.height())
if dy != 0:
changed[1] = True
viewRange[1] = [self.state['targetRange'][1][0] - dy, self.state['targetRange'][1][1] + dy]
else:
## view range needs to be wider than target
dx = 0.5 * (tr.height() * viewRatio - tr.width())
if dx != 0:
changed[0] = True
viewRange[0] = [self.state['targetRange'][0][0] - dx, self.state['targetRange'][0][1] + dx]
# ----------- Make corrections for view limits -----------
limits = (self.state['limits']['xLimits'], self.state['limits']['yLimits'])
minRng = [self.state['limits']['xRange'][0], self.state['limits']['yRange'][0]]
maxRng = [self.state['limits']['xRange'][1], self.state['limits']['yRange'][1]]
for axis in [0, 1]:
if limits[axis][0] is None and limits[axis][1] is None and minRng[axis] is None and maxRng[axis] is None:
continue
# max range cannot be larger than bounds, if they are given
if limits[axis][0] is not None and limits[axis][1] is not None:
if maxRng[axis] is not None:
maxRng[axis] = min(maxRng[axis], limits[axis][1]-limits[axis][0])
else:
maxRng[axis] = limits[axis][1]-limits[axis][0]
#print "\nLimits for axis %d: range=%s min=%s max=%s" % (axis, limits[axis], minRng[axis], maxRng[axis])
#print "Starting range:", viewRange[axis]
# Apply xRange, yRange
diff = viewRange[axis][1] - viewRange[axis][0]
if maxRng[axis] is not None and diff > maxRng[axis]:
delta = maxRng[axis] - diff
changed[axis] = True
elif minRng[axis] is not None and diff < minRng[axis]:
delta = minRng[axis] - diff
changed[axis] = True
else:
delta = 0
viewRange[axis][0] -= delta/2.
viewRange[axis][1] += delta/2.
#print "after applying min/max:", viewRange[axis]
# Apply xLimits, yLimits
mn, mx = limits[axis]
if mn is not None and viewRange[axis][0] < mn:
delta = mn - viewRange[axis][0]
viewRange[axis][0] += delta
viewRange[axis][1] += delta
changed[axis] = True
elif mx is not None and viewRange[axis][1] > mx:
delta = mx - viewRange[axis][1]
viewRange[axis][0] += delta
viewRange[axis][1] += delta
changed[axis] = True
#print "after applying edge limits:", viewRange[axis]
changed = [(viewRange[i][0] != self.state['viewRange'][i][0]) or (viewRange[i][1] != self.state['viewRange'][i][1]) for i in (0,1)]
self.state['viewRange'] = viewRange
if any(changed):
self._matrixNeedsUpdate = True
self.update()
# Inform linked views that the range has changed
for ax in [0, 1]:
if not changed[ax]:
continue
link = self.linkedView(ax)
if link is not None:
link.linkedViewChanged(self, ax)
# emit range change signals
if changed[0]:
self.sigXRangeChanged.emit(self, tuple(self.state['viewRange'][0]))
if changed[1]:
self.sigYRangeChanged.emit(self, tuple(self.state['viewRange'][1]))
self.sigRangeChanged.emit(self, self.state['viewRange'])
def updateMatrix(self, changed=None):
if not self._matrixNeedsUpdate:
return
## Make the childGroup's transform match the requested viewRange.
bounds = self.rect()
vr = self.viewRect()
if vr.height() == 0 or vr.width() == 0:
return
scale = Point(bounds.width()/vr.width(), bounds.height()/vr.height())
if not self.state['yInverted']:
scale = scale * Point(1, -1)
if self.state['xInverted']:
scale = scale * Point(-1, 1)
m = QtGui.QTransform()
## First center the viewport at 0
center = bounds.center()
m.translate(center.x(), center.y())
## Now scale and translate properly
m.scale(scale[0], scale[1])
st = Point(vr.center())
m.translate(-st[0], -st[1])
self.childGroup.setTransform(m)
self._matrixNeedsUpdate = False
self.sigTransformChanged.emit(self) ## segfaults here: 1
def paint(self, p, opt, widget):
if self.border is not None:
bounds = self.shape()
p.setPen(self.border)
#p.fillRect(bounds, QtGui.QColor(0, 0, 0))
p.drawPath(bounds)
#p.setPen(fn.mkPen('r'))
#path = QtGui.QPainterPath()
#path.addRect(self.targetRect())
#tr = self.mapFromView(path)
#p.drawPath(tr)
def updateBackground(self):
bg = self.state['background']
if bg is None:
self.background.hide()
else:
self.background.show()
self.background.setBrush(fn.mkBrush(bg))
def updateViewLists(self):
try:
self.window()
except RuntimeError: ## this view has already been deleted; it will probably be collected shortly.
return
def view_key(view):
return (view.window() is self.window(), view.name)
## make a sorted list of all named views
nv = sorted(ViewBox.NamedViews.values(), key=view_key)
if self in nv:
nv.remove(self)
if self.menu is not None:
self.menu.setViewList(nv)
for ax in [0,1]:
link = self.state['linkedViews'][ax]
if isinstance(link, basestring): ## axis has not been linked yet; see if it's possible now
for v in nv:
if link == v.name:
self.linkView(ax, v)
@staticmethod
def updateAllViewLists():
for v in ViewBox.AllViews:
v.updateViewLists()
@staticmethod
def forgetView(vid, name):
if ViewBox is None: ## can happen as python is shutting down
return
if QtGui.QApplication.instance() is None:
return
## Called with ID and name of view (the view itself is no longer available)
for v in list(ViewBox.AllViews.keys()):
if id(v) == vid:
ViewBox.AllViews.pop(v)
break
ViewBox.NamedViews.pop(name, None)
ViewBox.updateAllViewLists()
@staticmethod
def quit():
## called when the application is about to exit.
## this disables all callbacks, which might otherwise generate errors if invoked during exit.
for k in ViewBox.AllViews:
if isQObjectAlive(k) and getConfigOption('crashWarning'):
sys.stderr.write('Warning: ViewBox should be closed before application exit.\n')
try:
k.destroyed.disconnect()
except RuntimeError: ## signal is already disconnected.
pass
except TypeError: ## view has already been deleted (?)
pass
except AttributeError: # PySide has deleted signal
pass
def locate(self, item, timeout=3.0, children=False):
"""
Temporarily display the bounding rect of an item and lines connecting to the center of the view.
This is useful for determining the location of items that may be out of the range of the ViewBox.
if allChildren is True, then the bounding rect of all item's children will be shown instead.
"""
self.clearLocate()
if item.scene() is not self.scene():
raise Exception("Item does not share a scene with this ViewBox.")
c = self.viewRect().center()
if children:
br = self.mapFromItemToView(item, item.childrenBoundingRect()).boundingRect()
else:
br = self.mapFromItemToView(item, item.boundingRect()).boundingRect()
g = ItemGroup()
g.setParentItem(self.childGroup)
self.locateGroup = g
g.box = QtGui.QGraphicsRectItem(br)
g.box.setParentItem(g)
g.lines = []
for p in (br.topLeft(), br.bottomLeft(), br.bottomRight(), br.topRight()):
line = QtGui.QGraphicsLineItem(c.x(), c.y(), p.x(), p.y())
line.setParentItem(g)
g.lines.append(line)
for item in g.childItems():
item.setPen(fn.mkPen(color='y', width=3))
g.setZValue(1000000)
if children:
g.path = QtGui.QGraphicsPathItem(g.childrenShape())
else:
g.path = QtGui.QGraphicsPathItem(g.shape())
g.path.setParentItem(g)
g.path.setPen(fn.mkPen('g'))
g.path.setZValue(100)
QtCore.QTimer.singleShot(timeout*1000, self.clearLocate)
def clearLocate(self):
if self.locateGroup is None:
return
self.scene().removeItem(self.locateGroup)
self.locateGroup = None
from .ViewBoxMenu import ViewBoxMenu
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/ViewBox/__init__.py | .py | 29 | 2 | from .ViewBox import ViewBox
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/ViewBox/axisCtrlTemplate_pyqt.py | .py | 6,134 | 103 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './pyqtgraph/graphicsItems/ViewBox/axisCtrlTemplate.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 ...Qt 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(186, 154)
Form.setMaximumSize(QtCore.QSize(200, 16777215))
self.gridLayout = QtGui.QGridLayout(Form)
self.gridLayout.setMargin(0)
self.gridLayout.setSpacing(0)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.label = QtGui.QLabel(Form)
self.label.setObjectName(_fromUtf8("label"))
self.gridLayout.addWidget(self.label, 7, 0, 1, 2)
self.linkCombo = QtGui.QComboBox(Form)
self.linkCombo.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToContents)
self.linkCombo.setObjectName(_fromUtf8("linkCombo"))
self.gridLayout.addWidget(self.linkCombo, 7, 2, 1, 2)
self.autoPercentSpin = QtGui.QSpinBox(Form)
self.autoPercentSpin.setEnabled(True)
self.autoPercentSpin.setMinimum(1)
self.autoPercentSpin.setMaximum(100)
self.autoPercentSpin.setSingleStep(1)
self.autoPercentSpin.setProperty("value", 100)
self.autoPercentSpin.setObjectName(_fromUtf8("autoPercentSpin"))
self.gridLayout.addWidget(self.autoPercentSpin, 2, 2, 1, 2)
self.autoRadio = QtGui.QRadioButton(Form)
self.autoRadio.setChecked(True)
self.autoRadio.setObjectName(_fromUtf8("autoRadio"))
self.gridLayout.addWidget(self.autoRadio, 2, 0, 1, 2)
self.manualRadio = QtGui.QRadioButton(Form)
self.manualRadio.setObjectName(_fromUtf8("manualRadio"))
self.gridLayout.addWidget(self.manualRadio, 1, 0, 1, 2)
self.minText = QtGui.QLineEdit(Form)
self.minText.setObjectName(_fromUtf8("minText"))
self.gridLayout.addWidget(self.minText, 1, 2, 1, 1)
self.maxText = QtGui.QLineEdit(Form)
self.maxText.setObjectName(_fromUtf8("maxText"))
self.gridLayout.addWidget(self.maxText, 1, 3, 1, 1)
self.invertCheck = QtGui.QCheckBox(Form)
self.invertCheck.setObjectName(_fromUtf8("invertCheck"))
self.gridLayout.addWidget(self.invertCheck, 5, 0, 1, 4)
self.mouseCheck = QtGui.QCheckBox(Form)
self.mouseCheck.setChecked(True)
self.mouseCheck.setObjectName(_fromUtf8("mouseCheck"))
self.gridLayout.addWidget(self.mouseCheck, 6, 0, 1, 4)
self.visibleOnlyCheck = QtGui.QCheckBox(Form)
self.visibleOnlyCheck.setObjectName(_fromUtf8("visibleOnlyCheck"))
self.gridLayout.addWidget(self.visibleOnlyCheck, 3, 2, 1, 2)
self.autoPanCheck = QtGui.QCheckBox(Form)
self.autoPanCheck.setObjectName(_fromUtf8("autoPanCheck"))
self.gridLayout.addWidget(self.autoPanCheck, 4, 2, 1, 2)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Form", None))
self.label.setText(_translate("Form", "Link Axis:", None))
self.linkCombo.setToolTip(_translate("Form", "<html><head/><body><p>Links this axis with another view. When linked, both views will display the same data range.</p></body></html>", None))
self.autoPercentSpin.setToolTip(_translate("Form", "<html><head/><body><p>Percent of data to be visible when auto-scaling. It may be useful to decrease this value for data with spiky noise.</p></body></html>", None))
self.autoPercentSpin.setSuffix(_translate("Form", "%", None))
self.autoRadio.setToolTip(_translate("Form", "<html><head/><body><p>Automatically resize this axis whenever the displayed data is changed.</p></body></html>", None))
self.autoRadio.setText(_translate("Form", "Auto", None))
self.manualRadio.setToolTip(_translate("Form", "<html><head/><body><p>Set the range for this axis manually. This disables automatic scaling. </p></body></html>", None))
self.manualRadio.setText(_translate("Form", "Manual", None))
self.minText.setToolTip(_translate("Form", "<html><head/><body><p>Minimum value to display for this axis.</p></body></html>", None))
self.minText.setText(_translate("Form", "0", None))
self.maxText.setToolTip(_translate("Form", "<html><head/><body><p>Maximum value to display for this axis.</p></body></html>", None))
self.maxText.setText(_translate("Form", "0", None))
self.invertCheck.setToolTip(_translate("Form", "<html><head/><body><p>Inverts the display of this axis. (+y points downward instead of upward)</p></body></html>", None))
self.invertCheck.setText(_translate("Form", "Invert Axis", None))
self.mouseCheck.setToolTip(_translate("Form", "<html><head/><body><p>Enables mouse interaction (panning, scaling) for this axis.</p></body></html>", None))
self.mouseCheck.setText(_translate("Form", "Mouse Enabled", None))
self.visibleOnlyCheck.setToolTip(_translate("Form", "<html><head/><body><p>When checked, the axis will only auto-scale to data that is visible along the orthogonal axis.</p></body></html>", None))
self.visibleOnlyCheck.setText(_translate("Form", "Visible Data Only", None))
self.autoPanCheck.setToolTip(_translate("Form", "<html><head/><body><p>When checked, the axis will automatically pan to center on the current data, but the scale along this axis will not change.</p></body></html>", None))
self.autoPanCheck.setText(_translate("Form", "Auto Pan Only", None))
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/ViewBox/axisCtrlTemplate_pyside.py | .py | 6,650 | 89 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './pyqtgraph/graphicsItems/ViewBox/axisCtrlTemplate.ui'
#
# Created: Mon Dec 23 10:10:51 2013
# by: pyside-uic 0.2.14 running on PySide 1.1.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(186, 154)
Form.setMaximumSize(QtCore.QSize(200, 16777215))
self.gridLayout = QtGui.QGridLayout(Form)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setSpacing(0)
self.gridLayout.setObjectName("gridLayout")
self.label = QtGui.QLabel(Form)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 7, 0, 1, 2)
self.linkCombo = QtGui.QComboBox(Form)
self.linkCombo.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToContents)
self.linkCombo.setObjectName("linkCombo")
self.gridLayout.addWidget(self.linkCombo, 7, 2, 1, 2)
self.autoPercentSpin = QtGui.QSpinBox(Form)
self.autoPercentSpin.setEnabled(True)
self.autoPercentSpin.setMinimum(1)
self.autoPercentSpin.setMaximum(100)
self.autoPercentSpin.setSingleStep(1)
self.autoPercentSpin.setProperty("value", 100)
self.autoPercentSpin.setObjectName("autoPercentSpin")
self.gridLayout.addWidget(self.autoPercentSpin, 2, 2, 1, 2)
self.autoRadio = QtGui.QRadioButton(Form)
self.autoRadio.setChecked(True)
self.autoRadio.setObjectName("autoRadio")
self.gridLayout.addWidget(self.autoRadio, 2, 0, 1, 2)
self.manualRadio = QtGui.QRadioButton(Form)
self.manualRadio.setObjectName("manualRadio")
self.gridLayout.addWidget(self.manualRadio, 1, 0, 1, 2)
self.minText = QtGui.QLineEdit(Form)
self.minText.setObjectName("minText")
self.gridLayout.addWidget(self.minText, 1, 2, 1, 1)
self.maxText = QtGui.QLineEdit(Form)
self.maxText.setObjectName("maxText")
self.gridLayout.addWidget(self.maxText, 1, 3, 1, 1)
self.invertCheck = QtGui.QCheckBox(Form)
self.invertCheck.setObjectName("invertCheck")
self.gridLayout.addWidget(self.invertCheck, 5, 0, 1, 4)
self.mouseCheck = QtGui.QCheckBox(Form)
self.mouseCheck.setChecked(True)
self.mouseCheck.setObjectName("mouseCheck")
self.gridLayout.addWidget(self.mouseCheck, 6, 0, 1, 4)
self.visibleOnlyCheck = QtGui.QCheckBox(Form)
self.visibleOnlyCheck.setObjectName("visibleOnlyCheck")
self.gridLayout.addWidget(self.visibleOnlyCheck, 3, 2, 1, 2)
self.autoPanCheck = QtGui.QCheckBox(Form)
self.autoPanCheck.setObjectName("autoPanCheck")
self.gridLayout.addWidget(self.autoPanCheck, 4, 2, 1, 2)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("Form", "Link Axis:", None, QtGui.QApplication.UnicodeUTF8))
self.linkCombo.setToolTip(QtGui.QApplication.translate("Form", "<html><head/><body><p>Links this axis with another view. When linked, both views will display the same data range.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.autoPercentSpin.setToolTip(QtGui.QApplication.translate("Form", "<html><head/><body><p>Percent of data to be visible when auto-scaling. It may be useful to decrease this value for data with spiky noise.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.autoPercentSpin.setSuffix(QtGui.QApplication.translate("Form", "%", None, QtGui.QApplication.UnicodeUTF8))
self.autoRadio.setToolTip(QtGui.QApplication.translate("Form", "<html><head/><body><p>Automatically resize this axis whenever the displayed data is changed.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.autoRadio.setText(QtGui.QApplication.translate("Form", "Auto", None, QtGui.QApplication.UnicodeUTF8))
self.manualRadio.setToolTip(QtGui.QApplication.translate("Form", "<html><head/><body><p>Set the range for this axis manually. This disables automatic scaling. </p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.manualRadio.setText(QtGui.QApplication.translate("Form", "Manual", None, QtGui.QApplication.UnicodeUTF8))
self.minText.setToolTip(QtGui.QApplication.translate("Form", "<html><head/><body><p>Minimum value to display for this axis.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.minText.setText(QtGui.QApplication.translate("Form", "0", None, QtGui.QApplication.UnicodeUTF8))
self.maxText.setToolTip(QtGui.QApplication.translate("Form", "<html><head/><body><p>Maximum value to display for this axis.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.maxText.setText(QtGui.QApplication.translate("Form", "0", None, QtGui.QApplication.UnicodeUTF8))
self.invertCheck.setToolTip(QtGui.QApplication.translate("Form", "<html><head/><body><p>Inverts the display of this axis. (+y points downward instead of upward)</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.invertCheck.setText(QtGui.QApplication.translate("Form", "Invert Axis", None, QtGui.QApplication.UnicodeUTF8))
self.mouseCheck.setToolTip(QtGui.QApplication.translate("Form", "<html><head/><body><p>Enables mouse interaction (panning, scaling) for this axis.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.mouseCheck.setText(QtGui.QApplication.translate("Form", "Mouse Enabled", None, QtGui.QApplication.UnicodeUTF8))
self.visibleOnlyCheck.setToolTip(QtGui.QApplication.translate("Form", "<html><head/><body><p>When checked, the axis will only auto-scale to data that is visible along the orthogonal axis.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.visibleOnlyCheck.setText(QtGui.QApplication.translate("Form", "Visible Data Only", None, QtGui.QApplication.UnicodeUTF8))
self.autoPanCheck.setToolTip(QtGui.QApplication.translate("Form", "<html><head/><body><p>When checked, the axis will automatically pan to center on the current data, but the scale along this axis will not change.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.autoPanCheck.setText(QtGui.QApplication.translate("Form", "Auto Pan Only", None, QtGui.QApplication.UnicodeUTF8))
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/ViewBox/axisCtrlTemplate_pyside2.py | .py | 5,581 | 90 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './pyqtgraph/graphicsItems/ViewBox/axisCtrlTemplate.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(186, 154)
Form.setMaximumSize(QtCore.QSize(200, 16777215))
self.gridLayout = QtWidgets.QGridLayout(Form)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setSpacing(0)
self.gridLayout.setObjectName("gridLayout")
self.label = QtWidgets.QLabel(Form)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 7, 0, 1, 2)
self.linkCombo = QtWidgets.QComboBox(Form)
self.linkCombo.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)
self.linkCombo.setObjectName("linkCombo")
self.gridLayout.addWidget(self.linkCombo, 7, 2, 1, 2)
self.autoPercentSpin = QtWidgets.QSpinBox(Form)
self.autoPercentSpin.setEnabled(True)
self.autoPercentSpin.setMinimum(1)
self.autoPercentSpin.setMaximum(100)
self.autoPercentSpin.setSingleStep(1)
self.autoPercentSpin.setProperty("value", 100)
self.autoPercentSpin.setObjectName("autoPercentSpin")
self.gridLayout.addWidget(self.autoPercentSpin, 2, 2, 1, 2)
self.autoRadio = QtWidgets.QRadioButton(Form)
self.autoRadio.setChecked(True)
self.autoRadio.setObjectName("autoRadio")
self.gridLayout.addWidget(self.autoRadio, 2, 0, 1, 2)
self.manualRadio = QtWidgets.QRadioButton(Form)
self.manualRadio.setObjectName("manualRadio")
self.gridLayout.addWidget(self.manualRadio, 1, 0, 1, 2)
self.minText = QtWidgets.QLineEdit(Form)
self.minText.setObjectName("minText")
self.gridLayout.addWidget(self.minText, 1, 2, 1, 1)
self.maxText = QtWidgets.QLineEdit(Form)
self.maxText.setObjectName("maxText")
self.gridLayout.addWidget(self.maxText, 1, 3, 1, 1)
self.invertCheck = QtWidgets.QCheckBox(Form)
self.invertCheck.setObjectName("invertCheck")
self.gridLayout.addWidget(self.invertCheck, 5, 0, 1, 4)
self.mouseCheck = QtWidgets.QCheckBox(Form)
self.mouseCheck.setChecked(True)
self.mouseCheck.setObjectName("mouseCheck")
self.gridLayout.addWidget(self.mouseCheck, 6, 0, 1, 4)
self.visibleOnlyCheck = QtWidgets.QCheckBox(Form)
self.visibleOnlyCheck.setObjectName("visibleOnlyCheck")
self.gridLayout.addWidget(self.visibleOnlyCheck, 3, 2, 1, 2)
self.autoPanCheck = QtWidgets.QCheckBox(Form)
self.autoPanCheck.setObjectName("autoPanCheck")
self.gridLayout.addWidget(self.autoPanCheck, 4, 2, 1, 2)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.label.setText(_translate("Form", "Link Axis:"))
self.linkCombo.setToolTip(_translate("Form", "<html><head/><body><p>Links this axis with another view. When linked, both views will display the same data range.</p></body></html>"))
self.autoPercentSpin.setToolTip(_translate("Form", "<html><head/><body><p>Percent of data to be visible when auto-scaling. It may be useful to decrease this value for data with spiky noise.</p></body></html>"))
self.autoPercentSpin.setSuffix(_translate("Form", "%"))
self.autoRadio.setToolTip(_translate("Form", "<html><head/><body><p>Automatically resize this axis whenever the displayed data is changed.</p></body></html>"))
self.autoRadio.setText(_translate("Form", "Auto"))
self.manualRadio.setToolTip(_translate("Form", "<html><head/><body><p>Set the range for this axis manually. This disables automatic scaling. </p></body></html>"))
self.manualRadio.setText(_translate("Form", "Manual"))
self.minText.setToolTip(_translate("Form", "<html><head/><body><p>Minimum value to display for this axis.</p></body></html>"))
self.minText.setText(_translate("Form", "0"))
self.maxText.setToolTip(_translate("Form", "<html><head/><body><p>Maximum value to display for this axis.</p></body></html>"))
self.maxText.setText(_translate("Form", "0"))
self.invertCheck.setToolTip(_translate("Form", "<html><head/><body><p>Inverts the display of this axis. (+y points downward instead of upward)</p></body></html>"))
self.invertCheck.setText(_translate("Form", "Invert Axis"))
self.mouseCheck.setToolTip(_translate("Form", "<html><head/><body><p>Enables mouse interaction (panning, scaling) for this axis.</p></body></html>"))
self.mouseCheck.setText(_translate("Form", "Mouse Enabled"))
self.visibleOnlyCheck.setToolTip(_translate("Form", "<html><head/><body><p>When checked, the axis will only auto-scale to data that is visible along the orthogonal axis.</p></body></html>"))
self.visibleOnlyCheck.setText(_translate("Form", "Visible Data Only"))
self.autoPanCheck.setToolTip(_translate("Form", "<html><head/><body><p>When checked, the axis will automatically pan to center on the current data, but the scale along this axis will not change.</p></body></html>"))
self.autoPanCheck.setText(_translate("Form", "Auto Pan Only"))
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/ViewBox/ViewBoxMenu.py | .py | 10,034 | 279 | # -*- coding: utf-8 -*-
from ...Qt import QtCore, QtGui, QT_LIB
from ...python2_3 import asUnicode
from ...WidgetGroup import WidgetGroup
if QT_LIB == 'PyQt4':
from .axisCtrlTemplate_pyqt import Ui_Form as AxisCtrlTemplate
elif QT_LIB == 'PySide':
from .axisCtrlTemplate_pyside import Ui_Form as AxisCtrlTemplate
elif QT_LIB == 'PyQt5':
from .axisCtrlTemplate_pyqt5 import Ui_Form as AxisCtrlTemplate
elif QT_LIB == 'PySide2':
from .axisCtrlTemplate_pyside2 import Ui_Form as AxisCtrlTemplate
import weakref
class ViewBoxMenu(QtGui.QMenu):
def __init__(self, view):
QtGui.QMenu.__init__(self)
self.view = weakref.ref(view) ## keep weakref to view to avoid circular reference (don't know why, but this prevents the ViewBox from being collected)
self.valid = False ## tells us whether the ui needs to be updated
self.viewMap = weakref.WeakValueDictionary() ## weakrefs to all views listed in the link combos
self.setTitle("ViewBox options")
self.viewAll = QtGui.QAction("View All", self)
self.viewAll.triggered.connect(self.autoRange)
self.addAction(self.viewAll)
self.axes = []
self.ctrl = []
self.widgetGroups = []
self.dv = QtGui.QDoubleValidator(self)
for axis in 'XY':
m = QtGui.QMenu()
m.setTitle("%s Axis" % axis)
w = QtGui.QWidget()
ui = AxisCtrlTemplate()
ui.setupUi(w)
a = QtGui.QWidgetAction(self)
a.setDefaultWidget(w)
m.addAction(a)
self.addMenu(m)
self.axes.append(m)
self.ctrl.append(ui)
wg = WidgetGroup(w)
self.widgetGroups.append(w)
connects = [
(ui.mouseCheck.toggled, 'MouseToggled'),
(ui.manualRadio.clicked, 'ManualClicked'),
(ui.minText.editingFinished, 'RangeTextChanged'),
(ui.maxText.editingFinished, 'RangeTextChanged'),
(ui.autoRadio.clicked, 'AutoClicked'),
(ui.autoPercentSpin.valueChanged, 'AutoSpinChanged'),
(ui.linkCombo.currentIndexChanged, 'LinkComboChanged'),
(ui.autoPanCheck.toggled, 'AutoPanToggled'),
(ui.visibleOnlyCheck.toggled, 'VisibleOnlyToggled')
]
for sig, fn in connects:
sig.connect(getattr(self, axis.lower()+fn))
self.ctrl[0].invertCheck.toggled.connect(self.xInvertToggled)
self.ctrl[1].invertCheck.toggled.connect(self.yInvertToggled)
## exporting is handled by GraphicsScene now
#self.export = QtGui.QMenu("Export")
#self.setExportMethods(view.exportMethods)
#self.addMenu(self.export)
self.leftMenu = QtGui.QMenu("Mouse Mode")
group = QtGui.QActionGroup(self)
# This does not work! QAction _must_ be initialized with a permanent
# object as the parent or else it may be collected prematurely.
#pan = self.leftMenu.addAction("3 button", self.set3ButtonMode)
#zoom = self.leftMenu.addAction("1 button", self.set1ButtonMode)
pan = QtGui.QAction("3 button", self.leftMenu)
zoom = QtGui.QAction("1 button", self.leftMenu)
self.leftMenu.addAction(pan)
self.leftMenu.addAction(zoom)
pan.triggered.connect(self.set3ButtonMode)
zoom.triggered.connect(self.set1ButtonMode)
pan.setCheckable(True)
zoom.setCheckable(True)
pan.setActionGroup(group)
zoom.setActionGroup(group)
self.mouseModes = [pan, zoom]
self.addMenu(self.leftMenu)
self.view().sigStateChanged.connect(self.viewStateChanged)
self.updateState()
def setExportMethods(self, methods):
self.exportMethods = methods
self.export.clear()
for opt, fn in methods.items():
self.export.addAction(opt, self.exportMethod)
def viewStateChanged(self):
self.valid = False
if self.ctrl[0].minText.isVisible() or self.ctrl[1].minText.isVisible():
self.updateState()
def updateState(self):
## Something about the viewbox has changed; update the menu GUI
state = self.view().getState(copy=False)
if state['mouseMode'] == ViewBox.PanMode:
self.mouseModes[0].setChecked(True)
else:
self.mouseModes[1].setChecked(True)
for i in [0,1]: # x, y
tr = state['targetRange'][i]
self.ctrl[i].minText.setText("%0.5g" % tr[0])
self.ctrl[i].maxText.setText("%0.5g" % tr[1])
if state['autoRange'][i] is not False:
self.ctrl[i].autoRadio.setChecked(True)
if state['autoRange'][i] is not True:
self.ctrl[i].autoPercentSpin.setValue(state['autoRange'][i]*100)
else:
self.ctrl[i].manualRadio.setChecked(True)
self.ctrl[i].mouseCheck.setChecked(state['mouseEnabled'][i])
## Update combo to show currently linked view
c = self.ctrl[i].linkCombo
c.blockSignals(True)
try:
view = state['linkedViews'][i] ## will always be string or None
if view is None:
view = ''
ind = c.findText(view)
if ind == -1:
ind = 0
c.setCurrentIndex(ind)
finally:
c.blockSignals(False)
self.ctrl[i].autoPanCheck.setChecked(state['autoPan'][i])
self.ctrl[i].visibleOnlyCheck.setChecked(state['autoVisibleOnly'][i])
xy = ['x', 'y'][i]
self.ctrl[i].invertCheck.setChecked(state.get(xy+'Inverted', False))
self.valid = True
def popup(self, *args):
if not self.valid:
self.updateState()
QtGui.QMenu.popup(self, *args)
def autoRange(self):
self.view().autoRange() ## don't let signal call this directly--it'll add an unwanted argument
def xMouseToggled(self, b):
self.view().setMouseEnabled(x=b)
def xManualClicked(self):
self.view().enableAutoRange(ViewBox.XAxis, False)
def xRangeTextChanged(self):
self.ctrl[0].manualRadio.setChecked(True)
self.view().setXRange(*self._validateRangeText(0), padding=0)
def xAutoClicked(self):
val = self.ctrl[0].autoPercentSpin.value() * 0.01
self.view().enableAutoRange(ViewBox.XAxis, val)
def xAutoSpinChanged(self, val):
self.ctrl[0].autoRadio.setChecked(True)
self.view().enableAutoRange(ViewBox.XAxis, val*0.01)
def xLinkComboChanged(self, ind):
self.view().setXLink(str(self.ctrl[0].linkCombo.currentText()))
def xAutoPanToggled(self, b):
self.view().setAutoPan(x=b)
def xVisibleOnlyToggled(self, b):
self.view().setAutoVisible(x=b)
def yMouseToggled(self, b):
self.view().setMouseEnabled(y=b)
def yManualClicked(self):
self.view().enableAutoRange(ViewBox.YAxis, False)
def yRangeTextChanged(self):
self.ctrl[1].manualRadio.setChecked(True)
self.view().setYRange(*self._validateRangeText(1), padding=0)
def yAutoClicked(self):
val = self.ctrl[1].autoPercentSpin.value() * 0.01
self.view().enableAutoRange(ViewBox.YAxis, val)
def yAutoSpinChanged(self, val):
self.ctrl[1].autoRadio.setChecked(True)
self.view().enableAutoRange(ViewBox.YAxis, val*0.01)
def yLinkComboChanged(self, ind):
self.view().setYLink(str(self.ctrl[1].linkCombo.currentText()))
def yAutoPanToggled(self, b):
self.view().setAutoPan(y=b)
def yVisibleOnlyToggled(self, b):
self.view().setAutoVisible(y=b)
def yInvertToggled(self, b):
self.view().invertY(b)
def xInvertToggled(self, b):
self.view().invertX(b)
def exportMethod(self):
act = self.sender()
self.exportMethods[str(act.text())]()
def set3ButtonMode(self):
self.view().setLeftButtonAction('pan')
def set1ButtonMode(self):
self.view().setLeftButtonAction('rect')
def setViewList(self, views):
names = ['']
self.viewMap.clear()
## generate list of views to show in the link combo
for v in views:
name = v.name
if name is None: ## unnamed views do not show up in the view list (although they are linkable)
continue
names.append(name)
self.viewMap[name] = v
for i in [0,1]:
c = self.ctrl[i].linkCombo
current = asUnicode(c.currentText())
c.blockSignals(True)
changed = True
try:
c.clear()
for name in names:
c.addItem(name)
if name == current:
changed = False
c.setCurrentIndex(c.count()-1)
finally:
c.blockSignals(False)
if changed:
c.setCurrentIndex(0)
c.currentIndexChanged.emit(c.currentIndex())
def _validateRangeText(self, axis):
"""Validate range text inputs. Return current value(s) if invalid."""
inputs = (self.ctrl[axis].minText.text(),
self.ctrl[axis].maxText.text())
vals = self.view().viewRange()[axis]
for i, text in enumerate(inputs):
try:
vals[i] = float(text)
except ValueError:
# could not convert string to float
pass
return vals
from .ViewBox import ViewBox
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/ViewBox/tests/test_ViewBox.py | .py | 2,631 | 103 | #import PySide
import pyqtgraph as pg
import pytest
app = pg.mkQApp()
qtest = pg.Qt.QtTest.QTest
QRectF = pg.QtCore.QRectF
def assertMapping(vb, r1, r2):
assert vb.mapFromView(r1.topLeft()) == r2.topLeft()
assert vb.mapFromView(r1.bottomLeft()) == r2.bottomLeft()
assert vb.mapFromView(r1.topRight()) == r2.topRight()
assert vb.mapFromView(r1.bottomRight()) == r2.bottomRight()
def init_viewbox():
"""Helper function to init the ViewBox
"""
global win, vb
win = pg.GraphicsWindow()
win.ci.layout.setContentsMargins(0,0,0,0)
win.resize(200, 200)
win.show()
vb = win.addViewBox()
# set range before viewbox is shown
vb.setRange(xRange=[0, 10], yRange=[0, 10], padding=0)
# required to make mapFromView work properly.
qtest.qWaitForWindowShown(win)
g = pg.GridItem()
vb.addItem(g)
app.processEvents()
def test_ViewBox():
init_viewbox()
w = vb.geometry().width()
h = vb.geometry().height()
view1 = QRectF(0, 0, 10, 10)
size1 = QRectF(0, h, w, -h)
assertMapping(vb, view1, size1)
# test resize
win.resize(400, 400)
app.processEvents()
w = vb.geometry().width()
h = vb.geometry().height()
size1 = QRectF(0, h, w, -h)
assertMapping(vb, view1, size1)
# now lock aspect
vb.setAspectLocked()
# test wide resize
win.resize(800, 400)
app.processEvents()
w = vb.geometry().width()
h = vb.geometry().height()
view1 = QRectF(-5, 0, 20, 10)
size1 = QRectF(0, h, w, -h)
assertMapping(vb, view1, size1)
# test tall resize
win.resize(200, 400)
app.processEvents()
w = vb.geometry().width()
h = vb.geometry().height()
view1 = QRectF(0, -5, 10, 20)
size1 = QRectF(0, h, w, -h)
assertMapping(vb, view1, size1)
win.close()
def test_ViewBox_setMenuEnabled():
init_viewbox()
vb.setMenuEnabled(True)
assert vb.menu is not None
vb.setMenuEnabled(False)
assert vb.menu is None
skipreason = "Skipping this test until someone has time to fix it."
@pytest.mark.skipif(True, reason=skipreason)
def test_limits_and_resize():
init_viewbox()
# now lock aspect
vb.setAspectLocked()
# test limits + resize (aspect ratio constraint has priority over limits
win.resize(400, 400)
app.processEvents()
vb.setLimits(xMin=0, xMax=10, yMin=0, yMax=10)
win.resize(800, 400)
app.processEvents()
w = vb.geometry().width()
h = vb.geometry().height()
view1 = QRectF(-5, 0, 20, 10)
size1 = QRectF(0, h, w, -h)
assertMapping(vb, view1, size1)
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/tests/test_PlotDataItem.py | .py | 2,033 | 91 | import numpy as np
import pyqtgraph as pg
pg.mkQApp()
def test_fft():
f = 20.
x = np.linspace(0, 1, 1000)
y = np.sin(2 * np.pi * f * x)
pd = pg.PlotDataItem(x, y)
pd.setFftMode(True)
x, y = pd.getData()
assert abs(x[np.argmax(y)] - f) < 0.03
x = np.linspace(0, 1, 1001)
y = np.sin(2 * np.pi * f * x)
pd.setData(x, y)
x, y = pd.getData()
assert abs(x[np.argmax(y)]- f) < 0.03
pd.setLogMode(True, False)
x, y = pd.getData()
assert abs(x[np.argmax(y)] - np.log10(f)) < 0.01
def test_setData():
pdi = pg.PlotDataItem()
#test empty data
pdi.setData([])
#test y data
y = list(np.random.normal(size=100))
pdi.setData(y)
assert len(pdi.xData) == 100
assert len(pdi.yData) == 100
#test x, y data
y += list(np.random.normal(size=50))
x = np.linspace(5, 10, 150)
pdi.setData(x, y)
assert len(pdi.xData) == 150
assert len(pdi.yData) == 150
#test dict of x, y list
y += list(np.random.normal(size=50))
x = list(np.linspace(5, 10, 200))
pdi.setData({'x': x, 'y': y})
assert len(pdi.xData) == 200
assert len(pdi.yData) == 200
def test_clear():
y = list(np.random.normal(size=100))
x = np.linspace(5, 10, 100)
pdi = pg.PlotDataItem(x, y)
pdi.clear()
assert pdi.xData == None
assert pdi.yData == None
def test_clear_in_step_mode():
w = pg.PlotWidget()
c = pg.PlotDataItem([1,4,2,3], [5,7,6], stepMode=True)
w.addItem(c)
c.clear()
def test_clipping():
y = np.random.normal(size=150)
x = np.exp2(np.linspace(5, 10, 150)) # non-uniform spacing
w = pg.PlotWidget(autoRange=True, downsample=5)
c = pg.PlotDataItem(x, y)
w.addItem(c)
w.show()
c.setClipToView(True)
w.setXRange(200, 600)
for x_min in range(100, 2**10 - 100, 100):
w.setXRange(x_min, x_min + 100)
xDisp, _ = c.getData()
vr = c.viewRect()
assert xDisp[0] <= vr.left()
assert xDisp[-1] >= vr.right()
w.close()
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/tests/test_AxisItem.py | .py | 2,785 | 90 | import pyqtgraph as pg
app = pg.mkQApp()
def test_AxisItem_stopAxisAtTick(monkeypatch):
def test_bottom(p, axisSpec, tickSpecs, textSpecs):
assert view.mapToView(axisSpec[1]).x() == 0.25
assert view.mapToView(axisSpec[2]).x() == 0.75
def test_left(p, axisSpec, tickSpecs, textSpecs):
assert view.mapToView(axisSpec[1]).y() == 0.875
assert view.mapToView(axisSpec[2]).y() == 0.125
plot = pg.PlotWidget()
view = plot.plotItem.getViewBox()
bottom = plot.getAxis("bottom")
bottom.setRange(0, 1)
bticks = [(0.25, "a"), (0.6, "b"), (0.75, "c")]
bottom.setTicks([bticks, bticks])
bottom.setStyle(stopAxisAtTick=(True, True))
monkeypatch.setattr(bottom, "drawPicture", test_bottom)
left = plot.getAxis("left")
lticks = [(0.125, "a"), (0.55, "b"), (0.875, "c")]
left.setTicks([lticks, lticks])
left.setRange(0, 1)
left.setStyle(stopAxisAtTick=(True, True))
monkeypatch.setattr(left, "drawPicture", test_left)
plot.show()
app.processEvents()
plot.close()
def test_AxisItem_viewUnlink():
plot = pg.PlotWidget()
view = plot.plotItem.getViewBox()
axis = plot.getAxis("bottom")
assert axis.linkedView() == view
axis.unlinkFromView()
assert axis.linkedView() is None
class FakeSignal:
def __init__(self):
self.calls = []
def connect(self, *args, **kwargs):
self.calls.append('connect')
def disconnect(self, *args, **kwargs):
self.calls.append('disconnect')
class FakeView:
def __init__(self):
self.sigYRangeChanged = FakeSignal()
self.sigXRangeChanged = FakeSignal()
self.sigResized = FakeSignal()
def test_AxisItem_bottomRelink():
axis = pg.AxisItem('bottom')
fake_view = FakeView()
axis.linkToView(fake_view)
assert axis.linkedView() == fake_view
assert fake_view.sigYRangeChanged.calls == []
assert fake_view.sigXRangeChanged.calls == ['connect']
assert fake_view.sigResized.calls == ['connect']
axis.unlinkFromView()
assert fake_view.sigYRangeChanged.calls == []
assert fake_view.sigXRangeChanged.calls == ['connect', 'disconnect']
assert fake_view.sigResized.calls == ['connect', 'disconnect']
def test_AxisItem_leftRelink():
axis = pg.AxisItem('left')
fake_view = FakeView()
axis.linkToView(fake_view)
assert axis.linkedView() == fake_view
assert fake_view.sigYRangeChanged.calls == ['connect']
assert fake_view.sigXRangeChanged.calls == []
assert fake_view.sigResized.calls == ['connect']
axis.unlinkFromView()
assert fake_view.sigYRangeChanged.calls == ['connect', 'disconnect']
assert fake_view.sigXRangeChanged.calls == []
assert fake_view.sigResized.calls == ['connect', 'disconnect']
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/tests/test_ROI.py | .py | 8,578 | 240 | # -*- coding: utf-8 -*-
import sys
import numpy as np
import pytest
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtTest
from pyqtgraph.tests import assertImageApproved, mouseMove, mouseDrag, mouseClick, TransposedImageItem, resizeWindow
import pytest
app = pg.mkQApp()
def test_getArrayRegion(transpose=False):
pr = pg.PolyLineROI([[0, 0], [27, 0], [0, 28]], closed=True)
pr.setPos(1, 1)
rois = [
(pg.ROI([1, 1], [27, 28], pen='y'), 'baseroi'),
(pg.RectROI([1, 1], [27, 28], pen='y'), 'rectroi'),
(pg.EllipseROI([1, 1], [27, 28], pen='y'), 'ellipseroi'),
(pr, 'polylineroi'),
]
for roi, name in rois:
# For some ROIs, resize should not be used.
testResize = not isinstance(roi, pg.PolyLineROI)
origMode = pg.getConfigOption('imageAxisOrder')
try:
if transpose:
pg.setConfigOptions(imageAxisOrder='row-major')
check_getArrayRegion(roi, 'roi/'+name, testResize, transpose=True)
else:
pg.setConfigOptions(imageAxisOrder='col-major')
check_getArrayRegion(roi, 'roi/'+name, testResize)
finally:
pg.setConfigOptions(imageAxisOrder=origMode)
def test_getArrayRegion_axisorder():
test_getArrayRegion(transpose=True)
def check_getArrayRegion(roi, name, testResize=True, transpose=False):
initState = roi.getState()
#win = pg.GraphicsLayoutWidget()
win = pg.GraphicsView()
win.show()
resizeWindow(win, 200, 400)
# Don't use Qt's layouts for testing--these generate unpredictable results.
#vb1 = win.addViewBox()
#win.nextRow()
#vb2 = win.addViewBox()
# Instead, place the viewboxes manually
vb1 = pg.ViewBox()
win.scene().addItem(vb1)
vb1.setPos(6, 6)
vb1.resize(188, 191)
vb2 = pg.ViewBox()
win.scene().addItem(vb2)
vb2.setPos(6, 203)
vb2.resize(188, 191)
img1 = pg.ImageItem(border='w')
img2 = pg.ImageItem(border='w')
vb1.addItem(img1)
vb2.addItem(img2)
np.random.seed(0)
data = np.random.normal(size=(7, 30, 31, 5))
data[0, :, :, :] += 10
data[:, 1, :, :] += 10
data[:, :, 2, :] += 10
data[:, :, :, 3] += 10
if transpose:
data = data.transpose(0, 2, 1, 3)
img1.setImage(data[0, ..., 0])
vb1.setAspectLocked()
vb1.enableAutoRange(True, True)
roi.setZValue(10)
vb1.addItem(roi)
if isinstance(roi, pg.RectROI):
if transpose:
assert roi.getAffineSliceParams(data, img1, axes=(1, 2)) == ([28.0, 27.0], ((1.0, 0.0), (0.0, 1.0)), (1.0, 1.0))
else:
assert roi.getAffineSliceParams(data, img1, axes=(1, 2)) == ([27.0, 28.0], ((1.0, 0.0), (0.0, 1.0)), (1.0, 1.0))
rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
#assert np.all((rgn == data[:, 1:-2, 1:-2, :]) | (rgn == 0))
img2.setImage(rgn[0, ..., 0])
vb2.setAspectLocked()
vb2.enableAutoRange(True, True)
app.processEvents()
assertImageApproved(win, name+'/roi_getarrayregion', 'Simple ROI region selection.')
with pytest.raises(TypeError):
roi.setPos(0, False)
roi.setPos([0.5, 1.5])
rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
img2.setImage(rgn[0, ..., 0])
app.processEvents()
assertImageApproved(win, name+'/roi_getarrayregion_halfpx', 'Simple ROI region selection, 0.5 pixel shift.')
roi.setAngle(45)
roi.setPos([3, 0])
rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
img2.setImage(rgn[0, ..., 0])
app.processEvents()
assertImageApproved(win, name+'/roi_getarrayregion_rotate', 'Simple ROI region selection, rotation.')
if testResize:
roi.setSize([60, 60])
rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
img2.setImage(rgn[0, ..., 0])
app.processEvents()
assertImageApproved(win, name+'/roi_getarrayregion_resize', 'Simple ROI region selection, resized.')
img1.scale(1, -1)
img1.setPos(0, img1.height())
img1.rotate(20)
rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
img2.setImage(rgn[0, ..., 0])
app.processEvents()
assertImageApproved(win, name+'/roi_getarrayregion_img_trans', 'Simple ROI region selection, image transformed.')
vb1.invertY()
rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
img2.setImage(rgn[0, ..., 0])
app.processEvents()
# on windows, one edge of one ROI handle is shifted slightly; letting this slide with pxCount=10
if pg.Qt.QT_LIB in {'PyQt4', 'PySide'}:
pxCount = 10
else:
pxCount=-1
assertImageApproved(win, name+'/roi_getarrayregion_inverty', 'Simple ROI region selection, view inverted.', pxCount=pxCount)
roi.setState(initState)
img1.resetTransform()
img1.setPos(0, 0)
img1.scale(1, 0.5)
rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
img2.setImage(rgn[0, ..., 0])
app.processEvents()
assertImageApproved(win, name+'/roi_getarrayregion_anisotropic', 'Simple ROI region selection, image scaled anisotropically.')
# allow the roi to be re-used
roi.scene().removeItem(roi)
win.hide()
def test_PolyLineROI():
rois = [
(pg.PolyLineROI([[0, 0], [10, 0], [0, 15]], closed=True, pen=0.3), 'closed'),
(pg.PolyLineROI([[0, 0], [10, 0], [0, 15]], closed=False, pen=0.3), 'open')
]
#plt = pg.plot()
plt = pg.GraphicsView()
plt.show()
resizeWindow(plt, 200, 200)
vb = pg.ViewBox()
plt.scene().addItem(vb)
vb.resize(200, 200)
#plt.plotItem = pg.PlotItem()
#plt.scene().addItem(plt.plotItem)
#plt.plotItem.resize(200, 200)
plt.scene().minDragTime = 0 # let us simulate mouse drags very quickly.
# seemingly arbitrary requirements; might need longer wait time for some platforms..
QtTest.QTest.qWaitForWindowShown(plt)
QtTest.QTest.qWait(100)
for r, name in rois:
vb.clear()
vb.addItem(r)
vb.autoRange()
app.processEvents()
assertImageApproved(plt, 'roi/polylineroi/'+name+'_init', 'Init %s polyline.' % name)
initState = r.getState()
assert len(r.getState()['points']) == 3
# hover over center
center = r.mapToScene(pg.Point(3, 3))
mouseMove(plt, center)
assertImageApproved(plt, 'roi/polylineroi/'+name+'_hover_roi', 'Hover mouse over center of ROI.')
# drag ROI
mouseDrag(plt, center, center + pg.Point(10, -10), QtCore.Qt.LeftButton)
assertImageApproved(plt, 'roi/polylineroi/'+name+'_drag_roi', 'Drag mouse over center of ROI.')
# hover over handle
pt = r.mapToScene(pg.Point(r.getState()['points'][2]))
mouseMove(plt, pt)
assertImageApproved(plt, 'roi/polylineroi/'+name+'_hover_handle', 'Hover mouse over handle.')
# drag handle
mouseDrag(plt, pt, pt + pg.Point(5, 20), QtCore.Qt.LeftButton)
assertImageApproved(plt, 'roi/polylineroi/'+name+'_drag_handle', 'Drag mouse over handle.')
# hover over segment
pt = r.mapToScene((pg.Point(r.getState()['points'][2]) + pg.Point(r.getState()['points'][1])) * 0.5)
mouseMove(plt, pt+pg.Point(0, 2))
assertImageApproved(plt, 'roi/polylineroi/'+name+'_hover_segment', 'Hover mouse over diagonal segment.')
# click segment
mouseClick(plt, pt, QtCore.Qt.LeftButton)
assertImageApproved(plt, 'roi/polylineroi/'+name+'_click_segment', 'Click mouse over segment.')
# drag new handle
mouseMove(plt, pt+pg.Point(10, -10)) # pg bug: have to move the mouse off/on again to register hover
mouseDrag(plt, pt, pt + pg.Point(10, -10), QtCore.Qt.LeftButton)
assertImageApproved(plt, 'roi/polylineroi/'+name+'_drag_new_handle', 'Drag mouse over created handle.')
# clear all points
r.clearPoints()
assertImageApproved(plt, 'roi/polylineroi/'+name+'_clear', 'All points cleared.')
assert len(r.getState()['points']) == 0
# call setPoints
r.setPoints(initState['points'])
assertImageApproved(plt, 'roi/polylineroi/'+name+'_setpoints', 'Reset points to initial state.')
assert len(r.getState()['points']) == 3
# call setState
r.setState(initState)
assertImageApproved(plt, 'roi/polylineroi/'+name+'_setstate', 'Reset ROI to initial state.')
assert len(r.getState()['points']) == 3
plt.hide()
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/tests/test_PlotCurveItem.py | .py | 1,279 | 36 | import numpy as np
import pyqtgraph as pg
from pyqtgraph.tests import assertImageApproved
def test_PlotCurveItem():
p = pg.GraphicsWindow()
p.ci.layout.setContentsMargins(4, 4, 4, 4) # default margins vary by platform
v = p.addViewBox()
p.resize(200, 150)
data = np.array([1,4,2,3,np.inf,5,7,6,-np.inf,8,10,9,np.nan,-1,-2,0])
c = pg.PlotCurveItem(data)
v.addItem(c)
v.autoRange()
# Check auto-range works. Some platform differences may be expected..
checkRange = np.array([[-1.1457564053237301, 16.145756405323731], [-3.076811473165955, 11.076811473165955]])
assert np.allclose(v.viewRange(), checkRange)
assertImageApproved(p, 'plotcurveitem/connectall', "Plot curve with all points connected.")
c.setData(data, connect='pairs')
assertImageApproved(p, 'plotcurveitem/connectpairs', "Plot curve with pairs connected.")
c.setData(data, connect='finite')
assertImageApproved(p, 'plotcurveitem/connectfinite', "Plot curve with finite points connected.")
c.setData(data, connect=np.array([1,1,1,0,1,1,0,0,1,0,0,0,1,1,0,0]))
assertImageApproved(p, 'plotcurveitem/connectarray', "Plot curve with connection array.")
p.close()
if __name__ == '__main__':
test_PlotCurveItem()
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/tests/test_ImageItem.py | .py | 5,540 | 148 | import time
import pytest
from pyqtgraph.Qt import QtCore, QtGui, QtTest
import numpy as np
import pyqtgraph as pg
from pyqtgraph.tests import assertImageApproved, TransposedImageItem
app = pg.mkQApp()
def test_ImageItem(transpose=False):
w = pg.GraphicsWindow()
view = pg.ViewBox()
w.setCentralWidget(view)
w.resize(200, 200)
w.show()
img = TransposedImageItem(border=0.5, transpose=transpose)
view.addItem(img)
# test mono float
np.random.seed(0)
data = np.random.normal(size=(20, 20))
dmax = data.max()
data[:10, 1] = dmax + 10
data[1, :10] = dmax + 12
data[3, :10] = dmax + 13
img.setImage(data)
QtTest.QTest.qWaitForWindowShown(w)
time.sleep(0.1)
app.processEvents()
assertImageApproved(w, 'imageitem/init', 'Init image item. View is auto-scaled, image axis 0 marked by 1 line, axis 1 is marked by 2 lines. Origin in bottom-left.')
# ..with colormap
cmap = pg.ColorMap([0, 0.25, 0.75, 1], [[0, 0, 0, 255], [255, 0, 0, 255], [255, 255, 0, 255], [255, 255, 255, 255]])
img.setLookupTable(cmap.getLookupTable())
assertImageApproved(w, 'imageitem/lut', 'Set image LUT.')
# ..and different levels
img.setLevels([dmax+9, dmax+13])
assertImageApproved(w, 'imageitem/levels1', 'Levels show only axis lines.')
img.setLookupTable(None)
# test mono int
data = np.fromfunction(lambda x,y: x+y*10, (129, 128)).astype(np.int16)
img.setImage(data)
assertImageApproved(w, 'imageitem/gradient_mono_int', 'Mono int gradient.')
img.setLevels([640, 641])
assertImageApproved(w, 'imageitem/gradient_mono_int_levels', 'Mono int gradient w/ levels to isolate diagonal.')
# test mono byte
data = np.fromfunction(lambda x,y: x+y, (129, 128)).astype(np.ubyte)
img.setImage(data)
assertImageApproved(w, 'imageitem/gradient_mono_byte', 'Mono byte gradient.')
img.setLevels([127, 128])
assertImageApproved(w, 'imageitem/gradient_mono_byte_levels', 'Mono byte gradient w/ levels to isolate diagonal.')
# test monochrome image
data = np.zeros((10, 10), dtype='uint8')
data[:5,:5] = 1
data[5:,5:] = 1
img.setImage(data)
assertImageApproved(w, 'imageitem/monochrome', 'Ubyte image with only 0,1 values.')
# test bool
data = data.astype(bool)
img.setImage(data)
assertImageApproved(w, 'imageitem/bool', 'Boolean mask.')
# test RGBA byte
data = np.zeros((100, 100, 4), dtype='ubyte')
data[..., 0] = np.linspace(0, 255, 100).reshape(100, 1)
data[..., 1] = np.linspace(0, 255, 100).reshape(1, 100)
data[..., 3] = 255
img.setImage(data)
assertImageApproved(w, 'imageitem/gradient_rgba_byte', 'RGBA byte gradient.')
img.setLevels([[128, 129], [128, 255], [0, 1], [0, 255]])
assertImageApproved(w, 'imageitem/gradient_rgba_byte_levels', 'RGBA byte gradient. Levels set to show x=128 and y>128.')
# test RGBA float
data = data.astype(float)
img.setImage(data / 1e9)
assertImageApproved(w, 'imageitem/gradient_rgba_float', 'RGBA float gradient.')
# checkerboard to test alpha
img2 = TransposedImageItem(transpose=transpose)
img2.setImage(np.fromfunction(lambda x,y: (x+y)%2, (10, 10)), levels=[-1,2])
view.addItem(img2)
img2.scale(10, 10)
img2.setZValue(-10)
data[..., 0] *= 1e-9
data[..., 1] *= 1e9
data[..., 3] = np.fromfunction(lambda x,y: np.sin(0.1 * (x+y)), (100, 100))
img.setImage(data, levels=[[0, 128e-9],[0, 128e9],[0, 1],[-1, 1]])
assertImageApproved(w, 'imageitem/gradient_rgba_float_alpha', 'RGBA float gradient with alpha.')
# test composition mode
img.setCompositionMode(QtGui.QPainter.CompositionMode_Plus)
assertImageApproved(w, 'imageitem/gradient_rgba_float_additive', 'RGBA float gradient with alpha and additive composition mode.')
img2.hide()
img.setCompositionMode(QtGui.QPainter.CompositionMode_SourceOver)
# test downsampling
data = np.fromfunction(lambda x,y: np.cos(0.002 * x**2), (800, 100))
img.setImage(data, levels=[-1, 1])
assertImageApproved(w, 'imageitem/resolution_without_downsampling', 'Resolution test without downsampling.')
img.setAutoDownsample(True)
assertImageApproved(w, 'imageitem/resolution_with_downsampling_x', 'Resolution test with downsampling axross x axis.')
assert img._lastDownsample == (4, 1)
img.setImage(data.T, levels=[-1, 1])
assertImageApproved(w, 'imageitem/resolution_with_downsampling_y', 'Resolution test with downsampling across y axis.')
assert img._lastDownsample == (1, 4)
w.hide()
def test_ImageItem_axisorder():
# All image tests pass again using the opposite axis order
origMode = pg.getConfigOption('imageAxisOrder')
altMode = 'row-major' if origMode == 'col-major' else 'col-major'
pg.setConfigOptions(imageAxisOrder=altMode)
try:
test_ImageItem(transpose=True)
finally:
pg.setConfigOptions(imageAxisOrder=origMode)
@pytest.mark.skipif(pg.Qt.QT_LIB=='PySide', reason="pyside does not have qWait")
def test_dividebyzero():
import pyqtgraph as pg
im = pg.image(pg.np.random.normal(size=(100,100)))
im.imageItem.setAutoDownsample(True)
im.view.setRange(xRange=[-5+25, 5e+25],yRange=[-5e+25, 5e+25])
app.processEvents()
QtTest.QTest.qWait(1000)
# must manually call im.imageItem.render here or the exception
# will only exist on the Qt event loop
im.imageItem.render()
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/tests/test_ErrorBarItem.py | .py | 910 | 40 | import pyqtgraph as pg
import numpy as np
app = pg.mkQApp()
def test_ErrorBarItem_defer_data():
plot = pg.PlotWidget()
plot.show()
# plot some data away from the origin to set the view rect
x = np.arange(5) + 10
curve = pg.PlotCurveItem(x=x, y=x)
plot.addItem(curve)
app.processEvents()
r_no_ebi = plot.viewRect()
# ErrorBarItem with no data shouldn't affect the view rect
err = pg.ErrorBarItem()
plot.addItem(err)
app.processEvents()
r_empty_ebi = plot.viewRect()
assert r_no_ebi == r_empty_ebi
err.setData(x=x, y=x, bottom=x, top=x)
app.processEvents()
r_ebi = plot.viewRect()
assert r_empty_ebi != r_ebi
# unset data, ErrorBarItem disappears and view rect goes back to original
err.setData(x=None, y=None)
app.processEvents()
r_clear_ebi = plot.viewRect()
assert r_clear_ebi == r_no_ebi
plot.close()
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/tests/test_ScatterPlotItem.py | .py | 2,965 | 99 | from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import numpy as np
app = pg.mkQApp()
app.processEvents()
def test_scatterplotitem():
plot = pg.PlotWidget()
# set view range equal to its bounding rect.
# This causes plots to look the same regardless of pxMode.
plot.setRange(rect=plot.boundingRect())
# test SymbolAtlas accepts custom symbol
s = pg.ScatterPlotItem()
symbol = QtGui.QPainterPath()
symbol.addEllipse(QtCore.QRectF(-0.5, -0.5, 1, 1))
s.addPoints([{'pos': [0,0], 'data': 1, 'symbol': symbol}])
for i, pxMode in enumerate([True, False]):
for j, useCache in enumerate([True, False]):
s = pg.ScatterPlotItem()
s.opts['useCache'] = useCache
plot.addItem(s)
s.setData(x=np.array([10,40,20,30])+i*100, y=np.array([40,60,10,30])+j*100, pxMode=pxMode)
s.addPoints(x=np.array([60, 70])+i*100, y=np.array([60, 70])+j*100, size=[20, 30])
# Test uniform spot updates
s.setSize(10)
s.setBrush('r')
s.setPen('g')
s.setSymbol('+')
app.processEvents()
# Test list spot updates
s.setSize([10] * 6)
s.setBrush([pg.mkBrush('r')] * 6)
s.setPen([pg.mkPen('g')] * 6)
s.setSymbol(['+'] * 6)
s.setPointData([s] * 6)
app.processEvents()
# Test array spot updates
s.setSize(np.array([10] * 6))
s.setBrush(np.array([pg.mkBrush('r')] * 6))
s.setPen(np.array([pg.mkPen('g')] * 6))
s.setSymbol(np.array(['+'] * 6))
s.setPointData(np.array([s] * 6))
app.processEvents()
# Test per-spot updates
spot = s.points()[0]
spot.setSize(20)
spot.setBrush('b')
spot.setPen('g')
spot.setSymbol('o')
spot.setData(None)
app.processEvents()
plot.clear()
def test_init_spots():
plot = pg.PlotWidget()
# set view range equal to its bounding rect.
# This causes plots to look the same regardless of pxMode.
plot.setRange(rect=plot.boundingRect())
spots = [
{'x': 0, 'y': 1},
{'pos': (1, 2), 'pen': None, 'brush': None, 'data': 'zzz'},
]
s = pg.ScatterPlotItem(spots=spots)
# Check we can display without errors
plot.addItem(s)
app.processEvents()
plot.clear()
# check data is correct
spots = s.points()
defPen = pg.mkPen(pg.getConfigOption('foreground'))
assert spots[0].pos().x() == 0
assert spots[0].pos().y() == 1
assert spots[0].pen() == defPen
assert spots[0].data() is None
assert spots[1].pos().x() == 1
assert spots[1].pos().y() == 2
assert spots[1].pen() == pg.mkPen(None)
assert spots[1].brush() == pg.mkBrush(None)
assert spots[1].data() == 'zzz'
if __name__ == '__main__':
test_scatterplotitem()
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/tests/test_GraphicsItem.py | .py | 802 | 37 | import gc
import weakref
try:
import faulthandler
faulthandler.enable()
except ImportError:
pass
import pyqtgraph as pg
pg.mkQApp()
def test_getViewWidget():
view = pg.PlotWidget()
vref = weakref.ref(view)
item = pg.InfiniteLine()
view.addItem(item)
assert item.getViewWidget() is view
del view
gc.collect()
assert vref() is None
assert item.getViewWidget() is None
def test_getViewWidget_deleted():
view = pg.PlotWidget()
item = pg.InfiniteLine()
view.addItem(item)
assert item.getViewWidget() is view
# Arrange to have Qt automatically delete the view widget
obj = pg.QtGui.QWidget()
view.setParent(obj)
del obj
gc.collect()
assert not pg.Qt.isQObjectAlive(view)
assert item.getViewWidget() is None
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/tests/test_InfiniteLine.py | .py | 3,452 | 97 | import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore, QtTest
from pyqtgraph.tests import mouseDrag, mouseMove
pg.mkQApp()
def test_InfiniteLine():
# Test basic InfiniteLine API
plt = pg.plot()
plt.setXRange(-10, 10)
plt.setYRange(-10, 10)
plt.resize(600, 600)
# seemingly arbitrary requirements; might need longer wait time for some platforms..
QtTest.QTest.qWaitForWindowShown(plt)
QtTest.QTest.qWait(100)
vline = plt.addLine(x=1)
assert vline.angle == 90
br = vline.mapToView(QtGui.QPolygonF(vline.boundingRect()))
assert br.containsPoint(pg.Point(1, 5), QtCore.Qt.OddEvenFill)
assert not br.containsPoint(pg.Point(5, 0), QtCore.Qt.OddEvenFill)
hline = plt.addLine(y=0)
assert hline.angle == 0
assert hline.boundingRect().contains(pg.Point(5, 0))
assert not hline.boundingRect().contains(pg.Point(0, 5))
vline.setValue(2)
assert vline.value() == 2
vline.setPos(pg.Point(4, -5))
assert vline.value() == 4
oline = pg.InfiniteLine(angle=30)
plt.addItem(oline)
oline.setPos(pg.Point(1, -1))
assert oline.angle == 30
assert oline.pos() == pg.Point(1, -1)
assert oline.value() == [1, -1]
# test bounding rect for oblique line
br = oline.mapToScene(oline.boundingRect())
pos = oline.mapToScene(pg.Point(2, 0))
assert br.containsPoint(pos, QtCore.Qt.OddEvenFill)
px = pg.Point(-0.5, -1.0 / 3**0.5)
assert br.containsPoint(pos + 5 * px, QtCore.Qt.OddEvenFill)
assert not br.containsPoint(pos + 7 * px, QtCore.Qt.OddEvenFill)
def test_mouseInteraction():
plt = pg.plot()
plt.scene().minDragTime = 0 # let us simulate mouse drags very quickly.
vline = plt.addLine(x=0, movable=True)
plt.addItem(vline)
hline = plt.addLine(y=0, movable=True)
hline2 = plt.addLine(y=-1, movable=False)
plt.setXRange(-10, 10)
plt.setYRange(-10, 10)
# test horizontal drag
pos = plt.plotItem.vb.mapViewToScene(pg.Point(0,5)).toPoint()
pos2 = pos - QtCore.QPoint(200, 200)
mouseMove(plt, pos)
assert vline.mouseHovering is True and hline.mouseHovering is False
mouseDrag(plt, pos, pos2, QtCore.Qt.LeftButton)
px = vline.pixelLength(pg.Point(1, 0), ortho=True)
assert abs(vline.value() - plt.plotItem.vb.mapSceneToView(pos2).x()) <= px
# test missed drag
pos = plt.plotItem.vb.mapViewToScene(pg.Point(5,0)).toPoint()
pos = pos + QtCore.QPoint(0, 6)
pos2 = pos + QtCore.QPoint(-20, -20)
mouseMove(plt, pos)
assert vline.mouseHovering is False and hline.mouseHovering is False
mouseDrag(plt, pos, pos2, QtCore.Qt.LeftButton)
assert hline.value() == 0
# test vertical drag
pos = plt.plotItem.vb.mapViewToScene(pg.Point(5,0)).toPoint()
pos2 = pos - QtCore.QPoint(50, 50)
mouseMove(plt, pos)
assert vline.mouseHovering is False and hline.mouseHovering is True
mouseDrag(plt, pos, pos2, QtCore.Qt.LeftButton)
px = hline.pixelLength(pg.Point(1, 0), ortho=True)
assert abs(hline.value() - plt.plotItem.vb.mapSceneToView(pos2).y()) <= px
# test non-interactive line
pos = plt.plotItem.vb.mapViewToScene(pg.Point(5,-1)).toPoint()
pos2 = pos - QtCore.QPoint(50, 50)
mouseMove(plt, pos)
assert hline2.mouseHovering == False
mouseDrag(plt, pos, pos2, QtCore.Qt.LeftButton)
assert hline2.value() == -1
if __name__ == '__main__':
test_mouseInteraction()
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsItems/tests/test_TextItem.py | .py | 400 | 24 | import pytest
import pyqtgraph as pg
app = pg.mkQApp()
def test_TextItem_setAngle():
plt = pg.plot()
plt.setXRange(-10, 10)
plt.setYRange(-20, 20)
item = pg.TextItem(text="test")
plt.addItem(item)
t1 = item.transform()
item.setAngle(30)
app.processEvents()
t2 = item.transform()
assert t1 != t2
assert not t1.isRotating()
assert t2.isRotating()
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/flowchart/FlowchartTemplate_pyside.py | .py | 2,387 | 55 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './pyqtgraph/flowchart/FlowchartTemplate.ui'
#
# Created: Mon Dec 23 10:10:51 2013
# by: pyside-uic 0.2.14 running on PySide 1.1.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(529, 329)
self.selInfoWidget = QtGui.QWidget(Form)
self.selInfoWidget.setGeometry(QtCore.QRect(260, 10, 264, 222))
self.selInfoWidget.setObjectName("selInfoWidget")
self.gridLayout = QtGui.QGridLayout(self.selInfoWidget)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setObjectName("gridLayout")
self.selDescLabel = QtGui.QLabel(self.selInfoWidget)
self.selDescLabel.setText("")
self.selDescLabel.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.selDescLabel.setWordWrap(True)
self.selDescLabel.setObjectName("selDescLabel")
self.gridLayout.addWidget(self.selDescLabel, 0, 0, 1, 1)
self.selNameLabel = QtGui.QLabel(self.selInfoWidget)
font = QtGui.QFont()
font.setWeight(75)
font.setBold(True)
self.selNameLabel.setFont(font)
self.selNameLabel.setText("")
self.selNameLabel.setObjectName("selNameLabel")
self.gridLayout.addWidget(self.selNameLabel, 0, 1, 1, 1)
self.selectedTree = DataTreeWidget(self.selInfoWidget)
self.selectedTree.setObjectName("selectedTree")
self.selectedTree.headerItem().setText(0, "1")
self.gridLayout.addWidget(self.selectedTree, 1, 0, 1, 2)
self.hoverText = QtGui.QTextEdit(Form)
self.hoverText.setGeometry(QtCore.QRect(0, 240, 521, 81))
self.hoverText.setObjectName("hoverText")
self.view = FlowchartGraphicsView(Form)
self.view.setGeometry(QtCore.QRect(0, 0, 256, 192))
self.view.setObjectName("view")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8))
from ..flowchart.FlowchartGraphicsView import FlowchartGraphicsView
from ..widgets.DataTreeWidget import DataTreeWidget
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/flowchart/FlowchartTemplate_pyqt5.py | .py | 2,404 | 56 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './pyqtgraph/flowchart/FlowchartTemplate.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(529, 329)
self.selInfoWidget = QtWidgets.QWidget(Form)
self.selInfoWidget.setGeometry(QtCore.QRect(260, 10, 264, 222))
self.selInfoWidget.setObjectName("selInfoWidget")
self.gridLayout = QtWidgets.QGridLayout(self.selInfoWidget)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setObjectName("gridLayout")
self.selDescLabel = QtWidgets.QLabel(self.selInfoWidget)
self.selDescLabel.setText("")
self.selDescLabel.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.selDescLabel.setWordWrap(True)
self.selDescLabel.setObjectName("selDescLabel")
self.gridLayout.addWidget(self.selDescLabel, 0, 0, 1, 1)
self.selNameLabel = QtWidgets.QLabel(self.selInfoWidget)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.selNameLabel.setFont(font)
self.selNameLabel.setText("")
self.selNameLabel.setObjectName("selNameLabel")
self.gridLayout.addWidget(self.selNameLabel, 0, 1, 1, 1)
self.selectedTree = DataTreeWidget(self.selInfoWidget)
self.selectedTree.setObjectName("selectedTree")
self.selectedTree.headerItem().setText(0, "1")
self.gridLayout.addWidget(self.selectedTree, 1, 0, 1, 2)
self.hoverText = QtWidgets.QTextEdit(Form)
self.hoverText.setGeometry(QtCore.QRect(0, 240, 521, 81))
self.hoverText.setObjectName("hoverText")
self.view = FlowchartGraphicsView(Form)
self.view.setGeometry(QtCore.QRect(0, 0, 256, 192))
self.view.setObjectName("view")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
from ..widgets.DataTreeWidget import DataTreeWidget
from ..flowchart.FlowchartGraphicsView import FlowchartGraphicsView
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/flowchart/FlowchartGraphicsView.py | .py | 1,364 | 42 | # -*- coding: utf-8 -*-
from ..Qt import QtGui, QtCore
from ..widgets.GraphicsView import GraphicsView
from ..GraphicsScene import GraphicsScene
from ..graphicsItems.ViewBox import ViewBox
class FlowchartGraphicsView(GraphicsView):
sigHoverOver = QtCore.Signal(object)
sigClicked = QtCore.Signal(object)
def __init__(self, widget, *args):
GraphicsView.__init__(self, *args, useOpenGL=False)
self._vb = FlowchartViewBox(widget, lockAspect=True, invertY=True)
self.setCentralItem(self._vb)
self.setRenderHint(QtGui.QPainter.Antialiasing, True)
def viewBox(self):
return self._vb
class FlowchartViewBox(ViewBox):
def __init__(self, widget, *args, **kwargs):
ViewBox.__init__(self, *args, **kwargs)
self.widget = widget
def getMenu(self, ev):
## called by ViewBox to create a new context menu
self._fc_menu = QtGui.QMenu()
self._subMenus = self.getContextMenus(ev)
for menu in self._subMenus:
self._fc_menu.addMenu(menu)
return self._fc_menu
def getContextMenus(self, ev):
## called by scene to add menus on to someone else's context menu
menu = self.widget.buildMenu(ev.scenePos())
menu.setTitle("Add node")
return [menu, ViewBox.getMenu(self, ev)]
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/flowchart/FlowchartTemplate_pyqt.py | .py | 2,849 | 69 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './pyqtgraph/flowchart/FlowchartTemplate.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(529, 329)
self.selInfoWidget = QtGui.QWidget(Form)
self.selInfoWidget.setGeometry(QtCore.QRect(260, 10, 264, 222))
self.selInfoWidget.setObjectName(_fromUtf8("selInfoWidget"))
self.gridLayout = QtGui.QGridLayout(self.selInfoWidget)
self.gridLayout.setMargin(0)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.selDescLabel = QtGui.QLabel(self.selInfoWidget)
self.selDescLabel.setText(_fromUtf8(""))
self.selDescLabel.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.selDescLabel.setWordWrap(True)
self.selDescLabel.setObjectName(_fromUtf8("selDescLabel"))
self.gridLayout.addWidget(self.selDescLabel, 0, 0, 1, 1)
self.selNameLabel = QtGui.QLabel(self.selInfoWidget)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.selNameLabel.setFont(font)
self.selNameLabel.setText(_fromUtf8(""))
self.selNameLabel.setObjectName(_fromUtf8("selNameLabel"))
self.gridLayout.addWidget(self.selNameLabel, 0, 1, 1, 1)
self.selectedTree = DataTreeWidget(self.selInfoWidget)
self.selectedTree.setObjectName(_fromUtf8("selectedTree"))
self.selectedTree.headerItem().setText(0, _fromUtf8("1"))
self.gridLayout.addWidget(self.selectedTree, 1, 0, 1, 2)
self.hoverText = QtGui.QTextEdit(Form)
self.hoverText.setGeometry(QtCore.QRect(0, 240, 521, 81))
self.hoverText.setObjectName(_fromUtf8("hoverText"))
self.view = FlowchartGraphicsView(Form)
self.view.setGeometry(QtCore.QRect(0, 0, 256, 192))
self.view.setObjectName(_fromUtf8("view"))
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Form", None))
from ..flowchart.FlowchartGraphicsView import FlowchartGraphicsView
from ..widgets.DataTreeWidget import DataTreeWidget
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/flowchart/__init__.py | .py | 113 | 4 | # -*- coding: utf-8 -*-
from .Flowchart import *
from .library import getNodeType, registerNodeType, getNodeTree | Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/flowchart/Node.py | .py | 25,297 | 644 | # -*- coding: utf-8 -*-
from ..Qt import QtCore, QtGui
from ..graphicsItems.GraphicsObject import GraphicsObject
from .. import functions as fn
from .Terminal import *
from ..pgcollections import OrderedDict
from ..debug import *
import numpy as np
def strDict(d):
return dict([(str(k), v) for k, v in d.items()])
class Node(QtCore.QObject):
"""
Node represents the basic processing unit of a flowchart.
A Node subclass implements at least:
1) A list of input / ouptut terminals and their properties
2) a process() function which takes the names of input terminals as keyword arguments and returns a dict with the names of output terminals as keys.
A flowchart thus consists of multiple instances of Node subclasses, each of which is connected
to other by wires between their terminals. A flowchart is, itself, also a special subclass of Node.
This allows Nodes within the flowchart to connect to the input/output nodes of the flowchart itself.
Optionally, a node class can implement the ctrlWidget() method, which must return a QWidget (usually containing other widgets) that will be displayed in the flowchart control panel. Some nodes implement fairly complex control widgets, but most nodes follow a simple form-like pattern: a list of parameter names and a single value (represented as spin box, check box, etc..) for each parameter. To make this easier, the CtrlNode subclass allows you to instead define a simple data structure that CtrlNode will use to automatically generate the control widget. """
sigOutputChanged = QtCore.Signal(object) # self
sigClosed = QtCore.Signal(object)
sigRenamed = QtCore.Signal(object, object)
sigTerminalRenamed = QtCore.Signal(object, object) # term, oldName
sigTerminalAdded = QtCore.Signal(object, object) # self, term
sigTerminalRemoved = QtCore.Signal(object, object) # self, term
def __init__(self, name, terminals=None, allowAddInput=False, allowAddOutput=False, allowRemove=True):
"""
============== ============================================================
**Arguments:**
name The name of this specific node instance. It can be any
string, but must be unique within a flowchart. Usually,
we simply let the flowchart decide on a name when calling
Flowchart.addNode(...)
terminals Dict-of-dicts specifying the terminals present on this Node.
Terminal specifications look like::
'inputTerminalName': {'io': 'in'}
'outputTerminalName': {'io': 'out'}
There are a number of optional parameters for terminals:
multi, pos, renamable, removable, multiable, bypass. See
the Terminal class for more information.
allowAddInput bool; whether the user is allowed to add inputs by the
context menu.
allowAddOutput bool; whether the user is allowed to add outputs by the
context menu.
allowRemove bool; whether the user is allowed to remove this node by the
context menu.
============== ============================================================
"""
QtCore.QObject.__init__(self)
self._name = name
self._bypass = False
self.bypassButton = None ## this will be set by the flowchart ctrl widget..
self._graphicsItem = None
self.terminals = OrderedDict()
self._inputs = OrderedDict()
self._outputs = OrderedDict()
self._allowAddInput = allowAddInput ## flags to allow the user to add/remove terminals
self._allowAddOutput = allowAddOutput
self._allowRemove = allowRemove
self.exception = None
if terminals is None:
return
for name, opts in terminals.items():
self.addTerminal(name, **opts)
def nextTerminalName(self, name):
"""Return an unused terminal name"""
name2 = name
i = 1
while name2 in self.terminals:
name2 = "%s.%d" % (name, i)
i += 1
return name2
def addInput(self, name="Input", **args):
"""Add a new input terminal to this Node with the given name. Extra
keyword arguments are passed to Terminal.__init__.
This is a convenience function that just calls addTerminal(io='in', ...)"""
#print "Node.addInput called."
return self.addTerminal(name, io='in', **args)
def addOutput(self, name="Output", **args):
"""Add a new output terminal to this Node with the given name. Extra
keyword arguments are passed to Terminal.__init__.
This is a convenience function that just calls addTerminal(io='out', ...)"""
return self.addTerminal(name, io='out', **args)
def removeTerminal(self, term):
"""Remove the specified terminal from this Node. May specify either the
terminal's name or the terminal itself.
Causes sigTerminalRemoved to be emitted."""
if isinstance(term, Terminal):
name = term.name()
else:
name = term
term = self.terminals[name]
#print "remove", name
#term.disconnectAll()
term.close()
del self.terminals[name]
if name in self._inputs:
del self._inputs[name]
if name in self._outputs:
del self._outputs[name]
self.graphicsItem().updateTerminals()
self.sigTerminalRemoved.emit(self, term)
def terminalRenamed(self, term, oldName):
"""Called after a terminal has been renamed
Causes sigTerminalRenamed to be emitted."""
newName = term.name()
for d in [self.terminals, self._inputs, self._outputs]:
if oldName not in d:
continue
d[newName] = d[oldName]
del d[oldName]
self.graphicsItem().updateTerminals()
self.sigTerminalRenamed.emit(term, oldName)
def addTerminal(self, name, **opts):
"""Add a new terminal to this Node with the given name. Extra
keyword arguments are passed to Terminal.__init__.
Causes sigTerminalAdded to be emitted."""
name = self.nextTerminalName(name)
term = Terminal(self, name, **opts)
self.terminals[name] = term
if term.isInput():
self._inputs[name] = term
elif term.isOutput():
self._outputs[name] = term
self.graphicsItem().updateTerminals()
self.sigTerminalAdded.emit(self, term)
return term
def inputs(self):
"""Return dict of all input terminals.
Warning: do not modify."""
return self._inputs
def outputs(self):
"""Return dict of all output terminals.
Warning: do not modify."""
return self._outputs
def process(self, **kargs):
"""Process data through this node. This method is called any time the flowchart
wants the node to process data. It will be called with one keyword argument
corresponding to each input terminal, and must return a dict mapping the name
of each output terminal to its new value.
This method is also called with a 'display' keyword argument, which indicates
whether the node should update its display (if it implements any) while processing
this data. This is primarily used to disable expensive display operations
during batch processing.
"""
return {}
def graphicsItem(self):
"""Return the GraphicsItem for this node. Subclasses may re-implement
this method to customize their appearance in the flowchart."""
if self._graphicsItem is None:
self._graphicsItem = NodeGraphicsItem(self)
return self._graphicsItem
## this is just bad planning. Causes too many bugs.
def __getattr__(self, attr):
"""Return the terminal with the given name"""
if attr not in self.terminals:
raise AttributeError(attr)
else:
import traceback
traceback.print_stack()
print("Warning: use of node.terminalName is deprecated; use node['terminalName'] instead.")
return self.terminals[attr]
def __getitem__(self, item):
#return getattr(self, item)
"""Return the terminal with the given name"""
if item not in self.terminals:
raise KeyError(item)
else:
return self.terminals[item]
def name(self):
"""Return the name of this node."""
return self._name
def rename(self, name):
"""Rename this node. This will cause sigRenamed to be emitted."""
oldName = self._name
self._name = name
#self.emit(QtCore.SIGNAL('renamed'), self, oldName)
self.sigRenamed.emit(self, oldName)
def dependentNodes(self):
"""Return the list of nodes which provide direct input to this node"""
nodes = set()
for t in self.inputs().values():
nodes |= set([i.node() for i in t.inputTerminals()])
return nodes
#return set([t.inputTerminals().node() for t in self.listInputs().values()])
def __repr__(self):
return "<Node %s @%x>" % (self.name(), id(self))
def ctrlWidget(self):
"""Return this Node's control widget.
By default, Nodes have no control widget. Subclasses may reimplement this
method to provide a custom widget. This method is called by Flowcharts
when they are constructing their Node list."""
return None
def bypass(self, byp):
"""Set whether this node should be bypassed.
When bypassed, a Node's process() method is never called. In some cases,
data is automatically copied directly from specific input nodes to
output nodes instead (see the bypass argument to Terminal.__init__).
This is usually called when the user disables a node from the flowchart
control panel.
"""
self._bypass = byp
if self.bypassButton is not None:
self.bypassButton.setChecked(byp)
self.update()
def isBypassed(self):
"""Return True if this Node is currently bypassed."""
return self._bypass
def setInput(self, **args):
"""Set the values on input terminals. For most nodes, this will happen automatically through Terminal.inputChanged.
This is normally only used for nodes with no connected inputs."""
changed = False
for k, v in args.items():
term = self._inputs[k]
oldVal = term.value()
if not fn.eq(oldVal, v):
changed = True
term.setValue(v, process=False)
if changed and '_updatesHandled_' not in args:
self.update()
def inputValues(self):
"""Return a dict of all input values currently assigned to this node."""
vals = {}
for n, t in self.inputs().items():
vals[n] = t.value()
return vals
def outputValues(self):
"""Return a dict of all output values currently generated by this node."""
vals = {}
for n, t in self.outputs().items():
vals[n] = t.value()
return vals
def connected(self, localTerm, remoteTerm):
"""Called whenever one of this node's terminals is connected elsewhere."""
pass
def disconnected(self, localTerm, remoteTerm):
"""Called whenever one of this node's terminals is disconnected from another."""
pass
def update(self, signal=True):
"""Collect all input values, attempt to process new output values, and propagate downstream.
Subclasses should call update() whenever thir internal state has changed
(such as when the user interacts with the Node's control widget). Update
is automatically called when the inputs to the node are changed.
"""
vals = self.inputValues()
#print " inputs:", vals
try:
if self.isBypassed():
out = self.processBypassed(vals)
else:
out = self.process(**strDict(vals))
#print " output:", out
if out is not None:
if signal:
self.setOutput(**out)
else:
self.setOutputNoSignal(**out)
for n,t in self.inputs().items():
t.setValueAcceptable(True)
self.clearException()
except:
#printExc( "Exception while processing %s:" % self.name())
for n,t in self.outputs().items():
t.setValue(None)
self.setException(sys.exc_info())
if signal:
#self.emit(QtCore.SIGNAL('outputChanged'), self) ## triggers flowchart to propagate new data
self.sigOutputChanged.emit(self) ## triggers flowchart to propagate new data
def processBypassed(self, args):
"""Called when the flowchart would normally call Node.process, but this node is currently bypassed.
The default implementation looks for output terminals with a bypass connection and returns the
corresponding values. Most Node subclasses will _not_ need to reimplement this method."""
result = {}
for term in list(self.outputs().values()):
byp = term.bypassValue()
if byp is None:
result[term.name()] = None
else:
result[term.name()] = args.get(byp, None)
return result
def setOutput(self, **vals):
self.setOutputNoSignal(**vals)
#self.emit(QtCore.SIGNAL('outputChanged'), self) ## triggers flowchart to propagate new data
self.sigOutputChanged.emit(self) ## triggers flowchart to propagate new data
def setOutputNoSignal(self, **vals):
for k, v in vals.items():
term = self.outputs()[k]
term.setValue(v)
#targets = term.connections()
#for t in targets: ## propagate downstream
#if t is term:
#continue
#t.inputChanged(term)
term.setValueAcceptable(True)
def setException(self, exc):
self.exception = exc
self.recolor()
def clearException(self):
self.setException(None)
def recolor(self):
if self.exception is None:
self.graphicsItem().setPen(QtGui.QPen(QtGui.QColor(0, 0, 0)))
else:
self.graphicsItem().setPen(QtGui.QPen(QtGui.QColor(150, 0, 0), 3))
def saveState(self):
"""Return a dictionary representing the current state of this node
(excluding input / output values). This is used for saving/reloading
flowcharts. The default implementation returns this Node's position,
bypass state, and information about each of its terminals.
Subclasses may want to extend this method, adding extra keys to the returned
dict."""
pos = self.graphicsItem().pos()
state = {'pos': (pos.x(), pos.y()), 'bypass': self.isBypassed()}
termsEditable = self._allowAddInput | self._allowAddOutput
for term in list(self._inputs.values()) + list(self._outputs.values()):
termsEditable |= term._renamable | term._removable | term._multiable
if termsEditable:
state['terminals'] = self.saveTerminals()
return state
def restoreState(self, state):
"""Restore the state of this node from a structure previously generated
by saveState(). """
pos = state.get('pos', (0,0))
self.graphicsItem().setPos(*pos)
self.bypass(state.get('bypass', False))
if 'terminals' in state:
self.restoreTerminals(state['terminals'])
def saveTerminals(self):
terms = OrderedDict()
for n, t in self.terminals.items():
terms[n] = (t.saveState())
return terms
def restoreTerminals(self, state):
for name in list(self.terminals.keys()):
if name not in state:
self.removeTerminal(name)
for name, opts in state.items():
if name in self.terminals:
term = self[name]
term.setOpts(**opts)
continue
try:
opts = strDict(opts)
self.addTerminal(name, **opts)
except:
printExc("Error restoring terminal %s (%s):" % (str(name), str(opts)))
def clearTerminals(self):
for t in self.terminals.values():
t.close()
self.terminals = OrderedDict()
self._inputs = OrderedDict()
self._outputs = OrderedDict()
def close(self):
"""Cleans up after the node--removes terminals, graphicsItem, widget"""
self.disconnectAll()
self.clearTerminals()
item = self.graphicsItem()
if item.scene() is not None:
item.scene().removeItem(item)
self._graphicsItem = None
w = self.ctrlWidget()
if w is not None:
w.setParent(None)
#self.emit(QtCore.SIGNAL('closed'), self)
self.sigClosed.emit(self)
def disconnectAll(self):
for t in self.terminals.values():
t.disconnectAll()
#class NodeGraphicsItem(QtGui.QGraphicsItem):
class NodeGraphicsItem(GraphicsObject):
def __init__(self, node):
#QtGui.QGraphicsItem.__init__(self)
GraphicsObject.__init__(self)
#QObjectWorkaround.__init__(self)
#self.shadow = QtGui.QGraphicsDropShadowEffect()
#self.shadow.setOffset(5,5)
#self.shadow.setBlurRadius(10)
#self.setGraphicsEffect(self.shadow)
self.pen = fn.mkPen(0,0,0)
self.selectPen = fn.mkPen(200,200,200,width=2)
self.brush = fn.mkBrush(200, 200, 200, 150)
self.hoverBrush = fn.mkBrush(200, 200, 200, 200)
self.selectBrush = fn.mkBrush(200, 200, 255, 200)
self.hovered = False
self.node = node
flags = self.ItemIsMovable | self.ItemIsSelectable | self.ItemIsFocusable |self.ItemSendsGeometryChanges
#flags = self.ItemIsFocusable |self.ItemSendsGeometryChanges
self.setFlags(flags)
self.bounds = QtCore.QRectF(0, 0, 100, 100)
self.nameItem = QtGui.QGraphicsTextItem(self.node.name(), self)
self.nameItem.setDefaultTextColor(QtGui.QColor(50, 50, 50))
self.nameItem.moveBy(self.bounds.width()/2. - self.nameItem.boundingRect().width()/2., 0)
self.nameItem.setTextInteractionFlags(QtCore.Qt.TextEditorInteraction)
self.updateTerminals()
#self.setZValue(10)
self.nameItem.focusOutEvent = self.labelFocusOut
self.nameItem.keyPressEvent = self.labelKeyPress
self.menu = None
self.buildMenu()
#self.node.sigTerminalRenamed.connect(self.updateActionMenu)
#def setZValue(self, z):
#for t, item in self.terminals.values():
#item.setZValue(z+1)
#GraphicsObject.setZValue(self, z)
def labelFocusOut(self, ev):
QtGui.QGraphicsTextItem.focusOutEvent(self.nameItem, ev)
self.labelChanged()
def labelKeyPress(self, ev):
if ev.key() == QtCore.Qt.Key_Enter or ev.key() == QtCore.Qt.Key_Return:
self.labelChanged()
else:
QtGui.QGraphicsTextItem.keyPressEvent(self.nameItem, ev)
def labelChanged(self):
newName = str(self.nameItem.toPlainText())
if newName != self.node.name():
self.node.rename(newName)
### re-center the label
bounds = self.boundingRect()
self.nameItem.setPos(bounds.width()/2. - self.nameItem.boundingRect().width()/2., 0)
def setPen(self, *args, **kwargs):
self.pen = fn.mkPen(*args, **kwargs)
self.update()
def setBrush(self, brush):
self.brush = brush
self.update()
def updateTerminals(self):
bounds = self.bounds
self.terminals = {}
inp = self.node.inputs()
dy = bounds.height() / (len(inp)+1)
y = dy
for i, t in inp.items():
item = t.graphicsItem()
item.setParentItem(self)
#item.setZValue(self.zValue()+1)
br = self.bounds
item.setAnchor(0, y)
self.terminals[i] = (t, item)
y += dy
out = self.node.outputs()
dy = bounds.height() / (len(out)+1)
y = dy
for i, t in out.items():
item = t.graphicsItem()
item.setParentItem(self)
item.setZValue(self.zValue())
br = self.bounds
item.setAnchor(bounds.width(), y)
self.terminals[i] = (t, item)
y += dy
#self.buildMenu()
def boundingRect(self):
return self.bounds.adjusted(-5, -5, 5, 5)
def paint(self, p, *args):
p.setPen(self.pen)
if self.isSelected():
p.setPen(self.selectPen)
p.setBrush(self.selectBrush)
else:
p.setPen(self.pen)
if self.hovered:
p.setBrush(self.hoverBrush)
else:
p.setBrush(self.brush)
p.drawRect(self.bounds)
def mousePressEvent(self, ev):
ev.ignore()
def mouseClickEvent(self, ev):
#print "Node.mouseClickEvent called."
if int(ev.button()) == int(QtCore.Qt.LeftButton):
ev.accept()
#print " ev.button: left"
sel = self.isSelected()
#ret = QtGui.QGraphicsItem.mousePressEvent(self, ev)
self.setSelected(True)
if not sel and self.isSelected():
#self.setBrush(QtGui.QBrush(QtGui.QColor(200, 200, 255)))
#self.emit(QtCore.SIGNAL('selected'))
#self.scene().selectionChanged.emit() ## for some reason this doesn't seem to be happening automatically
self.update()
#return ret
elif int(ev.button()) == int(QtCore.Qt.RightButton):
#print " ev.button: right"
ev.accept()
#pos = ev.screenPos()
self.raiseContextMenu(ev)
#self.menu.popup(QtCore.QPoint(pos.x(), pos.y()))
def mouseDragEvent(self, ev):
#print "Node.mouseDrag"
if ev.button() == QtCore.Qt.LeftButton:
ev.accept()
self.setPos(self.pos()+self.mapToParent(ev.pos())-self.mapToParent(ev.lastPos()))
def hoverEvent(self, ev):
if not ev.isExit() and ev.acceptClicks(QtCore.Qt.LeftButton):
ev.acceptDrags(QtCore.Qt.LeftButton)
self.hovered = True
else:
self.hovered = False
self.update()
def keyPressEvent(self, ev):
if ev.key() == QtCore.Qt.Key_Delete or ev.key() == QtCore.Qt.Key_Backspace:
ev.accept()
if not self.node._allowRemove:
return
self.node.close()
else:
ev.ignore()
def itemChange(self, change, val):
if change == self.ItemPositionHasChanged:
for k, t in self.terminals.items():
t[1].nodeMoved()
return GraphicsObject.itemChange(self, change, val)
def getMenu(self):
return self.menu
def raiseContextMenu(self, ev):
menu = self.scene().addParentContextMenus(self, self.getMenu(), ev)
pos = ev.screenPos()
menu.popup(QtCore.QPoint(pos.x(), pos.y()))
def buildMenu(self):
self.menu = QtGui.QMenu()
self.menu.setTitle("Node")
a = self.menu.addAction("Add input", self.addInputFromMenu)
if not self.node._allowAddInput:
a.setEnabled(False)
a = self.menu.addAction("Add output", self.addOutputFromMenu)
if not self.node._allowAddOutput:
a.setEnabled(False)
a = self.menu.addAction("Remove node", self.node.close)
if not self.node._allowRemove:
a.setEnabled(False)
def addInputFromMenu(self): ## called when add input is clicked in context menu
self.node.addInput(renamable=True, removable=True, multiable=True)
def addOutputFromMenu(self): ## called when add output is clicked in context menu
self.node.addOutput(renamable=True, removable=True, multiable=False)
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/flowchart/FlowchartCtrlTemplate_pyqt.py | .py | 3,387 | 81 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './pyqtgraph/flowchart/FlowchartCtrlTemplate.ui'
#
# Created: Mon Dec 23 10:10:50 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(217, 499)
self.gridLayout = QtGui.QGridLayout(Form)
self.gridLayout.setMargin(0)
self.gridLayout.setVerticalSpacing(0)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.loadBtn = QtGui.QPushButton(Form)
self.loadBtn.setObjectName(_fromUtf8("loadBtn"))
self.gridLayout.addWidget(self.loadBtn, 1, 0, 1, 1)
self.saveBtn = FeedbackButton(Form)
self.saveBtn.setObjectName(_fromUtf8("saveBtn"))
self.gridLayout.addWidget(self.saveBtn, 1, 1, 1, 2)
self.saveAsBtn = FeedbackButton(Form)
self.saveAsBtn.setObjectName(_fromUtf8("saveAsBtn"))
self.gridLayout.addWidget(self.saveAsBtn, 1, 3, 1, 1)
self.reloadBtn = FeedbackButton(Form)
self.reloadBtn.setCheckable(False)
self.reloadBtn.setFlat(False)
self.reloadBtn.setObjectName(_fromUtf8("reloadBtn"))
self.gridLayout.addWidget(self.reloadBtn, 4, 0, 1, 2)
self.showChartBtn = QtGui.QPushButton(Form)
self.showChartBtn.setCheckable(True)
self.showChartBtn.setObjectName(_fromUtf8("showChartBtn"))
self.gridLayout.addWidget(self.showChartBtn, 4, 2, 1, 2)
self.ctrlList = TreeWidget(Form)
self.ctrlList.setObjectName(_fromUtf8("ctrlList"))
self.ctrlList.headerItem().setText(0, _fromUtf8("1"))
self.ctrlList.header().setVisible(False)
self.ctrlList.header().setStretchLastSection(False)
self.gridLayout.addWidget(self.ctrlList, 3, 0, 1, 4)
self.fileNameLabel = QtGui.QLabel(Form)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.fileNameLabel.setFont(font)
self.fileNameLabel.setText(_fromUtf8(""))
self.fileNameLabel.setAlignment(QtCore.Qt.AlignCenter)
self.fileNameLabel.setObjectName(_fromUtf8("fileNameLabel"))
self.gridLayout.addWidget(self.fileNameLabel, 0, 1, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Form", None))
self.loadBtn.setText(_translate("Form", "Load..", None))
self.saveBtn.setText(_translate("Form", "Save", None))
self.saveAsBtn.setText(_translate("Form", "As..", None))
self.reloadBtn.setText(_translate("Form", "Reload Libs", None))
self.showChartBtn.setText(_translate("Form", "Flowchart", None))
from ..widgets.TreeWidget import TreeWidget
from ..widgets.FeedbackButton import FeedbackButton
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/flowchart/FlowchartTemplate_pyside2.py | .py | 2,376 | 55 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'FlowchartTemplate.ui'
#
# Created: Sun Sep 18 19:16:03 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(529, 329)
self.selInfoWidget = QtWidgets.QWidget(Form)
self.selInfoWidget.setGeometry(QtCore.QRect(260, 10, 264, 222))
self.selInfoWidget.setObjectName("selInfoWidget")
self.gridLayout = QtWidgets.QGridLayout(self.selInfoWidget)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setObjectName("gridLayout")
self.selDescLabel = QtWidgets.QLabel(self.selInfoWidget)
self.selDescLabel.setText("")
self.selDescLabel.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.selDescLabel.setWordWrap(True)
self.selDescLabel.setObjectName("selDescLabel")
self.gridLayout.addWidget(self.selDescLabel, 0, 0, 1, 1)
self.selNameLabel = QtWidgets.QLabel(self.selInfoWidget)
font = QtGui.QFont()
font.setWeight(75)
font.setBold(True)
self.selNameLabel.setFont(font)
self.selNameLabel.setText("")
self.selNameLabel.setObjectName("selNameLabel")
self.gridLayout.addWidget(self.selNameLabel, 0, 1, 1, 1)
self.selectedTree = DataTreeWidget(self.selInfoWidget)
self.selectedTree.setObjectName("selectedTree")
self.selectedTree.headerItem().setText(0, "1")
self.gridLayout.addWidget(self.selectedTree, 1, 0, 1, 2)
self.hoverText = QtWidgets.QTextEdit(Form)
self.hoverText.setGeometry(QtCore.QRect(0, 240, 521, 81))
self.hoverText.setObjectName("hoverText")
self.view = FlowchartGraphicsView(Form)
self.view.setGeometry(QtCore.QRect(0, 0, 256, 192))
self.view.setObjectName("view")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(QtWidgets.QApplication.translate("Form", "Form", None, -1))
from ..flowchart.FlowchartGraphicsView import FlowchartGraphicsView
from ..widgets.DataTreeWidget import DataTreeWidget
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/flowchart/NodeLibrary.py | .py | 2,623 | 87 | from ..pgcollections import OrderedDict
from .Node import Node
def isNodeClass(cls):
try:
if not issubclass(cls, Node):
return False
except:
return False
return hasattr(cls, 'nodeName')
class NodeLibrary:
"""
A library of flowchart Node types. Custom libraries may be built to provide
each flowchart with a specific set of allowed Node types.
"""
def __init__(self):
self.nodeList = OrderedDict()
self.nodeTree = OrderedDict()
def addNodeType(self, nodeClass, paths, override=False):
"""
Register a new node type. If the type's name is already in use,
an exception will be raised (unless override=True).
============== =========================================================
**Arguments:**
nodeClass a subclass of Node (must have typ.nodeName)
paths list of tuples specifying the location(s) this
type will appear in the library tree.
override if True, overwrite any class having the same name
============== =========================================================
"""
if not isNodeClass(nodeClass):
raise Exception("Object %s is not a Node subclass" % str(nodeClass))
name = nodeClass.nodeName
if not override and name in self.nodeList:
raise Exception("Node type name '%s' is already registered." % name)
self.nodeList[name] = nodeClass
for path in paths:
root = self.nodeTree
for n in path:
if n not in root:
root[n] = OrderedDict()
root = root[n]
root[name] = nodeClass
def getNodeType(self, name):
try:
return self.nodeList[name]
except KeyError:
raise Exception("No node type called '%s'" % name)
def getNodeTree(self):
return self.nodeTree
def copy(self):
"""
Return a copy of this library.
"""
lib = NodeLibrary()
lib.nodeList = self.nodeList.copy()
lib.nodeTree = self.treeCopy(self.nodeTree)
return lib
@staticmethod
def treeCopy(tree):
copy = OrderedDict()
for k,v in tree.items():
if isNodeClass(v):
copy[k] = v
else:
copy[k] = NodeLibrary.treeCopy(v)
return copy
def reload(self):
"""
Reload Node classes in this library.
"""
raise NotImplementedError()
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/flowchart/FlowchartCtrlTemplate_pyside2.py | .py | 3,040 | 67 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'FlowchartCtrlTemplate.ui'
#
# Created: Sun Sep 18 19:16:46 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(217, 499)
self.gridLayout = QtWidgets.QGridLayout(Form)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setVerticalSpacing(0)
self.gridLayout.setObjectName("gridLayout")
self.loadBtn = QtWidgets.QPushButton(Form)
self.loadBtn.setObjectName("loadBtn")
self.gridLayout.addWidget(self.loadBtn, 1, 0, 1, 1)
self.saveBtn = FeedbackButton(Form)
self.saveBtn.setObjectName("saveBtn")
self.gridLayout.addWidget(self.saveBtn, 1, 1, 1, 2)
self.saveAsBtn = FeedbackButton(Form)
self.saveAsBtn.setObjectName("saveAsBtn")
self.gridLayout.addWidget(self.saveAsBtn, 1, 3, 1, 1)
self.reloadBtn = FeedbackButton(Form)
self.reloadBtn.setCheckable(False)
self.reloadBtn.setFlat(False)
self.reloadBtn.setObjectName("reloadBtn")
self.gridLayout.addWidget(self.reloadBtn, 4, 0, 1, 2)
self.showChartBtn = QtWidgets.QPushButton(Form)
self.showChartBtn.setCheckable(True)
self.showChartBtn.setObjectName("showChartBtn")
self.gridLayout.addWidget(self.showChartBtn, 4, 2, 1, 2)
self.ctrlList = TreeWidget(Form)
self.ctrlList.setObjectName("ctrlList")
self.ctrlList.headerItem().setText(0, "1")
self.ctrlList.header().setVisible(False)
self.ctrlList.header().setStretchLastSection(False)
self.gridLayout.addWidget(self.ctrlList, 3, 0, 1, 4)
self.fileNameLabel = QtWidgets.QLabel(Form)
font = QtGui.QFont()
font.setWeight(75)
font.setBold(True)
self.fileNameLabel.setFont(font)
self.fileNameLabel.setText("")
self.fileNameLabel.setAlignment(QtCore.Qt.AlignCenter)
self.fileNameLabel.setObjectName("fileNameLabel")
self.gridLayout.addWidget(self.fileNameLabel, 0, 1, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(QtWidgets.QApplication.translate("Form", "Form", None, -1))
self.loadBtn.setText(QtWidgets.QApplication.translate("Form", "Load..", None, -1))
self.saveBtn.setText(QtWidgets.QApplication.translate("Form", "Save", None, -1))
self.saveAsBtn.setText(QtWidgets.QApplication.translate("Form", "As..", None, -1))
self.reloadBtn.setText(QtWidgets.QApplication.translate("Form", "Reload Libs", None, -1))
self.showChartBtn.setText(QtWidgets.QApplication.translate("Form", "Flowchart", None, -1))
from ..widgets.FeedbackButton import FeedbackButton
from ..widgets.TreeWidget import TreeWidget
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/flowchart/FlowchartCtrlTemplate_pyqt5.py | .py | 2,908 | 68 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './pyqtgraph/flowchart/FlowchartCtrlTemplate.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(217, 499)
self.gridLayout = QtWidgets.QGridLayout(Form)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setVerticalSpacing(0)
self.gridLayout.setObjectName("gridLayout")
self.loadBtn = QtWidgets.QPushButton(Form)
self.loadBtn.setObjectName("loadBtn")
self.gridLayout.addWidget(self.loadBtn, 1, 0, 1, 1)
self.saveBtn = FeedbackButton(Form)
self.saveBtn.setObjectName("saveBtn")
self.gridLayout.addWidget(self.saveBtn, 1, 1, 1, 2)
self.saveAsBtn = FeedbackButton(Form)
self.saveAsBtn.setObjectName("saveAsBtn")
self.gridLayout.addWidget(self.saveAsBtn, 1, 3, 1, 1)
self.reloadBtn = FeedbackButton(Form)
self.reloadBtn.setCheckable(False)
self.reloadBtn.setFlat(False)
self.reloadBtn.setObjectName("reloadBtn")
self.gridLayout.addWidget(self.reloadBtn, 4, 0, 1, 2)
self.showChartBtn = QtWidgets.QPushButton(Form)
self.showChartBtn.setCheckable(True)
self.showChartBtn.setObjectName("showChartBtn")
self.gridLayout.addWidget(self.showChartBtn, 4, 2, 1, 2)
self.ctrlList = TreeWidget(Form)
self.ctrlList.setObjectName("ctrlList")
self.ctrlList.headerItem().setText(0, "1")
self.ctrlList.header().setVisible(False)
self.ctrlList.header().setStretchLastSection(False)
self.gridLayout.addWidget(self.ctrlList, 3, 0, 1, 4)
self.fileNameLabel = QtWidgets.QLabel(Form)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.fileNameLabel.setFont(font)
self.fileNameLabel.setText("")
self.fileNameLabel.setAlignment(QtCore.Qt.AlignCenter)
self.fileNameLabel.setObjectName("fileNameLabel")
self.gridLayout.addWidget(self.fileNameLabel, 0, 1, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.loadBtn.setText(_translate("Form", "Load.."))
self.saveBtn.setText(_translate("Form", "Save"))
self.saveAsBtn.setText(_translate("Form", "As.."))
self.reloadBtn.setText(_translate("Form", "Reload Libs"))
self.showChartBtn.setText(_translate("Form", "Flowchart"))
from ..widgets.FeedbackButton import FeedbackButton
from ..widgets.TreeWidget import TreeWidget
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/flowchart/Terminal.py | .py | 20,786 | 568 | # -*- coding: utf-8 -*-
from ..Qt import QtCore, QtGui
import weakref
from ..graphicsItems.GraphicsObject import GraphicsObject
from .. import functions as fn
from ..Point import Point
class Terminal(object):
def __init__(self, node, name, io, optional=False, multi=False, pos=None, renamable=False, removable=False, multiable=False, bypass=None):
"""
Construct a new terminal.
============== =================================================================================
**Arguments:**
node the node to which this terminal belongs
name string, the name of the terminal
io 'in' or 'out'
optional bool, whether the node may process without connection to this terminal
multi bool, for inputs: whether this terminal may make multiple connections
for outputs: whether this terminal creates a different value for each connection
pos [x, y], the position of the terminal within its node's boundaries
renamable (bool) Whether the terminal can be renamed by the user
removable (bool) Whether the terminal can be removed by the user
multiable (bool) Whether the user may toggle the *multi* option for this terminal
bypass (str) Name of the terminal from which this terminal's value is derived
when the Node is in bypass mode.
============== =================================================================================
"""
self._io = io
self._optional = optional
self._multi = multi
self._node = weakref.ref(node)
self._name = name
self._renamable = renamable
self._removable = removable
self._multiable = multiable
self._connections = {}
self._graphicsItem = TerminalGraphicsItem(self, parent=self._node().graphicsItem())
self._bypass = bypass
if multi:
self._value = {} ## dictionary of terminal:value pairs.
else:
self._value = None
self.valueOk = None
self.recolor()
def value(self, term=None):
"""Return the value this terminal provides for the connected terminal"""
if term is None:
return self._value
if self.isMultiValue():
return self._value.get(term, None)
else:
return self._value
def bypassValue(self):
return self._bypass
def setValue(self, val, process=True):
"""If this is a single-value terminal, val should be a single value.
If this is a multi-value terminal, val should be a dict of terminal:value pairs"""
if not self.isMultiValue():
if fn.eq(val, self._value):
return
self._value = val
else:
if not isinstance(self._value, dict):
self._value = {}
if val is not None:
self._value.update(val)
self.setValueAcceptable(None) ## by default, input values are 'unchecked' until Node.update().
if self.isInput() and process:
self.node().update()
self.recolor()
def setOpts(self, **opts):
self._renamable = opts.get('renamable', self._renamable)
self._removable = opts.get('removable', self._removable)
self._multiable = opts.get('multiable', self._multiable)
if 'multi' in opts:
self.setMultiValue(opts['multi'])
def connected(self, term):
"""Called whenever this terminal has been connected to another. (note--this function is called on both terminals)"""
if self.isInput() and term.isOutput():
self.inputChanged(term)
if self.isOutput() and self.isMultiValue():
self.node().update()
self.node().connected(self, term)
def disconnected(self, term):
"""Called whenever this terminal has been disconnected from another. (note--this function is called on both terminals)"""
if self.isMultiValue() and term in self._value:
del self._value[term]
self.node().update()
else:
if self.isInput():
self.setValue(None)
self.node().disconnected(self, term)
def inputChanged(self, term, process=True):
"""Called whenever there is a change to the input value to this terminal.
It may often be useful to override this function."""
if self.isMultiValue():
self.setValue({term: term.value(self)}, process=process)
else:
self.setValue(term.value(self), process=process)
def valueIsAcceptable(self):
"""Returns True->acceptable None->unknown False->Unacceptable"""
return self.valueOk
def setValueAcceptable(self, v=True):
self.valueOk = v
self.recolor()
def connections(self):
return self._connections
def node(self):
return self._node()
def isInput(self):
return self._io == 'in'
def isMultiValue(self):
return self._multi
def setMultiValue(self, multi):
"""Set whether this is a multi-value terminal."""
self._multi = multi
if not multi and len(self.inputTerminals()) > 1:
self.disconnectAll()
for term in self.inputTerminals():
self.inputChanged(term)
def isOutput(self):
return self._io == 'out'
def isRenamable(self):
return self._renamable
def isRemovable(self):
return self._removable
def isMultiable(self):
return self._multiable
def name(self):
return self._name
def graphicsItem(self):
return self._graphicsItem
def isConnected(self):
return len(self.connections()) > 0
def connectedTo(self, term):
return term in self.connections()
def hasInput(self):
for t in self.connections():
if t.isOutput():
return True
return False
def inputTerminals(self):
"""Return the terminal(s) that give input to this one."""
return [t for t in self.connections() if t.isOutput()]
def dependentNodes(self):
"""Return the list of nodes which receive input from this terminal."""
return set([t.node() for t in self.connections() if t.isInput()])
def connectTo(self, term, connectionItem=None):
try:
if self.connectedTo(term):
raise Exception('Already connected')
if term is self:
raise Exception('Not connecting terminal to self')
if term.node() is self.node():
raise Exception("Can't connect to terminal on same node.")
for t in [self, term]:
if t.isInput() and not t._multi and len(t.connections()) > 0:
raise Exception("Cannot connect %s <-> %s: Terminal %s is already connected to %s (and does not allow multiple connections)" % (self, term, t, list(t.connections().keys())))
except:
if connectionItem is not None:
connectionItem.close()
raise
if connectionItem is None:
connectionItem = ConnectionItem(self.graphicsItem(), term.graphicsItem())
self.graphicsItem().getViewBox().addItem(connectionItem)
self._connections[term] = connectionItem
term._connections[self] = connectionItem
self.recolor()
self.connected(term)
term.connected(self)
return connectionItem
def disconnectFrom(self, term):
if not self.connectedTo(term):
return
item = self._connections[term]
item.close()
del self._connections[term]
del term._connections[self]
self.recolor()
term.recolor()
self.disconnected(term)
term.disconnected(self)
def disconnectAll(self):
for t in list(self._connections.keys()):
self.disconnectFrom(t)
def recolor(self, color=None, recurse=True):
if color is None:
if not self.isConnected(): ## disconnected terminals are black
color = QtGui.QColor(0,0,0)
elif self.isInput() and not self.hasInput(): ## input terminal with no connected output terminals
color = QtGui.QColor(200,200,0)
elif self._value is None or fn.eq(self._value, {}): ## terminal is connected but has no data (possibly due to processing error)
color = QtGui.QColor(255,255,255)
elif self.valueIsAcceptable() is None: ## terminal has data, but it is unknown if the data is ok
color = QtGui.QColor(200, 200, 0)
elif self.valueIsAcceptable() is True: ## terminal has good input, all ok
color = QtGui.QColor(0, 200, 0)
else: ## terminal has bad input
color = QtGui.QColor(200, 0, 0)
self.graphicsItem().setBrush(QtGui.QBrush(color))
if recurse:
for t in self.connections():
t.recolor(color, recurse=False)
def rename(self, name):
oldName = self._name
self._name = name
self.node().terminalRenamed(self, oldName)
self.graphicsItem().termRenamed(name)
def __repr__(self):
return "<Terminal %s.%s>" % (str(self.node().name()), str(self.name()))
def __hash__(self):
return id(self)
def close(self):
self.disconnectAll()
item = self.graphicsItem()
if item.scene() is not None:
item.scene().removeItem(item)
def saveState(self):
return {'io': self._io, 'multi': self._multi, 'optional': self._optional, 'renamable': self._renamable, 'removable': self._removable, 'multiable': self._multiable}
class TerminalGraphicsItem(GraphicsObject):
def __init__(self, term, parent=None):
self.term = term
GraphicsObject.__init__(self, parent)
self.brush = fn.mkBrush(0,0,0)
self.box = QtGui.QGraphicsRectItem(0, 0, 10, 10, self)
self.label = QtGui.QGraphicsTextItem(self.term.name(), self)
self.label.scale(0.7, 0.7)
self.newConnection = None
self.setFiltersChildEvents(True) ## to pick up mouse events on the rectitem
if self.term.isRenamable():
self.label.setTextInteractionFlags(QtCore.Qt.TextEditorInteraction)
self.label.focusOutEvent = self.labelFocusOut
self.label.keyPressEvent = self.labelKeyPress
self.setZValue(1)
self.menu = None
def labelFocusOut(self, ev):
QtGui.QGraphicsTextItem.focusOutEvent(self.label, ev)
self.labelChanged()
def labelKeyPress(self, ev):
if ev.key() == QtCore.Qt.Key_Enter or ev.key() == QtCore.Qt.Key_Return:
self.labelChanged()
else:
QtGui.QGraphicsTextItem.keyPressEvent(self.label, ev)
def labelChanged(self):
newName = str(self.label.toPlainText())
if newName != self.term.name():
self.term.rename(newName)
def termRenamed(self, name):
self.label.setPlainText(name)
def setBrush(self, brush):
self.brush = brush
self.box.setBrush(brush)
def disconnect(self, target):
self.term.disconnectFrom(target.term)
def boundingRect(self):
br = self.box.mapRectToParent(self.box.boundingRect())
lr = self.label.mapRectToParent(self.label.boundingRect())
return br | lr
def paint(self, p, *args):
pass
def setAnchor(self, x, y):
pos = QtCore.QPointF(x, y)
self.anchorPos = pos
br = self.box.mapRectToParent(self.box.boundingRect())
lr = self.label.mapRectToParent(self.label.boundingRect())
if self.term.isInput():
self.box.setPos(pos.x(), pos.y()-br.height()/2.)
self.label.setPos(pos.x() + br.width(), pos.y() - lr.height()/2.)
else:
self.box.setPos(pos.x()-br.width(), pos.y()-br.height()/2.)
self.label.setPos(pos.x()-br.width()-lr.width(), pos.y()-lr.height()/2.)
self.updateConnections()
def updateConnections(self):
for t, c in self.term.connections().items():
c.updateLine()
def mousePressEvent(self, ev):
#ev.accept()
ev.ignore() ## necessary to allow click/drag events to process correctly
def mouseClickEvent(self, ev):
if ev.button() == QtCore.Qt.LeftButton:
ev.accept()
self.label.setFocus(QtCore.Qt.MouseFocusReason)
elif ev.button() == QtCore.Qt.RightButton:
ev.accept()
self.raiseContextMenu(ev)
def raiseContextMenu(self, ev):
## only raise menu if this terminal is removable
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("Terminal")
remAct = QtGui.QAction("Remove terminal", self.menu)
remAct.triggered.connect(self.removeSelf)
self.menu.addAction(remAct)
self.menu.remAct = remAct
if not self.term.isRemovable():
remAct.setEnabled(False)
multiAct = QtGui.QAction("Multi-value", self.menu)
multiAct.setCheckable(True)
multiAct.setChecked(self.term.isMultiValue())
multiAct.setEnabled(self.term.isMultiable())
multiAct.triggered.connect(self.toggleMulti)
self.menu.addAction(multiAct)
self.menu.multiAct = multiAct
if self.term.isMultiable():
multiAct.setEnabled = False
return self.menu
def toggleMulti(self):
multi = self.menu.multiAct.isChecked()
self.term.setMultiValue(multi)
def removeSelf(self):
self.term.node().removeTerminal(self.term)
def mouseDragEvent(self, ev):
if ev.button() != QtCore.Qt.LeftButton:
ev.ignore()
return
ev.accept()
if ev.isStart():
if self.newConnection is None:
self.newConnection = ConnectionItem(self)
#self.scene().addItem(self.newConnection)
self.getViewBox().addItem(self.newConnection)
#self.newConnection.setParentItem(self.parent().parent())
self.newConnection.setTarget(self.mapToView(ev.pos()))
elif ev.isFinish():
if self.newConnection is not None:
items = self.scene().items(ev.scenePos())
gotTarget = False
for i in items:
if isinstance(i, TerminalGraphicsItem):
self.newConnection.setTarget(i)
try:
self.term.connectTo(i.term, self.newConnection)
gotTarget = True
except:
self.scene().removeItem(self.newConnection)
self.newConnection = None
raise
break
if not gotTarget:
self.newConnection.close()
self.newConnection = None
else:
if self.newConnection is not None:
self.newConnection.setTarget(self.mapToView(ev.pos()))
def hoverEvent(self, ev):
if not ev.isExit() 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)
self.box.setBrush(fn.mkBrush('w'))
else:
self.box.setBrush(self.brush)
self.update()
def connectPoint(self):
## return the connect position of this terminal in view coords
return self.mapToView(self.mapFromItem(self.box, self.box.boundingRect().center()))
def nodeMoved(self):
for t, item in self.term.connections().items():
item.updateLine()
class ConnectionItem(GraphicsObject):
def __init__(self, source, target=None):
GraphicsObject.__init__(self)
self.setFlags(
self.ItemIsSelectable |
self.ItemIsFocusable
)
self.source = source
self.target = target
self.length = 0
self.hovered = False
self.path = None
self.shapePath = None
self.style = {
'shape': 'line',
'color': (100, 100, 250),
'width': 1.0,
'hoverColor': (150, 150, 250),
'hoverWidth': 1.0,
'selectedColor': (200, 200, 0),
'selectedWidth': 3.0,
}
self.source.getViewBox().addItem(self)
self.updateLine()
self.setZValue(0)
def close(self):
if self.scene() is not None:
self.scene().removeItem(self)
def setTarget(self, target):
self.target = target
self.updateLine()
def setStyle(self, **kwds):
self.style.update(kwds)
if 'shape' in kwds:
self.updateLine()
else:
self.update()
def updateLine(self):
start = Point(self.source.connectPoint())
if isinstance(self.target, TerminalGraphicsItem):
stop = Point(self.target.connectPoint())
elif isinstance(self.target, QtCore.QPointF):
stop = Point(self.target)
else:
return
self.prepareGeometryChange()
self.path = self.generatePath(start, stop)
self.shapePath = None
self.update()
def generatePath(self, start, stop):
path = QtGui.QPainterPath()
path.moveTo(start)
if self.style['shape'] == 'line':
path.lineTo(stop)
elif self.style['shape'] == 'cubic':
path.cubicTo(Point(stop.x(), start.y()), Point(start.x(), stop.y()), Point(stop.x(), stop.y()))
else:
raise Exception('Invalid shape "%s"; options are "line" or "cubic"' % self.style['shape'])
return path
def keyPressEvent(self, ev):
if not self.isSelected():
ev.ignore()
return
if ev.key() == QtCore.Qt.Key_Delete or ev.key() == QtCore.Qt.Key_Backspace:
self.source.disconnect(self.target)
ev.accept()
else:
ev.ignore()
def mousePressEvent(self, ev):
ev.ignore()
def mouseClickEvent(self, ev):
if ev.button() == QtCore.Qt.LeftButton:
ev.accept()
sel = self.isSelected()
self.setSelected(True)
self.setFocus()
if not sel and self.isSelected():
self.update()
def hoverEvent(self, ev):
if (not ev.isExit()) and ev.acceptClicks(QtCore.Qt.LeftButton):
self.hovered = True
else:
self.hovered = False
self.update()
def boundingRect(self):
return self.shape().boundingRect()
def viewRangeChanged(self):
self.shapePath = None
self.prepareGeometryChange()
def shape(self):
if self.shapePath is None:
if self.path is None:
return QtGui.QPainterPath()
stroker = QtGui.QPainterPathStroker()
px = self.pixelWidth()
stroker.setWidth(px*8)
self.shapePath = stroker.createStroke(self.path)
return self.shapePath
def paint(self, p, *args):
if self.isSelected():
p.setPen(fn.mkPen(self.style['selectedColor'], width=self.style['selectedWidth']))
else:
if self.hovered:
p.setPen(fn.mkPen(self.style['hoverColor'], width=self.style['hoverWidth']))
else:
p.setPen(fn.mkPen(self.style['color'], width=self.style['width']))
p.drawPath(self.path)
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/flowchart/Flowchart.py | .py | 35,702 | 941 | # -*- coding: utf-8 -*-
from ..Qt import QtCore, QtGui, QT_LIB
from .Node import *
from ..pgcollections import OrderedDict
from ..widgets.TreeWidget import *
from .. import FileDialog, DataTreeWidget
## pyside and pyqt use incompatible ui files.
if QT_LIB == 'PySide':
from . import FlowchartTemplate_pyside as FlowchartTemplate
from . import FlowchartCtrlTemplate_pyside as FlowchartCtrlTemplate
elif QT_LIB == 'PySide2':
from . import FlowchartTemplate_pyside2 as FlowchartTemplate
from . import FlowchartCtrlTemplate_pyside2 as FlowchartCtrlTemplate
elif QT_LIB == 'PyQt5':
from . import FlowchartTemplate_pyqt5 as FlowchartTemplate
from . import FlowchartCtrlTemplate_pyqt5 as FlowchartCtrlTemplate
else:
from . import FlowchartTemplate_pyqt as FlowchartTemplate
from . import FlowchartCtrlTemplate_pyqt as FlowchartCtrlTemplate
from .Terminal import Terminal
from numpy import ndarray
from .library import LIBRARY
from ..debug import printExc
from .. import configfile as configfile
from .. import dockarea as dockarea
from . import FlowchartGraphicsView
from .. import functions as fn
from ..python2_3 import asUnicode
def strDict(d):
return dict([(str(k), v) for k, v in d.items()])
class Flowchart(Node):
sigFileLoaded = QtCore.Signal(object)
sigFileSaved = QtCore.Signal(object)
#sigOutputChanged = QtCore.Signal() ## inherited from Node
sigChartLoaded = QtCore.Signal()
sigStateChanged = QtCore.Signal() # called when output is expected to have changed
sigChartChanged = QtCore.Signal(object, object, object) # called when nodes are added, removed, or renamed.
# (self, action, node)
def __init__(self, terminals=None, name=None, filePath=None, library=None):
self.library = library or LIBRARY
if name is None:
name = "Flowchart"
if terminals is None:
terminals = {}
self.filePath = filePath
Node.__init__(self, name, allowAddInput=True, allowAddOutput=True) ## create node without terminals; we'll add these later
self.inputWasSet = False ## flag allows detection of changes in the absence of input change.
self._nodes = {}
self.nextZVal = 10
#self.connects = []
#self._chartGraphicsItem = FlowchartGraphicsItem(self)
self._widget = None
self._scene = None
self.processing = False ## flag that prevents recursive node updates
self.widget()
self.inputNode = Node('Input', allowRemove=False, allowAddOutput=True)
self.outputNode = Node('Output', allowRemove=False, allowAddInput=True)
self.addNode(self.inputNode, 'Input', [-150, 0])
self.addNode(self.outputNode, 'Output', [300, 0])
self.outputNode.sigOutputChanged.connect(self.outputChanged)
self.outputNode.sigTerminalRenamed.connect(self.internalTerminalRenamed)
self.inputNode.sigTerminalRenamed.connect(self.internalTerminalRenamed)
self.outputNode.sigTerminalRemoved.connect(self.internalTerminalRemoved)
self.inputNode.sigTerminalRemoved.connect(self.internalTerminalRemoved)
self.outputNode.sigTerminalAdded.connect(self.internalTerminalAdded)
self.inputNode.sigTerminalAdded.connect(self.internalTerminalAdded)
self.viewBox.autoRange(padding = 0.04)
for name, opts in terminals.items():
self.addTerminal(name, **opts)
def setLibrary(self, lib):
self.library = lib
self.widget().chartWidget.buildMenu()
def setInput(self, **args):
"""Set the input values of the flowchart. This will automatically propagate
the new values throughout the flowchart, (possibly) causing the output to change.
"""
#print "setInput", args
#Node.setInput(self, **args)
#print " ....."
self.inputWasSet = True
self.inputNode.setOutput(**args)
def outputChanged(self):
## called when output of internal node has changed
vals = self.outputNode.inputValues()
self.widget().outputChanged(vals)
self.setOutput(**vals)
#self.sigOutputChanged.emit(self)
def output(self):
"""Return a dict of the values on the Flowchart's output terminals.
"""
return self.outputNode.inputValues()
def nodes(self):
return self._nodes
def addTerminal(self, name, **opts):
term = Node.addTerminal(self, name, **opts)
name = term.name()
if opts['io'] == 'in': ## inputs to the flowchart become outputs on the input node
opts['io'] = 'out'
opts['multi'] = False
self.inputNode.sigTerminalAdded.disconnect(self.internalTerminalAdded)
try:
term2 = self.inputNode.addTerminal(name, **opts)
finally:
self.inputNode.sigTerminalAdded.connect(self.internalTerminalAdded)
else:
opts['io'] = 'in'
#opts['multi'] = False
self.outputNode.sigTerminalAdded.disconnect(self.internalTerminalAdded)
try:
term2 = self.outputNode.addTerminal(name, **opts)
finally:
self.outputNode.sigTerminalAdded.connect(self.internalTerminalAdded)
return term
def removeTerminal(self, name):
#print "remove:", name
term = self[name]
inTerm = self.internalTerminal(term)
Node.removeTerminal(self, name)
inTerm.node().removeTerminal(inTerm.name())
def internalTerminalRenamed(self, term, oldName):
self[oldName].rename(term.name())
def internalTerminalAdded(self, node, term):
if term._io == 'in':
io = 'out'
else:
io = 'in'
Node.addTerminal(self, term.name(), io=io, renamable=term.isRenamable(), removable=term.isRemovable(), multiable=term.isMultiable())
def internalTerminalRemoved(self, node, term):
try:
Node.removeTerminal(self, term.name())
except KeyError:
pass
def terminalRenamed(self, term, oldName):
newName = term.name()
#print "flowchart rename", newName, oldName
#print self.terminals
Node.terminalRenamed(self, self[oldName], oldName)
#print self.terminals
for n in [self.inputNode, self.outputNode]:
if oldName in n.terminals:
n[oldName].rename(newName)
def createNode(self, nodeType, name=None, pos=None):
"""Create a new Node and add it to this flowchart.
"""
if name is None:
n = 0
while True:
name = "%s.%d" % (nodeType, n)
if name not in self._nodes:
break
n += 1
node = self.library.getNodeType(nodeType)(name)
self.addNode(node, name, pos)
return node
def addNode(self, node, name, pos=None):
"""Add an existing Node to this flowchart.
See also: createNode()
"""
if pos is None:
pos = [0, 0]
if type(pos) in [QtCore.QPoint, QtCore.QPointF]:
pos = [pos.x(), pos.y()]
item = node.graphicsItem()
item.setZValue(self.nextZVal*2)
self.nextZVal += 1
self.viewBox.addItem(item)
item.moveBy(*pos)
self._nodes[name] = node
if node is not self.inputNode and node is not self.outputNode:
self.widget().addNode(node)
node.sigClosed.connect(self.nodeClosed)
node.sigRenamed.connect(self.nodeRenamed)
node.sigOutputChanged.connect(self.nodeOutputChanged)
self.sigChartChanged.emit(self, 'add', node)
def removeNode(self, node):
"""Remove a Node from this flowchart.
"""
node.close()
def nodeClosed(self, node):
del self._nodes[node.name()]
self.widget().removeNode(node)
for signal in ['sigClosed', 'sigRenamed', 'sigOutputChanged']:
try:
getattr(node, signal).disconnect(self.nodeClosed)
except (TypeError, RuntimeError):
pass
self.sigChartChanged.emit(self, 'remove', node)
def nodeRenamed(self, node, oldName):
del self._nodes[oldName]
self._nodes[node.name()] = node
self.widget().nodeRenamed(node, oldName)
self.sigChartChanged.emit(self, 'rename', node)
def arrangeNodes(self):
pass
def internalTerminal(self, term):
"""If the terminal belongs to the external Node, return the corresponding internal terminal"""
if term.node() is self:
if term.isInput():
return self.inputNode[term.name()]
else:
return self.outputNode[term.name()]
else:
return term
def connectTerminals(self, term1, term2):
"""Connect two terminals together within this flowchart."""
term1 = self.internalTerminal(term1)
term2 = self.internalTerminal(term2)
term1.connectTo(term2)
def process(self, **args):
"""
Process data through the flowchart, returning the output.
Keyword arguments must be the names of input terminals.
The return value is a dict with one key per output terminal.
"""
data = {} ## Stores terminal:value pairs
## determine order of operations
## order should look like [('p', node1), ('p', node2), ('d', terminal1), ...]
## Each tuple specifies either (p)rocess this node or (d)elete the result from this terminal
order = self.processOrder()
#print "ORDER:", order
## Record inputs given to process()
for n, t in self.inputNode.outputs().items():
# if n not in args:
# raise Exception("Parameter %s required to process this chart." % n)
if n in args:
data[t] = args[n]
ret = {}
## process all in order
for c, arg in order:
if c == 'p': ## Process a single node
#print "===> process:", arg
node = arg
if node is self.inputNode:
continue ## input node has already been processed.
## get input and output terminals for this node
outs = list(node.outputs().values())
ins = list(node.inputs().values())
## construct input value dictionary
args = {}
for inp in ins:
inputs = inp.inputTerminals()
if len(inputs) == 0:
continue
if inp.isMultiValue(): ## multi-input terminals require a dict of all inputs
args[inp.name()] = dict([(i, data[i]) for i in inputs if i in data])
else: ## single-inputs terminals only need the single input value available
args[inp.name()] = data[inputs[0]]
if node is self.outputNode:
ret = args ## we now have the return value, but must keep processing in case there are other endpoint nodes in the chart
else:
try:
if node.isBypassed():
result = node.processBypassed(args)
else:
result = node.process(display=False, **args)
except:
print("Error processing node %s. Args are: %s" % (str(node), str(args)))
raise
for out in outs:
#print " Output:", out, out.name()
#print out.name()
try:
data[out] = result[out.name()]
except KeyError:
pass
elif c == 'd': ## delete a terminal result (no longer needed; may be holding a lot of memory)
#print "===> delete", arg
if arg in data:
del data[arg]
return ret
def processOrder(self):
"""Return the order of operations required to process this chart.
The order returned should look like [('p', node1), ('p', node2), ('d', terminal1), ...]
where each tuple specifies either (p)rocess this node or (d)elete the result from this terminal
"""
## first collect list of nodes/terminals and their dependencies
deps = {}
tdeps = {} ## {terminal: [nodes that depend on terminal]}
for name, node in self._nodes.items():
deps[node] = node.dependentNodes()
for t in node.outputs().values():
tdeps[t] = t.dependentNodes()
#print "DEPS:", deps
## determine correct node-processing order
order = fn.toposort(deps)
#print "ORDER1:", order
## construct list of operations
ops = [('p', n) for n in order]
## determine when it is safe to delete terminal values
dels = []
for t, nodes in tdeps.items():
lastInd = 0
lastNode = None
for n in nodes: ## determine which node is the last to be processed according to order
if n is self:
lastInd = None
break
else:
try:
ind = order.index(n)
except ValueError:
continue
if lastNode is None or ind > lastInd:
lastNode = n
lastInd = ind
if lastInd is not None:
dels.append((lastInd+1, t))
dels.sort(key=lambda a: a[0], reverse=True)
for i, t in dels:
ops.insert(i, ('d', t))
return ops
def nodeOutputChanged(self, startNode):
"""Triggered when a node's output values have changed. (NOT called during process())
Propagates new data forward through network."""
## first collect list of nodes/terminals and their dependencies
if self.processing:
return
self.processing = True
try:
deps = {}
for name, node in self._nodes.items():
deps[node] = []
for t in node.outputs().values():
deps[node].extend(t.dependentNodes())
## determine order of updates
order = fn.toposort(deps, nodes=[startNode])
order.reverse()
## keep track of terminals that have been updated
terms = set(startNode.outputs().values())
#print "======= Updating", startNode
# print("Order:", order)
for node in order[1:]:
# print("Processing node", node)
update = False
for term in list(node.inputs().values()):
# print(" checking terminal", term)
deps = list(term.connections().keys())
for d in deps:
if d in terms:
# print(" ..input", d, "changed")
update |= True
term.inputChanged(d, process=False)
if update:
# print(" processing..")
node.update()
terms |= set(node.outputs().values())
finally:
self.processing = False
if self.inputWasSet:
self.inputWasSet = False
else:
self.sigStateChanged.emit()
def chartGraphicsItem(self):
"""Return the graphicsItem that displays the internal nodes and
connections of this flowchart.
Note that the similar method `graphicsItem()` is inherited from Node
and returns the *external* graphical representation of this flowchart."""
return self.viewBox
def widget(self):
"""Return the control widget for this flowchart.
This widget provides GUI access to the parameters for each node and a
graphical representation of the flowchart.
"""
if self._widget is None:
self._widget = FlowchartCtrlWidget(self)
self.scene = self._widget.scene()
self.viewBox = self._widget.viewBox()
return self._widget
def listConnections(self):
conn = set()
for n in self._nodes.values():
terms = n.outputs()
for n, t in terms.items():
for c in t.connections():
conn.add((t, c))
return conn
def saveState(self):
"""Return a serializable data structure representing the current state of this flowchart.
"""
state = Node.saveState(self)
state['nodes'] = []
state['connects'] = []
for name, node in self._nodes.items():
cls = type(node)
if hasattr(cls, 'nodeName'):
clsName = cls.nodeName
pos = node.graphicsItem().pos()
ns = {'class': clsName, 'name': name, 'pos': (pos.x(), pos.y()), 'state': node.saveState()}
state['nodes'].append(ns)
conn = self.listConnections()
for a, b in conn:
state['connects'].append((a.node().name(), a.name(), b.node().name(), b.name()))
state['inputNode'] = self.inputNode.saveState()
state['outputNode'] = self.outputNode.saveState()
return state
def restoreState(self, state, clear=False):
"""Restore the state of this flowchart from a previous call to `saveState()`.
"""
self.blockSignals(True)
try:
if clear:
self.clear()
Node.restoreState(self, state)
nodes = state['nodes']
nodes.sort(key=lambda a: a['pos'][0])
for n in nodes:
if n['name'] in self._nodes:
self._nodes[n['name']].restoreState(n['state'])
continue
try:
node = self.createNode(n['class'], name=n['name'])
node.restoreState(n['state'])
except:
printExc("Error creating node %s: (continuing anyway)" % n['name'])
self.inputNode.restoreState(state.get('inputNode', {}))
self.outputNode.restoreState(state.get('outputNode', {}))
#self.restoreTerminals(state['terminals'])
for n1, t1, n2, t2 in state['connects']:
try:
self.connectTerminals(self._nodes[n1][t1], self._nodes[n2][t2])
except:
print(self._nodes[n1].terminals)
print(self._nodes[n2].terminals)
printExc("Error connecting terminals %s.%s - %s.%s:" % (n1, t1, n2, t2))
finally:
self.blockSignals(False)
self.outputChanged()
self.sigChartLoaded.emit()
self.sigStateChanged.emit()
def loadFile(self, fileName=None, startDir=None):
"""Load a flowchart (``*.fc``) file.
"""
if fileName is None:
if startDir is None:
startDir = self.filePath
if startDir is None:
startDir = '.'
self.fileDialog = FileDialog(None, "Load Flowchart..", startDir, "Flowchart (*.fc)")
self.fileDialog.show()
self.fileDialog.fileSelected.connect(self.loadFile)
return
## NOTE: was previously using a real widget for the file dialog's parent, but this caused weird mouse event bugs..
fileName = asUnicode(fileName)
state = configfile.readConfigFile(fileName)
self.restoreState(state, clear=True)
self.viewBox.autoRange()
self.sigFileLoaded.emit(fileName)
def saveFile(self, fileName=None, startDir=None, suggestedFileName='flowchart.fc'):
"""Save this flowchart to a .fc file
"""
if fileName is None:
if startDir is None:
startDir = self.filePath
if startDir is None:
startDir = '.'
self.fileDialog = FileDialog(None, "Save Flowchart..", startDir, "Flowchart (*.fc)")
self.fileDialog.setDefaultSuffix("fc")
self.fileDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
self.fileDialog.show()
self.fileDialog.fileSelected.connect(self.saveFile)
return
fileName = asUnicode(fileName)
configfile.writeConfigFile(self.saveState(), fileName)
self.sigFileSaved.emit(fileName)
def clear(self):
"""Remove all nodes from this flowchart except the original input/output nodes.
"""
for n in list(self._nodes.values()):
if n is self.inputNode or n is self.outputNode:
continue
n.close() ## calls self.nodeClosed(n) by signal
#self.clearTerminals()
self.widget().clear()
def clearTerminals(self):
Node.clearTerminals(self)
self.inputNode.clearTerminals()
self.outputNode.clearTerminals()
class FlowchartGraphicsItem(GraphicsObject):
def __init__(self, chart):
GraphicsObject.__init__(self)
self.chart = chart ## chart is an instance of Flowchart()
self.updateTerminals()
def updateTerminals(self):
self.terminals = {}
bounds = self.boundingRect()
inp = self.chart.inputs()
dy = bounds.height() / (len(inp)+1)
y = dy
for n, t in inp.items():
item = t.graphicsItem()
self.terminals[n] = item
item.setParentItem(self)
item.setAnchor(bounds.width(), y)
y += dy
out = self.chart.outputs()
dy = bounds.height() / (len(out)+1)
y = dy
for n, t in out.items():
item = t.graphicsItem()
self.terminals[n] = item
item.setParentItem(self)
item.setAnchor(0, y)
y += dy
def boundingRect(self):
#print "FlowchartGraphicsItem.boundingRect"
return QtCore.QRectF()
def paint(self, p, *args):
#print "FlowchartGraphicsItem.paint"
pass
#p.drawRect(self.boundingRect())
class FlowchartCtrlWidget(QtGui.QWidget):
"""The widget that contains the list of all the nodes in a flowchart and their controls, as well as buttons for loading/saving flowcharts."""
def __init__(self, chart):
self.items = {}
#self.loadDir = loadDir ## where to look initially for chart files
self.currentFileName = None
QtGui.QWidget.__init__(self)
self.chart = chart
self.ui = FlowchartCtrlTemplate.Ui_Form()
self.ui.setupUi(self)
self.ui.ctrlList.setColumnCount(2)
#self.ui.ctrlList.setColumnWidth(0, 200)
self.ui.ctrlList.setColumnWidth(1, 20)
self.ui.ctrlList.setVerticalScrollMode(self.ui.ctrlList.ScrollPerPixel)
self.ui.ctrlList.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.chartWidget = FlowchartWidget(chart, self)
#self.chartWidget.viewBox().autoRange()
self.cwWin = QtGui.QMainWindow()
self.cwWin.setWindowTitle('Flowchart')
self.cwWin.setCentralWidget(self.chartWidget)
self.cwWin.resize(1000,800)
h = self.ui.ctrlList.header()
if QT_LIB in ['PyQt4', 'PySide']:
h.setResizeMode(0, h.Stretch)
else:
h.setSectionResizeMode(0, h.Stretch)
self.ui.ctrlList.itemChanged.connect(self.itemChanged)
self.ui.loadBtn.clicked.connect(self.loadClicked)
self.ui.saveBtn.clicked.connect(self.saveClicked)
self.ui.saveAsBtn.clicked.connect(self.saveAsClicked)
self.ui.showChartBtn.toggled.connect(self.chartToggled)
self.chart.sigFileLoaded.connect(self.setCurrentFile)
self.ui.reloadBtn.clicked.connect(self.reloadClicked)
self.chart.sigFileSaved.connect(self.fileSaved)
#def resizeEvent(self, ev):
#QtGui.QWidget.resizeEvent(self, ev)
#self.ui.ctrlList.setColumnWidth(0, self.ui.ctrlList.viewport().width()-20)
def chartToggled(self, b):
if b:
self.cwWin.show()
else:
self.cwWin.hide()
def reloadClicked(self):
try:
self.chartWidget.reloadLibrary()
self.ui.reloadBtn.success("Reloaded.")
except:
self.ui.reloadBtn.success("Error.")
raise
def loadClicked(self):
newFile = self.chart.loadFile()
#self.setCurrentFile(newFile)
def fileSaved(self, fileName):
self.setCurrentFile(asUnicode(fileName))
self.ui.saveBtn.success("Saved.")
def saveClicked(self):
if self.currentFileName is None:
self.saveAsClicked()
else:
try:
self.chart.saveFile(self.currentFileName)
#self.ui.saveBtn.success("Saved.")
except:
self.ui.saveBtn.failure("Error")
raise
def saveAsClicked(self):
try:
if self.currentFileName is None:
newFile = self.chart.saveFile()
else:
newFile = self.chart.saveFile(suggestedFileName=self.currentFileName)
#self.ui.saveAsBtn.success("Saved.")
#print "Back to saveAsClicked."
except:
self.ui.saveBtn.failure("Error")
raise
#self.setCurrentFile(newFile)
def setCurrentFile(self, fileName):
self.currentFileName = asUnicode(fileName)
if fileName is None:
self.ui.fileNameLabel.setText("<b>[ new ]</b>")
else:
self.ui.fileNameLabel.setText("<b>%s</b>" % os.path.split(self.currentFileName)[1])
self.resizeEvent(None)
def itemChanged(self, *args):
pass
def scene(self):
return self.chartWidget.scene() ## returns the GraphicsScene object
def viewBox(self):
return self.chartWidget.viewBox()
def nodeRenamed(self, node, oldName):
self.items[node].setText(0, node.name())
def addNode(self, node):
ctrl = node.ctrlWidget()
#if ctrl is None:
#return
item = QtGui.QTreeWidgetItem([node.name(), '', ''])
self.ui.ctrlList.addTopLevelItem(item)
byp = QtGui.QPushButton('X')
byp.setCheckable(True)
byp.setFixedWidth(20)
item.bypassBtn = byp
self.ui.ctrlList.setItemWidget(item, 1, byp)
byp.node = node
node.bypassButton = byp
byp.setChecked(node.isBypassed())
byp.clicked.connect(self.bypassClicked)
if ctrl is not None:
item2 = QtGui.QTreeWidgetItem()
item.addChild(item2)
self.ui.ctrlList.setItemWidget(item2, 0, ctrl)
self.items[node] = item
def removeNode(self, node):
if node in self.items:
item = self.items[node]
#self.disconnect(item.bypassBtn, QtCore.SIGNAL('clicked()'), self.bypassClicked)
try:
item.bypassBtn.clicked.disconnect(self.bypassClicked)
except (TypeError, RuntimeError):
pass
self.ui.ctrlList.removeTopLevelItem(item)
def bypassClicked(self):
btn = QtCore.QObject.sender(self)
btn.node.bypass(btn.isChecked())
def chartWidget(self):
return self.chartWidget
def outputChanged(self, data):
pass
#self.ui.outputTree.setData(data, hideRoot=True)
def clear(self):
self.chartWidget.clear()
def select(self, node):
item = self.items[node]
self.ui.ctrlList.setCurrentItem(item)
class FlowchartWidget(dockarea.DockArea):
"""Includes the actual graphical flowchart and debugging interface"""
def __init__(self, chart, ctrl):
#QtGui.QWidget.__init__(self)
dockarea.DockArea.__init__(self)
self.chart = chart
self.ctrl = ctrl
self.hoverItem = None
#self.setMinimumWidth(250)
#self.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Expanding))
#self.ui = FlowchartTemplate.Ui_Form()
#self.ui.setupUi(self)
## build user interface (it was easier to do it here than via developer)
self.view = FlowchartGraphicsView.FlowchartGraphicsView(self)
self.viewDock = dockarea.Dock('view', size=(1000,600))
self.viewDock.addWidget(self.view)
self.viewDock.hideTitleBar()
self.addDock(self.viewDock)
self.hoverText = QtGui.QTextEdit()
self.hoverText.setReadOnly(True)
self.hoverDock = dockarea.Dock('Hover Info', size=(1000,20))
self.hoverDock.addWidget(self.hoverText)
self.addDock(self.hoverDock, 'bottom')
self.selInfo = QtGui.QWidget()
self.selInfoLayout = QtGui.QGridLayout()
self.selInfo.setLayout(self.selInfoLayout)
self.selDescLabel = QtGui.QLabel()
self.selNameLabel = QtGui.QLabel()
self.selDescLabel.setWordWrap(True)
self.selectedTree = DataTreeWidget()
#self.selectedTree.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
#self.selInfoLayout.addWidget(self.selNameLabel)
self.selInfoLayout.addWidget(self.selDescLabel)
self.selInfoLayout.addWidget(self.selectedTree)
self.selDock = dockarea.Dock('Selected Node', size=(1000,200))
self.selDock.addWidget(self.selInfo)
self.addDock(self.selDock, 'bottom')
self._scene = self.view.scene()
self._viewBox = self.view.viewBox()
#self._scene = QtGui.QGraphicsScene()
#self._scene = FlowchartGraphicsView.FlowchartGraphicsScene()
#self.view.setScene(self._scene)
self.buildMenu()
#self.ui.addNodeBtn.mouseReleaseEvent = self.addNodeBtnReleased
self._scene.selectionChanged.connect(self.selectionChanged)
self._scene.sigMouseHover.connect(self.hoverOver)
#self.view.sigClicked.connect(self.showViewMenu)
#self._scene.sigSceneContextMenu.connect(self.showViewMenu)
#self._viewBox.sigActionPositionChanged.connect(self.menuPosChanged)
def reloadLibrary(self):
#QtCore.QObject.disconnect(self.nodeMenu, QtCore.SIGNAL('triggered(QAction*)'), self.nodeMenuTriggered)
self.nodeMenu.triggered.disconnect(self.nodeMenuTriggered)
self.nodeMenu = None
self.subMenus = []
self.chart.library.reload()
self.buildMenu()
def buildMenu(self, pos=None):
def buildSubMenu(node, rootMenu, subMenus, pos=None):
for section, node in node.items():
if isinstance(node, OrderedDict):
menu = QtGui.QMenu(section)
rootMenu.addMenu(menu)
buildSubMenu(node, menu, subMenus, pos=pos)
subMenus.append(menu)
else:
act = rootMenu.addAction(section)
act.nodeType = section
act.pos = pos
self.nodeMenu = QtGui.QMenu()
self.subMenus = []
buildSubMenu(self.chart.library.getNodeTree(), self.nodeMenu, self.subMenus, pos=pos)
self.nodeMenu.triggered.connect(self.nodeMenuTriggered)
return self.nodeMenu
def menuPosChanged(self, pos):
self.menuPos = pos
def showViewMenu(self, ev):
#QtGui.QPushButton.mouseReleaseEvent(self.ui.addNodeBtn, ev)
#if ev.button() == QtCore.Qt.RightButton:
#self.menuPos = self.view.mapToScene(ev.pos())
#self.nodeMenu.popup(ev.globalPos())
#print "Flowchart.showViewMenu called"
#self.menuPos = ev.scenePos()
self.buildMenu(ev.scenePos())
self.nodeMenu.popup(ev.screenPos())
def scene(self):
return self._scene ## the GraphicsScene item
def viewBox(self):
return self._viewBox ## the viewBox that items should be added to
def nodeMenuTriggered(self, action):
nodeType = action.nodeType
if action.pos is not None:
pos = action.pos
else:
pos = self.menuPos
pos = self.viewBox().mapSceneToView(pos)
self.chart.createNode(nodeType, pos=pos)
def selectionChanged(self):
#print "FlowchartWidget.selectionChanged called."
items = self._scene.selectedItems()
#print " scene.selectedItems: ", items
if len(items) == 0:
data = None
else:
item = items[0]
if hasattr(item, 'node') and isinstance(item.node, Node):
n = item.node
self.ctrl.select(n)
data = {'outputs': n.outputValues(), 'inputs': n.inputValues()}
self.selNameLabel.setText(n.name())
if hasattr(n, 'nodeName'):
self.selDescLabel.setText("<b>%s</b>: %s" % (n.nodeName, n.__class__.__doc__))
else:
self.selDescLabel.setText("")
if n.exception is not None:
data['exception'] = n.exception
else:
data = None
self.selectedTree.setData(data, hideRoot=True)
def hoverOver(self, items):
#print "FlowchartWidget.hoverOver called."
term = None
for item in items:
if item is self.hoverItem:
return
self.hoverItem = item
if hasattr(item, 'term') and isinstance(item.term, Terminal):
term = item.term
break
if term is None:
self.hoverText.setPlainText("")
else:
val = term.value()
if isinstance(val, ndarray):
val = "%s %s %s" % (type(val).__name__, str(val.shape), str(val.dtype))
else:
val = str(val)
if len(val) > 400:
val = val[:400] + "..."
self.hoverText.setPlainText("%s.%s = %s" % (term.node().name(), term.name(), val))
#self.hoverLabel.setCursorPosition(0)
def clear(self):
#self.outputTree.setData(None)
self.selectedTree.setData(None)
self.hoverText.setPlainText('')
self.selNameLabel.setText('')
self.selDescLabel.setText('')
class FlowchartNode(Node):
pass
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/flowchart/FlowchartCtrlTemplate_pyside.py | .py | 3,175 | 67 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './pyqtgraph/flowchart/FlowchartCtrlTemplate.ui'
#
# Created: Mon Dec 23 10:10:51 2013
# by: pyside-uic 0.2.14 running on PySide 1.1.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(217, 499)
self.gridLayout = QtGui.QGridLayout(Form)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setVerticalSpacing(0)
self.gridLayout.setObjectName("gridLayout")
self.loadBtn = QtGui.QPushButton(Form)
self.loadBtn.setObjectName("loadBtn")
self.gridLayout.addWidget(self.loadBtn, 1, 0, 1, 1)
self.saveBtn = FeedbackButton(Form)
self.saveBtn.setObjectName("saveBtn")
self.gridLayout.addWidget(self.saveBtn, 1, 1, 1, 2)
self.saveAsBtn = FeedbackButton(Form)
self.saveAsBtn.setObjectName("saveAsBtn")
self.gridLayout.addWidget(self.saveAsBtn, 1, 3, 1, 1)
self.reloadBtn = FeedbackButton(Form)
self.reloadBtn.setCheckable(False)
self.reloadBtn.setFlat(False)
self.reloadBtn.setObjectName("reloadBtn")
self.gridLayout.addWidget(self.reloadBtn, 4, 0, 1, 2)
self.showChartBtn = QtGui.QPushButton(Form)
self.showChartBtn.setCheckable(True)
self.showChartBtn.setObjectName("showChartBtn")
self.gridLayout.addWidget(self.showChartBtn, 4, 2, 1, 2)
self.ctrlList = TreeWidget(Form)
self.ctrlList.setObjectName("ctrlList")
self.ctrlList.headerItem().setText(0, "1")
self.ctrlList.header().setVisible(False)
self.ctrlList.header().setStretchLastSection(False)
self.gridLayout.addWidget(self.ctrlList, 3, 0, 1, 4)
self.fileNameLabel = QtGui.QLabel(Form)
font = QtGui.QFont()
font.setWeight(75)
font.setBold(True)
self.fileNameLabel.setFont(font)
self.fileNameLabel.setText("")
self.fileNameLabel.setAlignment(QtCore.Qt.AlignCenter)
self.fileNameLabel.setObjectName("fileNameLabel")
self.gridLayout.addWidget(self.fileNameLabel, 0, 1, 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.loadBtn.setText(QtGui.QApplication.translate("Form", "Load..", None, QtGui.QApplication.UnicodeUTF8))
self.saveBtn.setText(QtGui.QApplication.translate("Form", "Save", None, QtGui.QApplication.UnicodeUTF8))
self.saveAsBtn.setText(QtGui.QApplication.translate("Form", "As..", None, QtGui.QApplication.UnicodeUTF8))
self.reloadBtn.setText(QtGui.QApplication.translate("Form", "Reload Libs", None, QtGui.QApplication.UnicodeUTF8))
self.showChartBtn.setText(QtGui.QApplication.translate("Form", "Flowchart", None, QtGui.QApplication.UnicodeUTF8))
from ..widgets.TreeWidget import TreeWidget
from ..widgets.FeedbackButton import FeedbackButton
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/flowchart/library/Filters.py | .py | 13,217 | 348 | # -*- coding: utf-8 -*-
import numpy as np
from ...Qt import QtCore, QtGui
from ..Node import Node
from . import functions
from ... import functions as pgfn
from .common import *
from ...python2_3 import xrange
from ... import PolyLineROI
from ... import Point
from ... import metaarray as metaarray
class Downsample(CtrlNode):
"""Downsample by averaging samples together."""
nodeName = 'Downsample'
uiTemplate = [
('n', 'intSpin', {'min': 1, 'max': 1000000})
]
def processData(self, data):
return functions.downsample(data, self.ctrls['n'].value(), axis=0)
class Subsample(CtrlNode):
"""Downsample by selecting every Nth sample."""
nodeName = 'Subsample'
uiTemplate = [
('n', 'intSpin', {'min': 1, 'max': 1000000})
]
def processData(self, data):
return data[::self.ctrls['n'].value()]
class Bessel(CtrlNode):
"""Bessel filter. Input data must have time values."""
nodeName = 'BesselFilter'
uiTemplate = [
('band', 'combo', {'values': ['lowpass', 'highpass'], 'index': 0}),
('cutoff', 'spin', {'value': 1000., 'step': 1, 'dec': True, 'bounds': [0.0, None], 'suffix': 'Hz', 'siPrefix': True}),
('order', 'intSpin', {'value': 4, 'min': 1, 'max': 16}),
('bidir', 'check', {'checked': True})
]
def processData(self, data):
s = self.stateGroup.state()
if s['band'] == 'lowpass':
mode = 'low'
else:
mode = 'high'
return functions.besselFilter(data, bidir=s['bidir'], btype=mode, cutoff=s['cutoff'], order=s['order'])
class Butterworth(CtrlNode):
"""Butterworth filter"""
nodeName = 'ButterworthFilter'
uiTemplate = [
('band', 'combo', {'values': ['lowpass', 'highpass'], 'index': 0}),
('wPass', 'spin', {'value': 1000., 'step': 1, 'dec': True, 'bounds': [0.0, None], 'suffix': 'Hz', 'siPrefix': True}),
('wStop', 'spin', {'value': 2000., 'step': 1, 'dec': True, 'bounds': [0.0, None], 'suffix': 'Hz', 'siPrefix': True}),
('gPass', 'spin', {'value': 2.0, 'step': 1, 'dec': True, 'bounds': [0.0, None], 'suffix': 'dB', 'siPrefix': True}),
('gStop', 'spin', {'value': 20.0, 'step': 1, 'dec': True, 'bounds': [0.0, None], 'suffix': 'dB', 'siPrefix': True}),
('bidir', 'check', {'checked': True})
]
def processData(self, data):
s = self.stateGroup.state()
if s['band'] == 'lowpass':
mode = 'low'
else:
mode = 'high'
ret = functions.butterworthFilter(data, bidir=s['bidir'], btype=mode, wPass=s['wPass'], wStop=s['wStop'], gPass=s['gPass'], gStop=s['gStop'])
return ret
class ButterworthNotch(CtrlNode):
"""Butterworth notch filter"""
nodeName = 'ButterworthNotchFilter'
uiTemplate = [
('low_wPass', 'spin', {'value': 1000., 'step': 1, 'dec': True, 'bounds': [0.0, None], 'suffix': 'Hz', 'siPrefix': True}),
('low_wStop', 'spin', {'value': 2000., 'step': 1, 'dec': True, 'bounds': [0.0, None], 'suffix': 'Hz', 'siPrefix': True}),
('low_gPass', 'spin', {'value': 2.0, 'step': 1, 'dec': True, 'bounds': [0.0, None], 'suffix': 'dB', 'siPrefix': True}),
('low_gStop', 'spin', {'value': 20.0, 'step': 1, 'dec': True, 'bounds': [0.0, None], 'suffix': 'dB', 'siPrefix': True}),
('high_wPass', 'spin', {'value': 3000., 'step': 1, 'dec': True, 'bounds': [0.0, None], 'suffix': 'Hz', 'siPrefix': True}),
('high_wStop', 'spin', {'value': 4000., 'step': 1, 'dec': True, 'bounds': [0.0, None], 'suffix': 'Hz', 'siPrefix': True}),
('high_gPass', 'spin', {'value': 2.0, 'step': 1, 'dec': True, 'bounds': [0.0, None], 'suffix': 'dB', 'siPrefix': True}),
('high_gStop', 'spin', {'value': 20.0, 'step': 1, 'dec': True, 'bounds': [0.0, None], 'suffix': 'dB', 'siPrefix': True}),
('bidir', 'check', {'checked': True})
]
def processData(self, data):
s = self.stateGroup.state()
low = functions.butterworthFilter(data, bidir=s['bidir'], btype='low', wPass=s['low_wPass'], wStop=s['low_wStop'], gPass=s['low_gPass'], gStop=s['low_gStop'])
high = functions.butterworthFilter(data, bidir=s['bidir'], btype='high', wPass=s['high_wPass'], wStop=s['high_wStop'], gPass=s['high_gPass'], gStop=s['high_gStop'])
return low + high
class Mean(CtrlNode):
"""Filters data by taking the mean of a sliding window"""
nodeName = 'MeanFilter'
uiTemplate = [
('n', 'intSpin', {'min': 1, 'max': 1000000})
]
@metaArrayWrapper
def processData(self, data):
n = self.ctrls['n'].value()
return functions.rollingSum(data, n) / n
class Median(CtrlNode):
"""Filters data by taking the median of a sliding window"""
nodeName = 'MedianFilter'
uiTemplate = [
('n', 'intSpin', {'min': 1, 'max': 1000000})
]
@metaArrayWrapper
def processData(self, data):
try:
import scipy.ndimage
except ImportError:
raise Exception("MedianFilter node requires the package scipy.ndimage.")
return scipy.ndimage.median_filter(data, self.ctrls['n'].value())
class Mode(CtrlNode):
"""Filters data by taking the mode (histogram-based) of a sliding window"""
nodeName = 'ModeFilter'
uiTemplate = [
('window', 'intSpin', {'value': 500, 'min': 1, 'max': 1000000}),
]
@metaArrayWrapper
def processData(self, data):
return functions.modeFilter(data, self.ctrls['window'].value())
class Denoise(CtrlNode):
"""Removes anomalous spikes from data, replacing with nearby values"""
nodeName = 'DenoiseFilter'
uiTemplate = [
('radius', 'intSpin', {'value': 2, 'min': 0, 'max': 1000000}),
('threshold', 'doubleSpin', {'value': 4.0, 'min': 0, 'max': 1000})
]
def processData(self, data):
#print "DENOISE"
s = self.stateGroup.state()
return functions.denoise(data, **s)
class Gaussian(CtrlNode):
"""Gaussian smoothing filter."""
nodeName = 'GaussianFilter'
uiTemplate = [
('sigma', 'doubleSpin', {'min': 0, 'max': 1000000})
]
@metaArrayWrapper
def processData(self, data):
sigma = self.ctrls['sigma'].value()
try:
import scipy.ndimage
return scipy.ndimage.gaussian_filter(data, sigma)
except ImportError:
return pgfn.gaussianFilter(data, sigma)
class Derivative(CtrlNode):
"""Returns the pointwise derivative of the input"""
nodeName = 'DerivativeFilter'
def processData(self, data):
if hasattr(data, 'implements') and data.implements('MetaArray'):
info = data.infoCopy()
if 'values' in info[0]:
info[0]['values'] = info[0]['values'][:-1]
return metaarray.MetaArray(data[1:] - data[:-1], info=info)
else:
return data[1:] - data[:-1]
class Integral(CtrlNode):
"""Returns the pointwise integral of the input"""
nodeName = 'IntegralFilter'
@metaArrayWrapper
def processData(self, data):
data[1:] += data[:-1]
return data
class Detrend(CtrlNode):
"""Removes linear trend from the data"""
nodeName = 'DetrendFilter'
@metaArrayWrapper
def processData(self, data):
try:
from scipy.signal import detrend
except ImportError:
raise Exception("DetrendFilter node requires the package scipy.signal.")
return detrend(data)
class RemoveBaseline(PlottingCtrlNode):
"""Remove an arbitrary, graphically defined baseline from the data."""
nodeName = 'RemoveBaseline'
def __init__(self, name):
## define inputs and outputs (one output needs to be a plot)
PlottingCtrlNode.__init__(self, name)
self.line = PolyLineROI([[0,0],[1,0]])
self.line.sigRegionChanged.connect(self.changed)
## create a PolyLineROI, add it to a plot -- actually, I think we want to do this after the node is connected to a plot (look at EventDetection.ThresholdEvents node for ideas), and possible after there is data. We will need to update the end positions of the line each time the input data changes
#self.line = None ## will become a PolyLineROI
def connectToPlot(self, node):
"""Define what happens when the node is connected to a plot"""
if node.plot is None:
return
node.getPlot().addItem(self.line)
def disconnectFromPlot(self, plot):
"""Define what happens when the node is disconnected from a plot"""
plot.removeItem(self.line)
def processData(self, data):
## get array of baseline (from PolyLineROI)
h0 = self.line.getHandles()[0]
h1 = self.line.getHandles()[-1]
timeVals = data.xvals(0)
h0.setPos(timeVals[0], h0.pos()[1])
h1.setPos(timeVals[-1], h1.pos()[1])
pts = self.line.listPoints() ## lists line handles in same coordinates as data
pts, indices = self.adjustXPositions(pts, timeVals) ## maxe sure x positions match x positions of data points
## construct an array that represents the baseline
arr = np.zeros(len(data), dtype=float)
n = 1
arr[0] = pts[0].y()
for i in range(len(pts)-1):
x1 = pts[i].x()
x2 = pts[i+1].x()
y1 = pts[i].y()
y2 = pts[i+1].y()
m = (y2-y1)/(x2-x1)
b = y1
times = timeVals[(timeVals > x1)*(timeVals <= x2)]
arr[n:n+len(times)] = (m*(times-times[0]))+b
n += len(times)
return data - arr ## subract baseline from data
def adjustXPositions(self, pts, data):
"""Return a list of Point() where the x position is set to the nearest x value in *data* for each point in *pts*."""
points = []
timeIndices = []
for p in pts:
x = np.argwhere(abs(data - p.x()) == abs(data - p.x()).min())
points.append(Point(data[x], p.y()))
timeIndices.append(x)
return points, timeIndices
class AdaptiveDetrend(CtrlNode):
"""Removes baseline from data, ignoring anomalous events"""
nodeName = 'AdaptiveDetrend'
uiTemplate = [
('threshold', 'doubleSpin', {'value': 3.0, 'min': 0, 'max': 1000000})
]
def processData(self, data):
return functions.adaptiveDetrend(data, threshold=self.ctrls['threshold'].value())
class HistogramDetrend(CtrlNode):
"""Removes baseline from data by computing mode (from histogram) of beginning and end of data."""
nodeName = 'HistogramDetrend'
uiTemplate = [
('windowSize', 'intSpin', {'value': 500, 'min': 10, 'max': 1000000, 'suffix': 'pts'}),
('numBins', 'intSpin', {'value': 50, 'min': 3, 'max': 1000000}),
('offsetOnly', 'check', {'checked': False}),
]
def processData(self, data):
s = self.stateGroup.state()
#ws = self.ctrls['windowSize'].value()
#bn = self.ctrls['numBins'].value()
#offset = self.ctrls['offsetOnly'].checked()
return functions.histogramDetrend(data, window=s['windowSize'], bins=s['numBins'], offsetOnly=s['offsetOnly'])
class RemovePeriodic(CtrlNode):
nodeName = 'RemovePeriodic'
uiTemplate = [
#('windowSize', 'intSpin', {'value': 500, 'min': 10, 'max': 1000000, 'suffix': 'pts'}),
#('numBins', 'intSpin', {'value': 50, 'min': 3, 'max': 1000000})
('f0', 'spin', {'value': 60, 'suffix': 'Hz', 'siPrefix': True, 'min': 0, 'max': None}),
('harmonics', 'intSpin', {'value': 30, 'min': 0}),
('samples', 'intSpin', {'value': 1, 'min': 1}),
]
def processData(self, data):
times = data.xvals('Time')
dt = times[1]-times[0]
data1 = data.asarray()
ft = np.fft.fft(data1)
## determine frequencies in fft data
df = 1.0 / (len(data1) * dt)
freqs = np.linspace(0.0, (len(ft)-1) * df, len(ft))
## flatten spikes at f0 and harmonics
f0 = self.ctrls['f0'].value()
for i in xrange(1, self.ctrls['harmonics'].value()+2):
f = f0 * i # target frequency
## determine index range to check for this frequency
ind1 = int(np.floor(f / df))
ind2 = int(np.ceil(f / df)) + (self.ctrls['samples'].value()-1)
if ind1 > len(ft)/2.:
break
mag = (abs(ft[ind1-1]) + abs(ft[ind2+1])) * 0.5
for j in range(ind1, ind2+1):
phase = np.angle(ft[j]) ## Must preserve the phase of each point, otherwise any transients in the trace might lead to large artifacts.
re = mag * np.cos(phase)
im = mag * np.sin(phase)
ft[j] = re + im*1j
ft[len(ft)-j] = re - im*1j
data2 = np.fft.ifft(ft).real
ma = metaarray.MetaArray(data2, info=data.infoCopy())
return ma
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/flowchart/library/Data.py | .py | 15,904 | 476 | # -*- coding: utf-8 -*-
from ..Node import Node
from ...Qt import QtGui, QtCore
import numpy as np
from .common import *
from ...SRTTransform import SRTTransform
from ...Point import Point
from ...widgets.TreeWidget import TreeWidget
from ...graphicsItems.LinearRegionItem import LinearRegionItem
from . import functions
class ColumnSelectNode(Node):
"""Select named columns from a record array or MetaArray."""
nodeName = "ColumnSelect"
def __init__(self, name):
Node.__init__(self, name, terminals={'In': {'io': 'in'}})
self.columns = set()
self.columnList = QtGui.QListWidget()
self.axis = 0
self.columnList.itemChanged.connect(self.itemChanged)
def process(self, In, display=True):
if display:
self.updateList(In)
out = {}
if hasattr(In, 'implements') and In.implements('MetaArray'):
for c in self.columns:
out[c] = In[self.axis:c]
elif isinstance(In, np.ndarray) and In.dtype.fields is not None:
for c in self.columns:
out[c] = In[c]
else:
self.In.setValueAcceptable(False)
raise Exception("Input must be MetaArray or ndarray with named fields")
return out
def ctrlWidget(self):
return self.columnList
def updateList(self, data):
if hasattr(data, 'implements') and data.implements('MetaArray'):
cols = data.listColumns()
for ax in cols: ## find first axis with columns
if len(cols[ax]) > 0:
self.axis = ax
cols = set(cols[ax])
break
else:
cols = list(data.dtype.fields.keys())
rem = set()
for c in self.columns:
if c not in cols:
self.removeTerminal(c)
rem.add(c)
self.columns -= rem
self.columnList.blockSignals(True)
self.columnList.clear()
for c in cols:
item = QtGui.QListWidgetItem(c)
item.setFlags(QtCore.Qt.ItemIsEnabled|QtCore.Qt.ItemIsUserCheckable)
if c in self.columns:
item.setCheckState(QtCore.Qt.Checked)
else:
item.setCheckState(QtCore.Qt.Unchecked)
self.columnList.addItem(item)
self.columnList.blockSignals(False)
def itemChanged(self, item):
col = str(item.text())
if item.checkState() == QtCore.Qt.Checked:
if col not in self.columns:
self.columns.add(col)
self.addOutput(col)
else:
if col in self.columns:
self.columns.remove(col)
self.removeTerminal(col)
self.update()
def saveState(self):
state = Node.saveState(self)
state['columns'] = list(self.columns)
return state
def restoreState(self, state):
Node.restoreState(self, state)
self.columns = set(state.get('columns', []))
for c in self.columns:
self.addOutput(c)
class RegionSelectNode(CtrlNode):
"""Returns a slice from a 1-D array. Connect the 'widget' output to a plot to display a region-selection widget."""
nodeName = "RegionSelect"
uiTemplate = [
('start', 'spin', {'value': 0, 'step': 0.1}),
('stop', 'spin', {'value': 0.1, 'step': 0.1}),
('display', 'check', {'value': True}),
('movable', 'check', {'value': True}),
]
def __init__(self, name):
self.items = {}
CtrlNode.__init__(self, name, terminals={
'data': {'io': 'in'},
'selected': {'io': 'out'},
'region': {'io': 'out'},
'widget': {'io': 'out', 'multi': True}
})
self.ctrls['display'].toggled.connect(self.displayToggled)
self.ctrls['movable'].toggled.connect(self.movableToggled)
def displayToggled(self, b):
for item in self.items.values():
item.setVisible(b)
def movableToggled(self, b):
for item in self.items.values():
item.setMovable(b)
def process(self, data=None, display=True):
#print "process.."
s = self.stateGroup.state()
region = [s['start'], s['stop']]
if display:
conn = self['widget'].connections()
for c in conn:
plot = c.node().getPlot()
if plot is None:
continue
if c in self.items:
item = self.items[c]
item.setRegion(region)
#print " set rgn:", c, region
#item.setXVals(events)
else:
item = LinearRegionItem(values=region)
self.items[c] = item
#item.connect(item, QtCore.SIGNAL('regionChanged'), self.rgnChanged)
item.sigRegionChanged.connect(self.rgnChanged)
item.setVisible(s['display'])
item.setMovable(s['movable'])
#print " new rgn:", c, region
#self.items[c].setYRange([0., 0.2], relative=True)
if self['selected'].isConnected():
if data is None:
sliced = None
elif (hasattr(data, 'implements') and data.implements('MetaArray')):
sliced = data[0:s['start']:s['stop']]
else:
mask = (data['time'] >= s['start']) * (data['time'] < s['stop'])
sliced = data[mask]
else:
sliced = None
return {'selected': sliced, 'widget': self.items, 'region': region}
def rgnChanged(self, item):
region = item.getRegion()
self.stateGroup.setState({'start': region[0], 'stop': region[1]})
self.update()
class EvalNode(Node):
"""Return the output of a string evaluated/executed by the python interpreter.
The string may be either an expression or a python script, and inputs are accessed as the name of the terminal.
For expressions, a single value may be evaluated for a single output, or a dict for multiple outputs.
For a script, the text will be executed as the body of a function."""
nodeName = 'PythonEval'
def __init__(self, name):
Node.__init__(self, name,
terminals = {
'input': {'io': 'in', 'renamable': True, 'multiable': True},
'output': {'io': 'out', 'renamable': True, 'multiable': True},
},
allowAddInput=True, allowAddOutput=True)
self.ui = QtGui.QWidget()
self.layout = QtGui.QGridLayout()
self.text = QtGui.QTextEdit()
self.text.setTabStopWidth(30)
self.text.setPlainText("# Access inputs as args['input_name']\nreturn {'output': None} ## one key per output terminal")
self.layout.addWidget(self.text, 1, 0, 1, 2)
self.ui.setLayout(self.layout)
self.text.focusOutEvent = self.focusOutEvent
self.lastText = None
def ctrlWidget(self):
return self.ui
def setCode(self, code):
# unindent code; this allows nicer inline code specification when
# calling this method.
ind = []
lines = code.split('\n')
for line in lines:
stripped = line.lstrip()
if len(stripped) > 0:
ind.append(len(line) - len(stripped))
if len(ind) > 0:
ind = min(ind)
code = '\n'.join([line[ind:] for line in lines])
self.text.clear()
self.text.insertPlainText(code)
def code(self):
return self.text.toPlainText()
def focusOutEvent(self, ev):
text = str(self.text.toPlainText())
if text != self.lastText:
self.lastText = text
self.update()
return QtGui.QTextEdit.focusOutEvent(self.text, ev)
def process(self, display=True, **args):
l = locals()
l.update(args)
## try eval first, then exec
try:
text = str(self.text.toPlainText()).replace('\n', ' ')
output = eval(text, globals(), l)
except SyntaxError:
fn = "def fn(**args):\n"
run = "\noutput=fn(**args)\n"
text = fn + "\n".join([" "+l for l in str(self.text.toPlainText()).split('\n')]) + run
exec(text)
except:
print("Error processing node: %s" % self.name())
raise
return output
def saveState(self):
state = Node.saveState(self)
state['text'] = str(self.text.toPlainText())
#state['terminals'] = self.saveTerminals()
return state
def restoreState(self, state):
Node.restoreState(self, state)
self.setCode(state['text'])
self.restoreTerminals(state['terminals'])
self.update()
class ColumnJoinNode(Node):
"""Concatenates record arrays and/or adds new columns"""
nodeName = 'ColumnJoin'
def __init__(self, name):
Node.__init__(self, name, terminals = {
'output': {'io': 'out'},
})
#self.items = []
self.ui = QtGui.QWidget()
self.layout = QtGui.QGridLayout()
self.ui.setLayout(self.layout)
self.tree = TreeWidget()
self.addInBtn = QtGui.QPushButton('+ Input')
self.remInBtn = QtGui.QPushButton('- Input')
self.layout.addWidget(self.tree, 0, 0, 1, 2)
self.layout.addWidget(self.addInBtn, 1, 0)
self.layout.addWidget(self.remInBtn, 1, 1)
self.addInBtn.clicked.connect(self.addInput)
self.remInBtn.clicked.connect(self.remInput)
self.tree.sigItemMoved.connect(self.update)
def ctrlWidget(self):
return self.ui
def addInput(self):
#print "ColumnJoinNode.addInput called."
term = Node.addInput(self, 'input', renamable=True, removable=True, multiable=True)
#print "Node.addInput returned. term:", term
item = QtGui.QTreeWidgetItem([term.name()])
item.term = term
term.joinItem = item
#self.items.append((term, item))
self.tree.addTopLevelItem(item)
def remInput(self):
sel = self.tree.currentItem()
term = sel.term
term.joinItem = None
sel.term = None
self.tree.removeTopLevelItem(sel)
self.removeTerminal(term)
self.update()
def process(self, display=True, **args):
order = self.order()
vals = []
for name in order:
if name not in args:
continue
val = args[name]
if isinstance(val, np.ndarray) and len(val.dtype) > 0:
vals.append(val)
else:
vals.append((name, None, val))
return {'output': functions.concatenateColumns(vals)}
def order(self):
return [str(self.tree.topLevelItem(i).text(0)) for i in range(self.tree.topLevelItemCount())]
def saveState(self):
state = Node.saveState(self)
state['order'] = self.order()
return state
def restoreState(self, state):
Node.restoreState(self, state)
inputs = self.inputs()
## Node.restoreState should have created all of the terminals we need
## However: to maintain support for some older flowchart files, we need
## to manually add any terminals that were not taken care of.
for name in [n for n in state['order'] if n not in inputs]:
Node.addInput(self, name, renamable=True, removable=True, multiable=True)
inputs = self.inputs()
order = [name for name in state['order'] if name in inputs]
for name in inputs:
if name not in order:
order.append(name)
self.tree.clear()
for name in order:
term = self[name]
item = QtGui.QTreeWidgetItem([name])
item.term = term
term.joinItem = item
#self.items.append((term, item))
self.tree.addTopLevelItem(item)
def terminalRenamed(self, term, oldName):
Node.terminalRenamed(self, term, oldName)
item = term.joinItem
item.setText(0, term.name())
self.update()
class Mean(CtrlNode):
"""Calculate the mean of an array across an axis.
"""
nodeName = 'Mean'
uiTemplate = [
('axis', 'intSpin', {'value': 0, 'min': -1, 'max': 1000000}),
]
def processData(self, data):
s = self.stateGroup.state()
ax = None if s['axis'] == -1 else s['axis']
return data.mean(axis=ax)
class Max(CtrlNode):
"""Calculate the maximum of an array across an axis.
"""
nodeName = 'Max'
uiTemplate = [
('axis', 'intSpin', {'value': 0, 'min': -1, 'max': 1000000}),
]
def processData(self, data):
s = self.stateGroup.state()
ax = None if s['axis'] == -1 else s['axis']
return data.max(axis=ax)
class Min(CtrlNode):
"""Calculate the minimum of an array across an axis.
"""
nodeName = 'Min'
uiTemplate = [
('axis', 'intSpin', {'value': 0, 'min': -1, 'max': 1000000}),
]
def processData(self, data):
s = self.stateGroup.state()
ax = None if s['axis'] == -1 else s['axis']
return data.min(axis=ax)
class Stdev(CtrlNode):
"""Calculate the standard deviation of an array across an axis.
"""
nodeName = 'Stdev'
uiTemplate = [
('axis', 'intSpin', {'value': -0, 'min': -1, 'max': 1000000}),
]
def processData(self, data):
s = self.stateGroup.state()
ax = None if s['axis'] == -1 else s['axis']
return data.std(axis=ax)
class Index(CtrlNode):
"""Select an index from an array axis.
"""
nodeName = 'Index'
uiTemplate = [
('axis', 'intSpin', {'value': 0, 'min': 0, 'max': 1000000}),
('index', 'intSpin', {'value': 0, 'min': 0, 'max': 1000000}),
]
def processData(self, data):
s = self.stateGroup.state()
ax = s['axis']
ind = s['index']
if ax == 0:
# allow support for non-ndarray sequence types
return data[ind]
else:
return data.take(ind, axis=ax)
class Slice(CtrlNode):
"""Select a slice from an array axis.
"""
nodeName = 'Slice'
uiTemplate = [
('axis', 'intSpin', {'value': 0, 'min': 0, 'max': 1e6}),
('start', 'intSpin', {'value': 0, 'min': -1e6, 'max': 1e6}),
('stop', 'intSpin', {'value': -1, 'min': -1e6, 'max': 1e6}),
('step', 'intSpin', {'value': 1, 'min': -1e6, 'max': 1e6}),
]
def processData(self, data):
s = self.stateGroup.state()
ax = s['axis']
start = s['start']
stop = s['stop']
step = s['step']
if ax == 0:
# allow support for non-ndarray sequence types
return data[start:stop:step]
else:
sl = [slice(None) for i in range(data.ndim)]
sl[ax] = slice(start, stop, step)
return data[sl]
class AsType(CtrlNode):
"""Convert an array to a different dtype.
"""
nodeName = 'AsType'
uiTemplate = [
('dtype', 'combo', {'values': ['float', 'int', 'float32', 'float64', 'float128', 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64'], 'index': 0}),
]
def processData(self, data):
s = self.stateGroup.state()
return data.astype(s['dtype'])
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/flowchart/library/Display.py | .py | 10,343 | 313 | # -*- coding: utf-8 -*-
from ..Node import Node
import weakref
from ...Qt import QtCore, QtGui
from ...graphicsItems.ScatterPlotItem import ScatterPlotItem
from ...graphicsItems.PlotCurveItem import PlotCurveItem
from ... import PlotDataItem, ComboBox
from .common import *
import numpy as np
class PlotWidgetNode(Node):
"""Connection to PlotWidget. Will plot arrays, metaarrays, and display event lists."""
nodeName = 'PlotWidget'
sigPlotChanged = QtCore.Signal(object)
def __init__(self, name):
Node.__init__(self, name, terminals={'In': {'io': 'in', 'multi': True}})
self.plot = None # currently selected plot
self.plots = {} # list of available plots user may select from
self.ui = None
self.items = {}
def disconnected(self, localTerm, remoteTerm):
if localTerm is self['In'] and remoteTerm in self.items:
self.plot.removeItem(self.items[remoteTerm])
del self.items[remoteTerm]
def setPlot(self, plot):
#print "======set plot"
if plot == self.plot:
return
# clear data from previous plot
if self.plot is not None:
for vid in list(self.items.keys()):
self.plot.removeItem(self.items[vid])
del self.items[vid]
self.plot = plot
self.updateUi()
self.update()
self.sigPlotChanged.emit(self)
def getPlot(self):
return self.plot
def process(self, In, display=True):
if display and self.plot is not None:
items = set()
# Add all new input items to selected plot
for name, vals in In.items():
if vals is None:
continue
if type(vals) is not list:
vals = [vals]
for val in vals:
vid = id(val)
if vid in self.items and self.items[vid].scene() is self.plot.scene():
# Item is already added to the correct scene
# possible bug: what if two plots occupy the same scene? (should
# rarely be a problem because items are removed from a plot before
# switching).
items.add(vid)
else:
# Add the item to the plot, or generate a new item if needed.
if isinstance(val, QtGui.QGraphicsItem):
self.plot.addItem(val)
item = val
else:
item = self.plot.plot(val)
self.items[vid] = item
items.add(vid)
# Any left-over items that did not appear in the input must be removed
for vid in list(self.items.keys()):
if vid not in items:
self.plot.removeItem(self.items[vid])
del self.items[vid]
def processBypassed(self, args):
if self.plot is None:
return
for item in list(self.items.values()):
self.plot.removeItem(item)
self.items = {}
def ctrlWidget(self):
if self.ui is None:
self.ui = ComboBox()
self.ui.currentIndexChanged.connect(self.plotSelected)
self.updateUi()
return self.ui
def plotSelected(self, index):
self.setPlot(self.ui.value())
def setPlotList(self, plots):
"""
Specify the set of plots (PlotWidget or PlotItem) that the user may
select from.
*plots* must be a dictionary of {name: plot} pairs.
"""
self.plots = plots
self.updateUi()
def updateUi(self):
# sets list and automatically preserves previous selection
self.ui.setItems(self.plots)
try:
self.ui.setValue(self.plot)
except ValueError:
pass
class CanvasNode(Node):
"""Connection to a Canvas widget."""
nodeName = 'CanvasWidget'
def __init__(self, name):
Node.__init__(self, name, terminals={'In': {'io': 'in', 'multi': True}})
self.canvas = None
self.items = {}
def disconnected(self, localTerm, remoteTerm):
if localTerm is self.In and remoteTerm in self.items:
self.canvas.removeItem(self.items[remoteTerm])
del self.items[remoteTerm]
def setCanvas(self, canvas):
self.canvas = canvas
def getCanvas(self):
return self.canvas
def process(self, In, display=True):
if display:
items = set()
for name, vals in In.items():
if vals is None:
continue
if type(vals) is not list:
vals = [vals]
for val in vals:
vid = id(val)
if vid in self.items:
items.add(vid)
else:
self.canvas.addItem(val)
item = val
self.items[vid] = item
items.add(vid)
for vid in list(self.items.keys()):
if vid not in items:
#print "remove", self.items[vid]
self.canvas.removeItem(self.items[vid])
del self.items[vid]
class PlotCurve(CtrlNode):
"""Generates a plot curve from x/y data"""
nodeName = 'PlotCurve'
uiTemplate = [
('color', 'color'),
]
def __init__(self, name):
CtrlNode.__init__(self, name, terminals={
'x': {'io': 'in'},
'y': {'io': 'in'},
'plot': {'io': 'out'}
})
self.item = PlotDataItem()
def process(self, x, y, display=True):
#print "scatterplot process"
if not display:
return {'plot': None}
self.item.setData(x, y, pen=self.ctrls['color'].color())
return {'plot': self.item}
class ScatterPlot(CtrlNode):
"""Generates a scatter plot from a record array or nested dicts"""
nodeName = 'ScatterPlot'
uiTemplate = [
('x', 'combo', {'values': [], 'index': 0}),
('y', 'combo', {'values': [], 'index': 0}),
('sizeEnabled', 'check', {'value': False}),
('size', 'combo', {'values': [], 'index': 0}),
('absoluteSize', 'check', {'value': False}),
('colorEnabled', 'check', {'value': False}),
('color', 'colormap', {}),
('borderEnabled', 'check', {'value': False}),
('border', 'colormap', {}),
]
def __init__(self, name):
CtrlNode.__init__(self, name, terminals={
'input': {'io': 'in'},
'plot': {'io': 'out'}
})
self.item = ScatterPlotItem()
self.keys = []
#self.ui = QtGui.QWidget()
#self.layout = QtGui.QGridLayout()
#self.ui.setLayout(self.layout)
#self.xCombo = QtGui.QComboBox()
#self.yCombo = QtGui.QComboBox()
def process(self, input, display=True):
#print "scatterplot process"
if not display:
return {'plot': None}
self.updateKeys(input[0])
x = str(self.ctrls['x'].currentText())
y = str(self.ctrls['y'].currentText())
size = str(self.ctrls['size'].currentText())
pen = QtGui.QPen(QtGui.QColor(0,0,0,0))
points = []
for i in input:
pt = {'pos': (i[x], i[y])}
if self.ctrls['sizeEnabled'].isChecked():
pt['size'] = i[size]
if self.ctrls['borderEnabled'].isChecked():
pt['pen'] = QtGui.QPen(self.ctrls['border'].getColor(i))
else:
pt['pen'] = pen
if self.ctrls['colorEnabled'].isChecked():
pt['brush'] = QtGui.QBrush(self.ctrls['color'].getColor(i))
points.append(pt)
self.item.setPxMode(not self.ctrls['absoluteSize'].isChecked())
self.item.setPoints(points)
return {'plot': self.item}
def updateKeys(self, data):
if isinstance(data, dict):
keys = list(data.keys())
elif isinstance(data, list) or isinstance(data, tuple):
keys = data
elif isinstance(data, np.ndarray) or isinstance(data, np.void):
keys = data.dtype.names
else:
print("Unknown data type:", type(data), data)
return
for c in self.ctrls.values():
c.blockSignals(True)
for c in [self.ctrls['x'], self.ctrls['y'], self.ctrls['size']]:
cur = str(c.currentText())
c.clear()
for k in keys:
c.addItem(k)
if k == cur:
c.setCurrentIndex(c.count()-1)
for c in [self.ctrls['color'], self.ctrls['border']]:
c.setArgList(keys)
for c in self.ctrls.values():
c.blockSignals(False)
self.keys = keys
def saveState(self):
state = CtrlNode.saveState(self)
return {'keys': self.keys, 'ctrls': state}
def restoreState(self, state):
self.updateKeys(state['keys'])
CtrlNode.restoreState(self, state['ctrls'])
#class ImageItem(Node):
#"""Creates an ImageItem for display in a canvas from a file handle."""
#nodeName = 'Image'
#def __init__(self, name):
#Node.__init__(self, name, terminals={
#'file': {'io': 'in'},
#'image': {'io': 'out'}
#})
#self.imageItem = graphicsItems.ImageItem()
#self.handle = None
#def process(self, file, display=True):
#if not display:
#return {'image': None}
#if file != self.handle:
#self.handle = file
#data = file.read()
#self.imageItem.updateImage(data)
#pos = file.
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/flowchart/library/common.py | .py | 5,982 | 192 | # -*- coding: utf-8 -*-
from ...Qt import QtCore, QtGui
from ...widgets.SpinBox import SpinBox
#from ...SignalProxy import SignalProxy
from ...WidgetGroup import WidgetGroup
#from ColorMapper import ColorMapper
from ..Node import Node
import numpy as np
from ...widgets.ColorButton import ColorButton
try:
import metaarray
HAVE_METAARRAY = True
except:
HAVE_METAARRAY = False
def generateUi(opts):
"""Convenience function for generating common UI types"""
widget = QtGui.QWidget()
l = QtGui.QFormLayout()
l.setSpacing(0)
widget.setLayout(l)
ctrls = {}
row = 0
for opt in opts:
if len(opt) == 2:
k, t = opt
o = {}
elif len(opt) == 3:
k, t, o = opt
else:
raise Exception("Widget specification must be (name, type) or (name, type, {opts})")
## clean out these options so they don't get sent to SpinBox
hidden = o.pop('hidden', False)
tip = o.pop('tip', None)
if t == 'intSpin':
w = QtGui.QSpinBox()
if 'max' in o:
w.setMaximum(o['max'])
if 'min' in o:
w.setMinimum(o['min'])
if 'value' in o:
w.setValue(o['value'])
elif t == 'doubleSpin':
w = QtGui.QDoubleSpinBox()
if 'max' in o:
w.setMaximum(o['max'])
if 'min' in o:
w.setMinimum(o['min'])
if 'value' in o:
w.setValue(o['value'])
elif t == 'spin':
w = SpinBox()
w.setOpts(**o)
elif t == 'check':
w = QtGui.QCheckBox()
if 'checked' in o:
w.setChecked(o['checked'])
elif t == 'combo':
w = QtGui.QComboBox()
for i in o['values']:
w.addItem(i)
#elif t == 'colormap':
#w = ColorMapper()
elif t == 'color':
w = ColorButton()
else:
raise Exception("Unknown widget type '%s'" % str(t))
if tip is not None:
w.setToolTip(tip)
w.setObjectName(k)
l.addRow(k, w)
if hidden:
w.hide()
label = l.labelForField(w)
label.hide()
ctrls[k] = w
w.rowNum = row
row += 1
group = WidgetGroup(widget)
return widget, group, ctrls
class CtrlNode(Node):
"""Abstract class for nodes with auto-generated control UI"""
sigStateChanged = QtCore.Signal(object)
def __init__(self, name, ui=None, terminals=None):
if terminals is None:
terminals = {'In': {'io': 'in'}, 'Out': {'io': 'out', 'bypass': 'In'}}
Node.__init__(self, name=name, terminals=terminals)
if ui is None:
if hasattr(self, 'uiTemplate'):
ui = self.uiTemplate
else:
ui = []
self.ui, self.stateGroup, self.ctrls = generateUi(ui)
self.stateGroup.sigChanged.connect(self.changed)
def ctrlWidget(self):
return self.ui
def changed(self):
self.update()
self.sigStateChanged.emit(self)
def process(self, In, display=True):
out = self.processData(In)
return {'Out': out}
def saveState(self):
state = Node.saveState(self)
state['ctrl'] = self.stateGroup.state()
return state
def restoreState(self, state):
Node.restoreState(self, state)
if self.stateGroup is not None:
self.stateGroup.setState(state.get('ctrl', {}))
def hideRow(self, name):
w = self.ctrls[name]
l = self.ui.layout().labelForField(w)
w.hide()
l.hide()
def showRow(self, name):
w = self.ctrls[name]
l = self.ui.layout().labelForField(w)
w.show()
l.show()
class PlottingCtrlNode(CtrlNode):
"""Abstract class for CtrlNodes that can connect to plots."""
def __init__(self, name, ui=None, terminals=None):
#print "PlottingCtrlNode.__init__ called."
CtrlNode.__init__(self, name, ui=ui, terminals=terminals)
self.plotTerminal = self.addOutput('plot', optional=True)
def connected(self, term, remote):
CtrlNode.connected(self, term, remote)
if term is not self.plotTerminal:
return
node = remote.node()
node.sigPlotChanged.connect(self.connectToPlot)
self.connectToPlot(node)
def disconnected(self, term, remote):
CtrlNode.disconnected(self, term, remote)
if term is not self.plotTerminal:
return
remote.node().sigPlotChanged.disconnect(self.connectToPlot)
self.disconnectFromPlot(remote.node().getPlot())
def connectToPlot(self, node):
"""Define what happens when the node is connected to a plot"""
raise Exception("Must be re-implemented in subclass")
def disconnectFromPlot(self, plot):
"""Define what happens when the node is disconnected from a plot"""
raise Exception("Must be re-implemented in subclass")
def process(self, In, display=True):
out = CtrlNode.process(self, In, display)
out['plot'] = None
return out
def metaArrayWrapper(fn):
def newFn(self, data, *args, **kargs):
if HAVE_METAARRAY and (hasattr(data, 'implements') and data.implements('MetaArray')):
d1 = fn(self, data.view(np.ndarray), *args, **kargs)
info = data.infoCopy()
if d1.shape != data.shape:
for i in range(data.ndim):
if 'values' in info[i]:
info[i]['values'] = info[i]['values'][:d1.shape[i]]
return metaarray.MetaArray(d1, info=info)
else:
return fn(self, data, *args, **kargs)
return newFn
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/flowchart/library/__init__.py | .py | 812 | 29 | # -*- coding: utf-8 -*-
from ...pgcollections import OrderedDict
import os, types
from ...debug import printExc
from ..NodeLibrary import NodeLibrary, isNodeClass
from ... import reload as reload
# Build default library
LIBRARY = NodeLibrary()
# For backward compatibility, expose the default library's properties here:
NODE_LIST = LIBRARY.nodeList
NODE_TREE = LIBRARY.nodeTree
registerNodeType = LIBRARY.addNodeType
getNodeTree = LIBRARY.getNodeTree
getNodeType = LIBRARY.getNodeType
# Add all nodes to the default library
from . import Data, Display, Filters, Operators
for mod in [Data, Display, Filters, Operators]:
nodes = [getattr(mod, name) for name in dir(mod) if isNodeClass(getattr(mod, name))]
for node in nodes:
LIBRARY.addNodeType(node, [(mod.__name__.split('.')[-1],)])
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/flowchart/library/functions.py | .py | 11,766 | 357 | import numpy as np
from ...metaarray import MetaArray
from ...python2_3 import basestring, xrange
def downsample(data, n, axis=0, xvals='subsample'):
"""Downsample by averaging points together across axis.
If multiple axes are specified, runs once per axis.
If a metaArray is given, then the axis values can be either subsampled
or downsampled to match.
"""
ma = None
if (hasattr(data, 'implements') and data.implements('MetaArray')):
ma = data
data = data.view(np.ndarray)
if hasattr(axis, '__len__'):
if not hasattr(n, '__len__'):
n = [n]*len(axis)
for i in range(len(axis)):
data = downsample(data, n[i], axis[i])
return data
nPts = int(data.shape[axis] / n)
s = list(data.shape)
s[axis] = nPts
s.insert(axis+1, n)
sl = [slice(None)] * data.ndim
sl[axis] = slice(0, nPts*n)
d1 = data[tuple(sl)]
#print d1.shape, s
d1.shape = tuple(s)
d2 = d1.mean(axis+1)
if ma is None:
return d2
else:
info = ma.infoCopy()
if 'values' in info[axis]:
if xvals == 'subsample':
info[axis]['values'] = info[axis]['values'][::n][:nPts]
elif xvals == 'downsample':
info[axis]['values'] = downsample(info[axis]['values'], n)
return MetaArray(d2, info=info)
def applyFilter(data, b, a, padding=100, bidir=True):
"""Apply a linear filter with coefficients a, b. Optionally pad the data before filtering
and/or run the filter in both directions."""
try:
import scipy.signal
except ImportError:
raise Exception("applyFilter() requires the package scipy.signal.")
d1 = data.view(np.ndarray)
if padding > 0:
d1 = np.hstack([d1[:padding], d1, d1[-padding:]])
if bidir:
d1 = scipy.signal.lfilter(b, a, scipy.signal.lfilter(b, a, d1)[::-1])[::-1]
else:
d1 = scipy.signal.lfilter(b, a, d1)
if padding > 0:
d1 = d1[padding:-padding]
if (hasattr(data, 'implements') and data.implements('MetaArray')):
return MetaArray(d1, info=data.infoCopy())
else:
return d1
def besselFilter(data, cutoff, order=1, dt=None, btype='low', bidir=True):
"""return data passed through bessel filter"""
try:
import scipy.signal
except ImportError:
raise Exception("besselFilter() requires the package scipy.signal.")
if dt is None:
try:
tvals = data.xvals('Time')
dt = (tvals[-1]-tvals[0]) / (len(tvals)-1)
except:
dt = 1.0
b,a = scipy.signal.bessel(order, cutoff * dt, btype=btype)
return applyFilter(data, b, a, bidir=bidir)
#base = data.mean()
#d1 = scipy.signal.lfilter(b, a, data.view(ndarray)-base) + base
#if (hasattr(data, 'implements') and data.implements('MetaArray')):
#return MetaArray(d1, info=data.infoCopy())
#return d1
def butterworthFilter(data, wPass, wStop=None, gPass=2.0, gStop=20.0, order=1, dt=None, btype='low', bidir=True):
"""return data passed through bessel filter"""
try:
import scipy.signal
except ImportError:
raise Exception("butterworthFilter() requires the package scipy.signal.")
if dt is None:
try:
tvals = data.xvals('Time')
dt = (tvals[-1]-tvals[0]) / (len(tvals)-1)
except:
dt = 1.0
if wStop is None:
wStop = wPass * 2.0
ord, Wn = scipy.signal.buttord(wPass*dt*2., wStop*dt*2., gPass, gStop)
#print "butterworth ord %f Wn %f c %f sc %f" % (ord, Wn, cutoff, stopCutoff)
b,a = scipy.signal.butter(ord, Wn, btype=btype)
return applyFilter(data, b, a, bidir=bidir)
def rollingSum(data, n):
d1 = data.copy()
d1[1:] += d1[:-1] # integrate
d2 = np.empty(len(d1) - n + 1, dtype=data.dtype)
d2[0] = d1[n-1] # copy first point
d2[1:] = d1[n:] - d1[:-n] # subtract
return d2
def mode(data, bins=None):
"""Returns location max value from histogram."""
if bins is None:
bins = int(len(data)/10.)
if bins < 2:
bins = 2
y, x = np.histogram(data, bins=bins)
ind = np.argmax(y)
mode = 0.5 * (x[ind] + x[ind+1])
return mode
def modeFilter(data, window=500, step=None, bins=None):
"""Filter based on histogram-based mode function"""
d1 = data.view(np.ndarray)
vals = []
l2 = int(window/2.)
if step is None:
step = l2
i = 0
while True:
if i > len(data)-step:
break
vals.append(mode(d1[i:i+window], bins))
i += step
chunks = [np.linspace(vals[0], vals[0], l2)]
for i in range(len(vals)-1):
chunks.append(np.linspace(vals[i], vals[i+1], step))
remain = len(data) - step*(len(vals)-1) - l2
chunks.append(np.linspace(vals[-1], vals[-1], remain))
d2 = np.hstack(chunks)
if (hasattr(data, 'implements') and data.implements('MetaArray')):
return MetaArray(d2, info=data.infoCopy())
return d2
def denoise(data, radius=2, threshold=4):
"""Very simple noise removal function. Compares a point to surrounding points,
replaces with nearby values if the difference is too large."""
r2 = radius * 2
d1 = data.view(np.ndarray)
d2 = d1[radius:] - d1[:-radius] #a derivative
#d3 = data[r2:] - data[:-r2]
#d4 = d2 - d3
stdev = d2.std()
#print "denoise: stdev of derivative:", stdev
mask1 = d2 > stdev*threshold #where derivative is large and positive
mask2 = d2 < -stdev*threshold #where derivative is large and negative
maskpos = mask1[:-radius] * mask2[radius:] #both need to be true
maskneg = mask1[radius:] * mask2[:-radius]
mask = maskpos + maskneg
d5 = np.where(mask, d1[:-r2], d1[radius:-radius]) #where both are true replace the value with the value from 2 points before
d6 = np.empty(d1.shape, dtype=d1.dtype) #add points back to the ends
d6[radius:-radius] = d5
d6[:radius] = d1[:radius]
d6[-radius:] = d1[-radius:]
if (hasattr(data, 'implements') and data.implements('MetaArray')):
return MetaArray(d6, info=data.infoCopy())
return d6
def adaptiveDetrend(data, x=None, threshold=3.0):
"""Return the signal with baseline removed. Discards outliers from baseline measurement."""
try:
import scipy.signal
except ImportError:
raise Exception("adaptiveDetrend() requires the package scipy.signal.")
if x is None:
x = data.xvals(0)
d = data.view(np.ndarray)
d2 = scipy.signal.detrend(d)
stdev = d2.std()
mask = abs(d2) < stdev*threshold
#d3 = where(mask, 0, d2)
#d4 = d2 - lowPass(d3, cutoffs[1], dt=dt)
lr = scipy.stats.linregress(x[mask], d[mask])
base = lr[1] + lr[0]*x
d4 = d - base
if (hasattr(data, 'implements') and data.implements('MetaArray')):
return MetaArray(d4, info=data.infoCopy())
return d4
def histogramDetrend(data, window=500, bins=50, threshold=3.0, offsetOnly=False):
"""Linear detrend. Works by finding the most common value at the beginning and end of a trace, excluding outliers.
If offsetOnly is True, then only the offset from the beginning of the trace is subtracted.
"""
d1 = data.view(np.ndarray)
d2 = [d1[:window], d1[-window:]]
v = [0, 0]
for i in [0, 1]:
d3 = d2[i]
stdev = d3.std()
mask = abs(d3-np.median(d3)) < stdev*threshold
d4 = d3[mask]
y, x = np.histogram(d4, bins=bins)
ind = np.argmax(y)
v[i] = 0.5 * (x[ind] + x[ind+1])
if offsetOnly:
d3 = data.view(np.ndarray) - v[0]
else:
base = np.linspace(v[0], v[1], len(data))
d3 = data.view(np.ndarray) - base
if (hasattr(data, 'implements') and data.implements('MetaArray')):
return MetaArray(d3, info=data.infoCopy())
return d3
def concatenateColumns(data):
"""Returns a single record array with columns taken from the elements in data.
data should be a list of elements, which can be either record arrays or tuples (name, type, data)
"""
## first determine dtype
dtype = []
names = set()
maxLen = 0
for element in data:
if isinstance(element, np.ndarray):
## use existing columns
for i in range(len(element.dtype)):
name = element.dtype.names[i]
dtype.append((name, element.dtype[i]))
maxLen = max(maxLen, len(element))
else:
name, type, d = element
if type is None:
type = suggestDType(d)
dtype.append((name, type))
if isinstance(d, list) or isinstance(d, np.ndarray):
maxLen = max(maxLen, len(d))
if name in names:
raise Exception('Name "%s" repeated' % name)
names.add(name)
## create empty array
out = np.empty(maxLen, dtype)
## fill columns
for element in data:
if isinstance(element, np.ndarray):
for i in range(len(element.dtype)):
name = element.dtype.names[i]
try:
out[name] = element[name]
except:
print("Column:", name)
print("Input shape:", element.shape, element.dtype)
print("Output shape:", out.shape, out.dtype)
raise
else:
name, type, d = element
out[name] = d
return out
def suggestDType(x):
"""Return a suitable dtype for x"""
if isinstance(x, list) or isinstance(x, tuple):
if len(x) == 0:
raise Exception('can not determine dtype for empty list')
x = x[0]
if hasattr(x, 'dtype'):
return x.dtype
elif isinstance(x, float):
return float
elif isinstance(x, int):
return int
#elif isinstance(x, basestring): ## don't try to guess correct string length; use object instead.
#return '<U%d' % len(x)
else:
return object
def removePeriodic(data, f0=60.0, dt=None, harmonics=10, samples=4):
if (hasattr(data, 'implements') and data.implements('MetaArray')):
data1 = data.asarray()
if dt is None:
times = data.xvals('Time')
dt = times[1]-times[0]
else:
data1 = data
if dt is None:
raise Exception('Must specify dt for this data')
ft = np.fft.fft(data1)
## determine frequencies in fft data
df = 1.0 / (len(data1) * dt)
freqs = np.linspace(0.0, (len(ft)-1) * df, len(ft))
## flatten spikes at f0 and harmonics
for i in xrange(1, harmonics + 2):
f = f0 * i # target frequency
## determine index range to check for this frequency
ind1 = int(np.floor(f / df))
ind2 = int(np.ceil(f / df)) + (samples-1)
if ind1 > len(ft)/2.:
break
mag = (abs(ft[ind1-1]) + abs(ft[ind2+1])) * 0.5
for j in range(ind1, ind2+1):
phase = np.angle(ft[j]) ## Must preserve the phase of each point, otherwise any transients in the trace might lead to large artifacts.
re = mag * np.cos(phase)
im = mag * np.sin(phase)
ft[j] = re + im*1j
ft[len(ft)-j] = re - im*1j
data2 = np.fft.ifft(ft).real
if (hasattr(data, 'implements') and data.implements('MetaArray')):
return metaarray.MetaArray(data2, info=data.infoCopy())
else:
return data2
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/flowchart/library/Operators.py | .py | 3,225 | 106 | # -*- coding: utf-8 -*-
from ..Node import Node
from .common import CtrlNode
class UniOpNode(Node):
"""Generic node for performing any operation like Out = In.fn()"""
def __init__(self, name, fn):
self.fn = fn
Node.__init__(self, name, terminals={
'In': {'io': 'in'},
'Out': {'io': 'out', 'bypass': 'In'}
})
def process(self, **args):
return {'Out': getattr(args['In'], self.fn)()}
class BinOpNode(CtrlNode):
"""Generic node for performing any operation like A.fn(B)"""
_dtypes = [
'float64', 'float32', 'float16',
'int64', 'int32', 'int16', 'int8',
'uint64', 'uint32', 'uint16', 'uint8'
]
uiTemplate = [
('outputType', 'combo', {'values': ['no change', 'input A', 'input B'] + _dtypes , 'index': 0})
]
def __init__(self, name, fn):
self.fn = fn
CtrlNode.__init__(self, name, terminals={
'A': {'io': 'in'},
'B': {'io': 'in'},
'Out': {'io': 'out', 'bypass': 'A'}
})
def process(self, **args):
if isinstance(self.fn, tuple):
for name in self.fn:
try:
fn = getattr(args['A'], name)
break
except AttributeError:
pass
else:
fn = getattr(args['A'], self.fn)
out = fn(args['B'])
if out is NotImplemented:
raise Exception("Operation %s not implemented between %s and %s" % (fn, str(type(args['A'])), str(type(args['B']))))
# Coerce dtype if requested
typ = self.stateGroup.state()['outputType']
if typ == 'no change':
pass
elif typ == 'input A':
out = out.astype(args['A'].dtype)
elif typ == 'input B':
out = out.astype(args['B'].dtype)
else:
out = out.astype(typ)
#print " ", fn, out
return {'Out': out}
class AbsNode(UniOpNode):
"""Returns abs(Inp). Does not check input types."""
nodeName = 'Abs'
def __init__(self, name):
UniOpNode.__init__(self, name, '__abs__')
class AddNode(BinOpNode):
"""Returns A + B. Does not check input types."""
nodeName = 'Add'
def __init__(self, name):
BinOpNode.__init__(self, name, '__add__')
class SubtractNode(BinOpNode):
"""Returns A - B. Does not check input types."""
nodeName = 'Subtract'
def __init__(self, name):
BinOpNode.__init__(self, name, '__sub__')
class MultiplyNode(BinOpNode):
"""Returns A * B. Does not check input types."""
nodeName = 'Multiply'
def __init__(self, name):
BinOpNode.__init__(self, name, '__mul__')
class DivideNode(BinOpNode):
"""Returns A / B. Does not check input types."""
nodeName = 'Divide'
def __init__(self, name):
# try truediv first, followed by div
BinOpNode.__init__(self, name, ('__truediv__', '__div__'))
class FloorDivideNode(BinOpNode):
"""Returns A // B. Does not check input types."""
nodeName = 'FloorDivide'
def __init__(self, name):
BinOpNode.__init__(self, name, '__floordiv__')
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/imageview/ImageViewTemplate_pyqt.py | .py | 8,781 | 169 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ImageViewTemplate.ui'
#
# Created: Thu May 1 15:20:40 2014
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from ..Qt 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(726, 588)
self.gridLayout_3 = QtGui.QGridLayout(Form)
self.gridLayout_3.setMargin(0)
self.gridLayout_3.setSpacing(0)
self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3"))
self.splitter = QtGui.QSplitter(Form)
self.splitter.setOrientation(QtCore.Qt.Vertical)
self.splitter.setObjectName(_fromUtf8("splitter"))
self.layoutWidget = QtGui.QWidget(self.splitter)
self.layoutWidget.setObjectName(_fromUtf8("layoutWidget"))
self.gridLayout = QtGui.QGridLayout(self.layoutWidget)
self.gridLayout.setSpacing(0)
self.gridLayout.setMargin(0)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.graphicsView = GraphicsView(self.layoutWidget)
self.graphicsView.setObjectName(_fromUtf8("graphicsView"))
self.gridLayout.addWidget(self.graphicsView, 0, 0, 2, 1)
self.histogram = HistogramLUTWidget(self.layoutWidget)
self.histogram.setObjectName(_fromUtf8("histogram"))
self.gridLayout.addWidget(self.histogram, 0, 1, 1, 2)
self.roiBtn = QtGui.QPushButton(self.layoutWidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(1)
sizePolicy.setHeightForWidth(self.roiBtn.sizePolicy().hasHeightForWidth())
self.roiBtn.setSizePolicy(sizePolicy)
self.roiBtn.setCheckable(True)
self.roiBtn.setObjectName(_fromUtf8("roiBtn"))
self.gridLayout.addWidget(self.roiBtn, 1, 1, 1, 1)
self.menuBtn = QtGui.QPushButton(self.layoutWidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(1)
sizePolicy.setHeightForWidth(self.menuBtn.sizePolicy().hasHeightForWidth())
self.menuBtn.setSizePolicy(sizePolicy)
self.menuBtn.setObjectName(_fromUtf8("menuBtn"))
self.gridLayout.addWidget(self.menuBtn, 1, 2, 1, 1)
self.roiPlot = PlotWidget(self.splitter)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.roiPlot.sizePolicy().hasHeightForWidth())
self.roiPlot.setSizePolicy(sizePolicy)
self.roiPlot.setMinimumSize(QtCore.QSize(0, 40))
self.roiPlot.setObjectName(_fromUtf8("roiPlot"))
self.gridLayout_3.addWidget(self.splitter, 0, 0, 1, 1)
self.normGroup = QtGui.QGroupBox(Form)
self.normGroup.setObjectName(_fromUtf8("normGroup"))
self.gridLayout_2 = QtGui.QGridLayout(self.normGroup)
self.gridLayout_2.setMargin(0)
self.gridLayout_2.setSpacing(0)
self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
self.normSubtractRadio = QtGui.QRadioButton(self.normGroup)
self.normSubtractRadio.setObjectName(_fromUtf8("normSubtractRadio"))
self.gridLayout_2.addWidget(self.normSubtractRadio, 0, 2, 1, 1)
self.normDivideRadio = QtGui.QRadioButton(self.normGroup)
self.normDivideRadio.setChecked(False)
self.normDivideRadio.setObjectName(_fromUtf8("normDivideRadio"))
self.gridLayout_2.addWidget(self.normDivideRadio, 0, 1, 1, 1)
self.label_5 = QtGui.QLabel(self.normGroup)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_5.setFont(font)
self.label_5.setObjectName(_fromUtf8("label_5"))
self.gridLayout_2.addWidget(self.label_5, 0, 0, 1, 1)
self.label_3 = QtGui.QLabel(self.normGroup)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_3.setFont(font)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.gridLayout_2.addWidget(self.label_3, 1, 0, 1, 1)
self.label_4 = QtGui.QLabel(self.normGroup)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_4.setFont(font)
self.label_4.setObjectName(_fromUtf8("label_4"))
self.gridLayout_2.addWidget(self.label_4, 2, 0, 1, 1)
self.normROICheck = QtGui.QCheckBox(self.normGroup)
self.normROICheck.setObjectName(_fromUtf8("normROICheck"))
self.gridLayout_2.addWidget(self.normROICheck, 1, 1, 1, 1)
self.normXBlurSpin = QtGui.QDoubleSpinBox(self.normGroup)
self.normXBlurSpin.setObjectName(_fromUtf8("normXBlurSpin"))
self.gridLayout_2.addWidget(self.normXBlurSpin, 2, 2, 1, 1)
self.label_8 = QtGui.QLabel(self.normGroup)
self.label_8.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_8.setObjectName(_fromUtf8("label_8"))
self.gridLayout_2.addWidget(self.label_8, 2, 1, 1, 1)
self.label_9 = QtGui.QLabel(self.normGroup)
self.label_9.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_9.setObjectName(_fromUtf8("label_9"))
self.gridLayout_2.addWidget(self.label_9, 2, 3, 1, 1)
self.normYBlurSpin = QtGui.QDoubleSpinBox(self.normGroup)
self.normYBlurSpin.setObjectName(_fromUtf8("normYBlurSpin"))
self.gridLayout_2.addWidget(self.normYBlurSpin, 2, 4, 1, 1)
self.label_10 = QtGui.QLabel(self.normGroup)
self.label_10.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_10.setObjectName(_fromUtf8("label_10"))
self.gridLayout_2.addWidget(self.label_10, 2, 5, 1, 1)
self.normOffRadio = QtGui.QRadioButton(self.normGroup)
self.normOffRadio.setChecked(True)
self.normOffRadio.setObjectName(_fromUtf8("normOffRadio"))
self.gridLayout_2.addWidget(self.normOffRadio, 0, 3, 1, 1)
self.normTimeRangeCheck = QtGui.QCheckBox(self.normGroup)
self.normTimeRangeCheck.setObjectName(_fromUtf8("normTimeRangeCheck"))
self.gridLayout_2.addWidget(self.normTimeRangeCheck, 1, 3, 1, 1)
self.normFrameCheck = QtGui.QCheckBox(self.normGroup)
self.normFrameCheck.setObjectName(_fromUtf8("normFrameCheck"))
self.gridLayout_2.addWidget(self.normFrameCheck, 1, 2, 1, 1)
self.normTBlurSpin = QtGui.QDoubleSpinBox(self.normGroup)
self.normTBlurSpin.setObjectName(_fromUtf8("normTBlurSpin"))
self.gridLayout_2.addWidget(self.normTBlurSpin, 2, 6, 1, 1)
self.gridLayout_3.addWidget(self.normGroup, 1, 0, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Form", None))
self.roiBtn.setText(_translate("Form", "ROI", None))
self.menuBtn.setText(_translate("Form", "Menu", None))
self.normGroup.setTitle(_translate("Form", "Normalization", None))
self.normSubtractRadio.setText(_translate("Form", "Subtract", None))
self.normDivideRadio.setText(_translate("Form", "Divide", None))
self.label_5.setText(_translate("Form", "Operation:", None))
self.label_3.setText(_translate("Form", "Mean:", None))
self.label_4.setText(_translate("Form", "Blur:", None))
self.normROICheck.setText(_translate("Form", "ROI", None))
self.label_8.setText(_translate("Form", "X", None))
self.label_9.setText(_translate("Form", "Y", None))
self.label_10.setText(_translate("Form", "T", None))
self.normOffRadio.setText(_translate("Form", "Off", None))
self.normTimeRangeCheck.setText(_translate("Form", "Time range", None))
self.normFrameCheck.setText(_translate("Form", "Frame", None))
from ..widgets.HistogramLUTWidget import HistogramLUTWidget
from ..widgets.GraphicsView import GraphicsView
from ..widgets.PlotWidget import PlotWidget
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/imageview/__init__.py | .py | 161 | 7 | """
Widget used for display and analysis of 2D and 3D image data.
Includes ROI plotting over time and image normalization.
"""
from .ImageView import ImageView
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/imageview/ImageView.py | .py | 31,448 | 828 | # -*- coding: utf-8 -*-
"""
ImageView.py - Widget for basic image dispay and analysis
Copyright 2010 Luke Campagnola
Distributed under MIT/X11 license. See license.txt for more information.
Widget used for displaying 2D or 3D data. Features:
- float or int (including 16-bit int) image display via ImageItem
- zoom/pan via GraphicsView
- black/white level controls
- time slider for 3D data sets
- ROI plotting
- Image normalization through a variety of methods
"""
import os, sys
import numpy as np
from ..Qt import QtCore, QtGui, QT_LIB
if QT_LIB == 'PySide':
from .ImageViewTemplate_pyside import *
elif QT_LIB == 'PySide2':
from .ImageViewTemplate_pyside2 import *
elif QT_LIB == 'PyQt5':
from .ImageViewTemplate_pyqt5 import *
else:
from .ImageViewTemplate_pyqt import *
from ..graphicsItems.ImageItem import *
from ..graphicsItems.ROI import *
from ..graphicsItems.LinearRegionItem import *
from ..graphicsItems.InfiniteLine import *
from ..graphicsItems.ViewBox import *
from ..graphicsItems.VTickGroup import VTickGroup
from ..graphicsItems.GradientEditorItem import addGradientListToDocstring
from .. import ptime as ptime
from .. import debug as debug
from ..SignalProxy import SignalProxy
from .. import getConfigOption
try:
from bottleneck import nanmin, nanmax
except ImportError:
from numpy import nanmin, nanmax
class PlotROI(ROI):
def __init__(self, size):
ROI.__init__(self, pos=[0,0], size=size) #, scaleSnap=True, translateSnap=True)
self.addScaleHandle([1, 1], [0, 0])
self.addRotateHandle([0, 0], [0.5, 0.5])
class ImageView(QtGui.QWidget):
"""
Widget used for display and analysis of image data.
Implements many features:
* Displays 2D and 3D image data. For 3D data, a z-axis
slider is displayed allowing the user to select which frame is displayed.
* Displays histogram of image data with movable region defining the dark/light levels
* Editable gradient provides a color lookup table
* Frame slider may also be moved using left/right arrow keys as well as pgup, pgdn, home, and end.
* Basic analysis features including:
* ROI and embedded plot for measuring image values across frames
* Image normalization / background subtraction
Basic Usage::
imv = pg.ImageView()
imv.show()
imv.setImage(data)
**Keyboard interaction**
* left/right arrows step forward/backward 1 frame when pressed,
seek at 20fps when held.
* up/down arrows seek at 100fps
* pgup/pgdn seek at 1000fps
* home/end seek immediately to the first/last frame
* space begins playing frames. If time values (in seconds) are given
for each frame, then playback is in realtime.
"""
sigTimeChanged = QtCore.Signal(object, object)
sigProcessingChanged = QtCore.Signal(object)
def __init__(self, parent=None, name="ImageView", view=None, imageItem=None,
levelMode='mono', *args):
"""
By default, this class creates an :class:`ImageItem <pyqtgraph.ImageItem>` to display image data
and a :class:`ViewBox <pyqtgraph.ViewBox>` to contain the ImageItem.
============= =========================================================
**Arguments**
parent (QWidget) Specifies the parent widget to which
this ImageView will belong. If None, then the ImageView
is created with no parent.
name (str) The name used to register both the internal ViewBox
and the PlotItem used to display ROI data. See the *name*
argument to :func:`ViewBox.__init__()
<pyqtgraph.ViewBox.__init__>`.
view (ViewBox or PlotItem) If specified, this will be used
as the display area that contains the displayed image.
Any :class:`ViewBox <pyqtgraph.ViewBox>`,
:class:`PlotItem <pyqtgraph.PlotItem>`, or other
compatible object is acceptable.
imageItem (ImageItem) If specified, this object will be used to
display the image. Must be an instance of ImageItem
or other compatible object.
levelMode See the *levelMode* argument to
:func:`HistogramLUTItem.__init__()
<pyqtgraph.HistogramLUTItem.__init__>`
============= =========================================================
Note: to display axis ticks inside the ImageView, instantiate it
with a PlotItem instance as its view::
pg.ImageView(view=pg.PlotItem())
"""
QtGui.QWidget.__init__(self, parent, *args)
self._imageLevels = None # [(min, max), ...] per channel image metrics
self.levelMin = None # min / max levels across all channels
self.levelMax = None
self.name = name
self.image = None
self.axes = {}
self.imageDisp = None
self.ui = Ui_Form()
self.ui.setupUi(self)
self.scene = self.ui.graphicsView.scene()
self.ui.histogram.setLevelMode(levelMode)
self.ignorePlaying = False
if view is None:
self.view = ViewBox()
else:
self.view = view
self.ui.graphicsView.setCentralItem(self.view)
self.view.setAspectLocked(True)
self.view.invertY()
if imageItem is None:
self.imageItem = ImageItem()
else:
self.imageItem = imageItem
self.view.addItem(self.imageItem)
self.currentIndex = 0
self.ui.histogram.setImageItem(self.imageItem)
self.menu = None
self.ui.normGroup.hide()
self.roi = PlotROI(10)
self.roi.setZValue(20)
self.view.addItem(self.roi)
self.roi.hide()
self.normRoi = PlotROI(10)
self.normRoi.setPen('y')
self.normRoi.setZValue(20)
self.view.addItem(self.normRoi)
self.normRoi.hide()
self.roiCurves = []
self.timeLine = InfiniteLine(0, movable=True, markers=[('^', 0), ('v', 1)])
self.timeLine.setPen((255, 255, 0, 200))
self.timeLine.setZValue(1)
self.ui.roiPlot.addItem(self.timeLine)
self.ui.splitter.setSizes([self.height()-35, 35])
self.ui.roiPlot.hideAxis('left')
self.frameTicks = VTickGroup(yrange=[0.8, 1], pen=0.4)
self.ui.roiPlot.addItem(self.frameTicks, ignoreBounds=True)
self.keysPressed = {}
self.playTimer = QtCore.QTimer()
self.playRate = 0
self.lastPlayTime = 0
self.normRgn = LinearRegionItem()
self.normRgn.setZValue(0)
self.ui.roiPlot.addItem(self.normRgn)
self.normRgn.hide()
## wrap functions from view box
for fn in ['addItem', 'removeItem']:
setattr(self, fn, getattr(self.view, fn))
## wrap functions from histogram
for fn in ['setHistogramRange', 'autoHistogramRange', 'getLookupTable', 'getLevels']:
setattr(self, fn, getattr(self.ui.histogram, fn))
self.timeLine.sigPositionChanged.connect(self.timeLineChanged)
self.ui.roiBtn.clicked.connect(self.roiClicked)
self.roi.sigRegionChanged.connect(self.roiChanged)
#self.ui.normBtn.toggled.connect(self.normToggled)
self.ui.menuBtn.clicked.connect(self.menuClicked)
self.ui.normDivideRadio.clicked.connect(self.normRadioChanged)
self.ui.normSubtractRadio.clicked.connect(self.normRadioChanged)
self.ui.normOffRadio.clicked.connect(self.normRadioChanged)
self.ui.normROICheck.clicked.connect(self.updateNorm)
self.ui.normFrameCheck.clicked.connect(self.updateNorm)
self.ui.normTimeRangeCheck.clicked.connect(self.updateNorm)
self.playTimer.timeout.connect(self.timeout)
self.normProxy = SignalProxy(self.normRgn.sigRegionChanged, slot=self.updateNorm)
self.normRoi.sigRegionChangeFinished.connect(self.updateNorm)
self.ui.roiPlot.registerPlot(self.name + '_ROI')
self.view.register(self.name)
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.roiClicked() ## initialize roi plot to correct shape / visibility
def setImage(self, img, autoRange=True, autoLevels=True, levels=None, axes=None, xvals=None, pos=None, scale=None, transform=None, autoHistogramRange=True, levelMode=None):
"""
Set the image to be displayed in the widget.
================== ===========================================================================
**Arguments:**
img (numpy array) the image to be displayed. See :func:`ImageItem.setImage` and
*notes* below.
xvals (numpy array) 1D array of z-axis values corresponding to the first axis
in a 3D image. For video, this array should contain the time of each
frame.
autoRange (bool) whether to scale/pan the view to fit the image.
autoLevels (bool) whether to update the white/black levels to fit the image.
levels (min, max); the white and black level values to use.
axes Dictionary indicating the interpretation for each axis.
This is only needed to override the default guess. Format is::
{'t':0, 'x':1, 'y':2, 'c':3};
pos Change the position of the displayed image
scale Change the scale of the displayed image
transform Set the transform of the displayed image. This option overrides *pos*
and *scale*.
autoHistogramRange If True, the histogram y-range is automatically scaled to fit the
image data.
levelMode If specified, this sets the user interaction mode for setting image
levels. Options are 'mono', which provides a single level control for
all image channels, and 'rgb' or 'rgba', which provide individual
controls for each channel.
================== ===========================================================================
**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()::
imageview.setImage(imagedata.T)
This requirement can be changed by the ``imageAxisOrder``
:ref:`global configuration option <apiref_config>`.
"""
profiler = debug.Profiler()
if hasattr(img, 'implements') and img.implements('MetaArray'):
img = img.asarray()
if not isinstance(img, np.ndarray):
required = ['dtype', 'max', 'min', 'ndim', 'shape', 'size']
if not all([hasattr(img, attr) for attr in required]):
raise TypeError("Image must be NumPy array or any object "
"that provides compatible attributes/methods:\n"
" %s" % str(required))
self.image = img
self.imageDisp = None
if levelMode is not None:
self.ui.histogram.setLevelMode(levelMode)
profiler()
if axes is None:
x,y = (0, 1) if self.imageItem.axisOrder == 'col-major' else (1, 0)
if img.ndim == 2:
self.axes = {'t': None, 'x': x, 'y': y, 'c': None}
elif img.ndim == 3:
# Ambiguous case; make a guess
if img.shape[2] <= 4:
self.axes = {'t': None, 'x': x, 'y': y, 'c': 2}
else:
self.axes = {'t': 0, 'x': x+1, 'y': y+1, 'c': None}
elif img.ndim == 4:
# Even more ambiguous; just assume the default
self.axes = {'t': 0, 'x': x+1, 'y': y+1, 'c': 3}
else:
raise Exception("Can not interpret image with dimensions %s" % (str(img.shape)))
elif isinstance(axes, dict):
self.axes = axes.copy()
elif isinstance(axes, list) or isinstance(axes, tuple):
self.axes = {}
for i in range(len(axes)):
self.axes[axes[i]] = i
else:
raise Exception("Can not interpret axis specification %s. Must be like {'t': 2, 'x': 0, 'y': 1} or ('t', 'x', 'y', 'c')" % (str(axes)))
for x in ['t', 'x', 'y', 'c']:
self.axes[x] = self.axes.get(x, None)
axes = self.axes
if xvals is not None:
self.tVals = xvals
elif axes['t'] is not None:
if hasattr(img, 'xvals'):
try:
self.tVals = img.xvals(axes['t'])
except:
self.tVals = np.arange(img.shape[axes['t']])
else:
self.tVals = np.arange(img.shape[axes['t']])
profiler()
self.currentIndex = 0
self.updateImage(autoHistogramRange=autoHistogramRange)
if levels is None and autoLevels:
self.autoLevels()
if levels is not None: ## this does nothing since getProcessedImage sets these values again.
self.setLevels(*levels)
if self.ui.roiBtn.isChecked():
self.roiChanged()
profiler()
if self.axes['t'] is not None:
self.ui.roiPlot.setXRange(self.tVals.min(), self.tVals.max())
self.frameTicks.setXVals(self.tVals)
self.timeLine.setValue(0)
if len(self.tVals) > 1:
start = self.tVals.min()
stop = self.tVals.max() + abs(self.tVals[-1] - self.tVals[0]) * 0.02
elif len(self.tVals) == 1:
start = self.tVals[0] - 0.5
stop = self.tVals[0] + 0.5
else:
start = 0
stop = 1
for s in [self.timeLine, self.normRgn]:
s.setBounds([start, stop])
profiler()
self.imageItem.resetTransform()
if scale is not None:
self.imageItem.scale(*scale)
if pos is not None:
self.imageItem.setPos(*pos)
if transform is not None:
self.imageItem.setTransform(transform)
profiler()
if autoRange:
self.autoRange()
self.roiClicked()
profiler()
def clear(self):
self.image = None
self.imageItem.clear()
def play(self, rate):
"""Begin automatically stepping frames forward at the given rate (in fps).
This can also be accessed by pressing the spacebar."""
#print "play:", rate
self.playRate = rate
if rate == 0:
self.playTimer.stop()
return
self.lastPlayTime = ptime.time()
if not self.playTimer.isActive():
self.playTimer.start(16)
def autoLevels(self):
"""Set the min/max intensity levels automatically to match the image data."""
self.setLevels(rgba=self._imageLevels)
def setLevels(self, *args, **kwds):
"""Set the min/max (bright and dark) levels.
See :func:`HistogramLUTItem.setLevels <pyqtgraph.HistogramLUTItem.setLevels>`.
"""
self.ui.histogram.setLevels(*args, **kwds)
def autoRange(self):
"""Auto scale and pan the view around the image such that the image fills the view."""
image = self.getProcessedImage()
self.view.autoRange()
def getProcessedImage(self):
"""Returns the image data after it has been processed by any normalization options in use.
"""
if self.imageDisp is None:
image = self.normalize(self.image)
self.imageDisp = image
self._imageLevels = self.quickMinMax(self.imageDisp)
self.levelMin = min([level[0] for level in self._imageLevels])
self.levelMax = max([level[1] for level in self._imageLevels])
return self.imageDisp
def close(self):
"""Closes the widget nicely, making sure to clear the graphics scene and release memory."""
self.ui.roiPlot.close()
self.ui.graphicsView.close()
self.scene.clear()
del self.image
del self.imageDisp
super(ImageView, self).close()
self.setParent(None)
def keyPressEvent(self, ev):
#print ev.key()
if ev.key() == QtCore.Qt.Key_Space:
if self.playRate == 0:
fps = (self.getProcessedImage().shape[0]-1) / (self.tVals[-1] - self.tVals[0])
self.play(fps)
#print fps
else:
self.play(0)
ev.accept()
elif ev.key() == QtCore.Qt.Key_Home:
self.setCurrentIndex(0)
self.play(0)
ev.accept()
elif ev.key() == QtCore.Qt.Key_End:
self.setCurrentIndex(self.getProcessedImage().shape[0]-1)
self.play(0)
ev.accept()
elif ev.key() in self.noRepeatKeys:
ev.accept()
if ev.isAutoRepeat():
return
self.keysPressed[ev.key()] = 1
self.evalKeyState()
else:
QtGui.QWidget.keyPressEvent(self, ev)
def keyReleaseEvent(self, ev):
if ev.key() in [QtCore.Qt.Key_Space, QtCore.Qt.Key_Home, QtCore.Qt.Key_End]:
ev.accept()
elif ev.key() in self.noRepeatKeys:
ev.accept()
if ev.isAutoRepeat():
return
try:
del self.keysPressed[ev.key()]
except:
self.keysPressed = {}
self.evalKeyState()
else:
QtGui.QWidget.keyReleaseEvent(self, ev)
def evalKeyState(self):
if len(self.keysPressed) == 1:
key = list(self.keysPressed.keys())[0]
if key == QtCore.Qt.Key_Right:
self.play(20)
self.jumpFrames(1)
self.lastPlayTime = ptime.time() + 0.2 ## 2ms wait before start
## This happens *after* jumpFrames, since it might take longer than 2ms
elif key == QtCore.Qt.Key_Left:
self.play(-20)
self.jumpFrames(-1)
self.lastPlayTime = ptime.time() + 0.2
elif key == QtCore.Qt.Key_Up:
self.play(-100)
elif key == QtCore.Qt.Key_Down:
self.play(100)
elif key == QtCore.Qt.Key_PageUp:
self.play(-1000)
elif key == QtCore.Qt.Key_PageDown:
self.play(1000)
else:
self.play(0)
def timeout(self):
now = ptime.time()
dt = now - self.lastPlayTime
if dt < 0:
return
n = int(self.playRate * dt)
if n != 0:
self.lastPlayTime += (float(n)/self.playRate)
if self.currentIndex+n > self.image.shape[self.axes['t']]:
self.play(0)
self.jumpFrames(n)
def setCurrentIndex(self, ind):
"""Set the currently displayed frame index."""
index = np.clip(ind, 0, self.getProcessedImage().shape[self.axes['t']]-1)
self.ignorePlaying = True
# Implicitly call timeLineChanged
self.timeLine.setValue(self.tVals[index])
self.ignorePlaying = False
def jumpFrames(self, n):
"""Move video frame ahead n frames (may be negative)"""
if self.axes['t'] is not None:
self.setCurrentIndex(self.currentIndex + n)
def normRadioChanged(self):
self.imageDisp = None
self.updateImage()
self.autoLevels()
self.roiChanged()
self.sigProcessingChanged.emit(self)
def updateNorm(self):
if self.ui.normTimeRangeCheck.isChecked():
self.normRgn.show()
else:
self.normRgn.hide()
if self.ui.normROICheck.isChecked():
self.normRoi.show()
else:
self.normRoi.hide()
if not self.ui.normOffRadio.isChecked():
self.imageDisp = None
self.updateImage()
self.autoLevels()
self.roiChanged()
self.sigProcessingChanged.emit(self)
def normToggled(self, b):
self.ui.normGroup.setVisible(b)
self.normRoi.setVisible(b and self.ui.normROICheck.isChecked())
self.normRgn.setVisible(b and self.ui.normTimeRangeCheck.isChecked())
def hasTimeAxis(self):
return 't' in self.axes and self.axes['t'] is not None
def roiClicked(self):
showRoiPlot = False
if self.ui.roiBtn.isChecked():
showRoiPlot = True
self.roi.show()
#self.ui.roiPlot.show()
self.ui.roiPlot.setMouseEnabled(True, True)
self.ui.splitter.setSizes([self.height()*0.6, self.height()*0.4])
for c in self.roiCurves:
c.show()
self.roiChanged()
self.ui.roiPlot.showAxis('left')
else:
self.roi.hide()
self.ui.roiPlot.setMouseEnabled(False, False)
for c in self.roiCurves:
c.hide()
self.ui.roiPlot.hideAxis('left')
if self.hasTimeAxis():
showRoiPlot = True
mn = self.tVals.min()
mx = self.tVals.max()
self.ui.roiPlot.setXRange(mn, mx, padding=0.01)
self.timeLine.show()
self.timeLine.setBounds([mn, mx])
self.ui.roiPlot.show()
if not self.ui.roiBtn.isChecked():
self.ui.splitter.setSizes([self.height()-35, 35])
else:
self.timeLine.hide()
#self.ui.roiPlot.hide()
self.ui.roiPlot.setVisible(showRoiPlot)
def roiChanged(self):
if self.image is None:
return
image = self.getProcessedImage()
# Extract image data from ROI
axes = (self.axes['x'], self.axes['y'])
data, coords = self.roi.getArrayRegion(image.view(np.ndarray), self.imageItem, axes, returnMappedCoords=True)
if data is None:
return
# Convert extracted data into 1D plot data
if self.axes['t'] is None:
# Average across y-axis of ROI
data = data.mean(axis=axes[1])
coords = coords[:,:,0] - coords[:,0:1,0]
xvals = (coords**2).sum(axis=0) ** 0.5
else:
# Average data within entire ROI for each frame
data = data.mean(axis=max(axes)).mean(axis=min(axes))
xvals = self.tVals
# Handle multi-channel data
if data.ndim == 1:
plots = [(xvals, data, 'w')]
if data.ndim == 2:
if data.shape[1] == 1:
colors = 'w'
else:
colors = 'rgbw'
plots = []
for i in range(data.shape[1]):
d = data[:,i]
plots.append((xvals, d, colors[i]))
# Update plot line(s)
while len(plots) < len(self.roiCurves):
c = self.roiCurves.pop()
c.scene().removeItem(c)
while len(plots) > len(self.roiCurves):
self.roiCurves.append(self.ui.roiPlot.plot())
for i in range(len(plots)):
x, y, p = plots[i]
self.roiCurves[i].setData(x, y, pen=p)
def quickMinMax(self, data):
"""
Estimate the min/max values of *data* by subsampling.
Returns [(min, max), ...] with one item per channel
"""
while data.size > 1e6:
ax = np.argmax(data.shape)
sl = [slice(None)] * data.ndim
sl[ax] = slice(None, None, 2)
data = data[tuple(sl)]
cax = self.axes['c']
if cax is None:
if data.size == 0:
return [(0, 0)]
return [(float(nanmin(data)), float(nanmax(data)))]
else:
if data.size == 0:
return [(0, 0)] * data.shape[-1]
return [(float(nanmin(data.take(i, axis=cax))),
float(nanmax(data.take(i, axis=cax)))) for i in range(data.shape[-1])]
def normalize(self, image):
"""
Process *image* using the normalization options configured in the
control panel.
This can be repurposed to process any data through the same filter.
"""
if self.ui.normOffRadio.isChecked():
return image
div = self.ui.normDivideRadio.isChecked()
norm = image.view(np.ndarray).copy()
#if div:
#norm = ones(image.shape)
#else:
#norm = zeros(image.shape)
if div:
norm = norm.astype(np.float32)
if self.ui.normTimeRangeCheck.isChecked() and image.ndim == 3:
(sind, start) = self.timeIndex(self.normRgn.lines[0])
(eind, end) = self.timeIndex(self.normRgn.lines[1])
#print start, end, sind, eind
n = image[sind:eind+1].mean(axis=0)
n.shape = (1,) + n.shape
if div:
norm /= n
else:
norm -= n
if self.ui.normFrameCheck.isChecked() and image.ndim == 3:
n = image.mean(axis=1).mean(axis=1)
n.shape = n.shape + (1, 1)
if div:
norm /= n
else:
norm -= n
if self.ui.normROICheck.isChecked() and image.ndim == 3:
n = self.normRoi.getArrayRegion(norm, self.imageItem, (1, 2)).mean(axis=1).mean(axis=1)
n = n[:,np.newaxis,np.newaxis]
#print start, end, sind, eind
if div:
norm /= n
else:
norm -= n
return norm
def timeLineChanged(self):
if not self.ignorePlaying:
self.play(0)
(ind, time) = self.timeIndex(self.timeLine)
if ind != self.currentIndex:
self.currentIndex = ind
self.updateImage()
self.sigTimeChanged.emit(ind, time)
def updateImage(self, autoHistogramRange=True):
## Redraw image on screen
if self.image is None:
return
image = self.getProcessedImage()
if autoHistogramRange:
self.ui.histogram.setHistogramRange(self.levelMin, self.levelMax)
# Transpose image into order expected by ImageItem
if self.imageItem.axisOrder == 'col-major':
axorder = ['t', 'x', 'y', 'c']
else:
axorder = ['t', 'y', 'x', 'c']
axorder = [self.axes[ax] for ax in axorder if self.axes[ax] is not None]
image = image.transpose(axorder)
# Select time index
if self.axes['t'] is not None:
self.ui.roiPlot.show()
image = image[self.currentIndex]
self.imageItem.updateImage(image)
def timeIndex(self, slider):
## Return the time and frame index indicated by a slider
if self.image is None:
return (0,0)
t = slider.value()
xv = self.tVals
if xv is None:
ind = int(t)
else:
if len(xv) < 2:
return (0,0)
totTime = xv[-1] + (xv[-1]-xv[-2])
inds = np.argwhere(xv <= t)
if len(inds) < 1:
return (0,t)
ind = inds[-1,0]
return ind, t
def getView(self):
"""Return the ViewBox (or other compatible object) which displays the ImageItem"""
return self.view
def getImageItem(self):
"""Return the ImageItem for this ImageView."""
return self.imageItem
def getRoiPlot(self):
"""Return the ROI PlotWidget for this ImageView"""
return self.ui.roiPlot
def getHistogramWidget(self):
"""Return the HistogramLUTWidget for this ImageView"""
return self.ui.histogram
def export(self, fileName):
"""
Export data from the ImageView to a file, or to a stack of files if
the data is 3D. Saving an image stack will result in index numbers
being added to the file name. Images are saved as they would appear
onscreen, with levels and lookup table applied.
"""
img = self.getProcessedImage()
if self.hasTimeAxis():
base, ext = os.path.splitext(fileName)
fmt = "%%s%%0%dd%%s" % int(np.log10(img.shape[0])+1)
for i in range(img.shape[0]):
self.imageItem.setImage(img[i], autoLevels=False)
self.imageItem.save(fmt % (base, i, ext))
self.updateImage()
else:
self.imageItem.save(fileName)
def exportClicked(self):
fileName = QtGui.QFileDialog.getSaveFileName()
if isinstance(fileName, tuple):
fileName = fileName[0] # Qt4/5 API difference
if fileName == '':
return
self.export(str(fileName))
def buildMenu(self):
self.menu = QtGui.QMenu()
self.normAction = QtGui.QAction("Normalization", self.menu)
self.normAction.setCheckable(True)
self.normAction.toggled.connect(self.normToggled)
self.menu.addAction(self.normAction)
self.exportAction = QtGui.QAction("Export", self.menu)
self.exportAction.triggered.connect(self.exportClicked)
self.menu.addAction(self.exportAction)
def menuClicked(self):
if self.menu is None:
self.buildMenu()
self.menu.popup(QtGui.QCursor.pos())
def setColorMap(self, colormap):
"""Set the color map.
============= =========================================================
**Arguments**
colormap (A ColorMap() instance) The ColorMap to use for coloring
images.
============= =========================================================
"""
self.ui.histogram.gradient.setColorMap(colormap)
@addGradientListToDocstring()
def setPredefinedGradient(self, name):
"""Set one of the gradients defined in :class:`GradientEditorItem <pyqtgraph.graphicsItems.GradientEditorItem>`.
Currently available gradients are:
"""
self.ui.histogram.gradient.loadPreset(name)
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/imageview/ImageViewTemplate_pyside2.py | .py | 8,687 | 155 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ImageViewTemplate.ui'
#
# Created: Sun Sep 18 19:17: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(726, 588)
self.gridLayout_3 = QtWidgets.QGridLayout(Form)
self.gridLayout_3.setContentsMargins(0, 0, 0, 0)
self.gridLayout_3.setSpacing(0)
self.gridLayout_3.setObjectName("gridLayout_3")
self.splitter = QtWidgets.QSplitter(Form)
self.splitter.setOrientation(QtCore.Qt.Vertical)
self.splitter.setObjectName("splitter")
self.layoutWidget = QtWidgets.QWidget(self.splitter)
self.layoutWidget.setObjectName("layoutWidget")
self.gridLayout = QtWidgets.QGridLayout(self.layoutWidget)
self.gridLayout.setSpacing(0)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setObjectName("gridLayout")
self.graphicsView = GraphicsView(self.layoutWidget)
self.graphicsView.setObjectName("graphicsView")
self.gridLayout.addWidget(self.graphicsView, 0, 0, 2, 1)
self.histogram = HistogramLUTWidget(self.layoutWidget)
self.histogram.setObjectName("histogram")
self.gridLayout.addWidget(self.histogram, 0, 1, 1, 2)
self.roiBtn = QtWidgets.QPushButton(self.layoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(1)
sizePolicy.setHeightForWidth(self.roiBtn.sizePolicy().hasHeightForWidth())
self.roiBtn.setSizePolicy(sizePolicy)
self.roiBtn.setCheckable(True)
self.roiBtn.setObjectName("roiBtn")
self.gridLayout.addWidget(self.roiBtn, 1, 1, 1, 1)
self.menuBtn = QtWidgets.QPushButton(self.layoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(1)
sizePolicy.setHeightForWidth(self.menuBtn.sizePolicy().hasHeightForWidth())
self.menuBtn.setSizePolicy(sizePolicy)
self.menuBtn.setObjectName("menuBtn")
self.gridLayout.addWidget(self.menuBtn, 1, 2, 1, 1)
self.roiPlot = PlotWidget(self.splitter)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.roiPlot.sizePolicy().hasHeightForWidth())
self.roiPlot.setSizePolicy(sizePolicy)
self.roiPlot.setMinimumSize(QtCore.QSize(0, 40))
self.roiPlot.setObjectName("roiPlot")
self.gridLayout_3.addWidget(self.splitter, 0, 0, 1, 1)
self.normGroup = QtWidgets.QGroupBox(Form)
self.normGroup.setObjectName("normGroup")
self.gridLayout_2 = QtWidgets.QGridLayout(self.normGroup)
self.gridLayout_2.setContentsMargins(0, 0, 0, 0)
self.gridLayout_2.setSpacing(0)
self.gridLayout_2.setObjectName("gridLayout_2")
self.normSubtractRadio = QtWidgets.QRadioButton(self.normGroup)
self.normSubtractRadio.setObjectName("normSubtractRadio")
self.gridLayout_2.addWidget(self.normSubtractRadio, 0, 2, 1, 1)
self.normDivideRadio = QtWidgets.QRadioButton(self.normGroup)
self.normDivideRadio.setChecked(False)
self.normDivideRadio.setObjectName("normDivideRadio")
self.gridLayout_2.addWidget(self.normDivideRadio, 0, 1, 1, 1)
self.label_5 = QtWidgets.QLabel(self.normGroup)
font = QtGui.QFont()
font.setWeight(75)
font.setBold(True)
self.label_5.setFont(font)
self.label_5.setObjectName("label_5")
self.gridLayout_2.addWidget(self.label_5, 0, 0, 1, 1)
self.label_3 = QtWidgets.QLabel(self.normGroup)
font = QtGui.QFont()
font.setWeight(75)
font.setBold(True)
self.label_3.setFont(font)
self.label_3.setObjectName("label_3")
self.gridLayout_2.addWidget(self.label_3, 1, 0, 1, 1)
self.label_4 = QtWidgets.QLabel(self.normGroup)
font = QtGui.QFont()
font.setWeight(75)
font.setBold(True)
self.label_4.setFont(font)
self.label_4.setObjectName("label_4")
self.gridLayout_2.addWidget(self.label_4, 2, 0, 1, 1)
self.normROICheck = QtWidgets.QCheckBox(self.normGroup)
self.normROICheck.setObjectName("normROICheck")
self.gridLayout_2.addWidget(self.normROICheck, 1, 1, 1, 1)
self.normXBlurSpin = QtWidgets.QDoubleSpinBox(self.normGroup)
self.normXBlurSpin.setObjectName("normXBlurSpin")
self.gridLayout_2.addWidget(self.normXBlurSpin, 2, 2, 1, 1)
self.label_8 = QtWidgets.QLabel(self.normGroup)
self.label_8.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_8.setObjectName("label_8")
self.gridLayout_2.addWidget(self.label_8, 2, 1, 1, 1)
self.label_9 = QtWidgets.QLabel(self.normGroup)
self.label_9.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_9.setObjectName("label_9")
self.gridLayout_2.addWidget(self.label_9, 2, 3, 1, 1)
self.normYBlurSpin = QtWidgets.QDoubleSpinBox(self.normGroup)
self.normYBlurSpin.setObjectName("normYBlurSpin")
self.gridLayout_2.addWidget(self.normYBlurSpin, 2, 4, 1, 1)
self.label_10 = QtWidgets.QLabel(self.normGroup)
self.label_10.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_10.setObjectName("label_10")
self.gridLayout_2.addWidget(self.label_10, 2, 5, 1, 1)
self.normOffRadio = QtWidgets.QRadioButton(self.normGroup)
self.normOffRadio.setChecked(True)
self.normOffRadio.setObjectName("normOffRadio")
self.gridLayout_2.addWidget(self.normOffRadio, 0, 3, 1, 1)
self.normTimeRangeCheck = QtWidgets.QCheckBox(self.normGroup)
self.normTimeRangeCheck.setObjectName("normTimeRangeCheck")
self.gridLayout_2.addWidget(self.normTimeRangeCheck, 1, 3, 1, 1)
self.normFrameCheck = QtWidgets.QCheckBox(self.normGroup)
self.normFrameCheck.setObjectName("normFrameCheck")
self.gridLayout_2.addWidget(self.normFrameCheck, 1, 2, 1, 1)
self.normTBlurSpin = QtWidgets.QDoubleSpinBox(self.normGroup)
self.normTBlurSpin.setObjectName("normTBlurSpin")
self.gridLayout_2.addWidget(self.normTBlurSpin, 2, 6, 1, 1)
self.gridLayout_3.addWidget(self.normGroup, 1, 0, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(QtWidgets.QApplication.translate("Form", "Form", None, -1))
self.roiBtn.setText(QtWidgets.QApplication.translate("Form", "ROI", None, -1))
self.menuBtn.setText(QtWidgets.QApplication.translate("Form", "Menu", None, -1))
self.normGroup.setTitle(QtWidgets.QApplication.translate("Form", "Normalization", None, -1))
self.normSubtractRadio.setText(QtWidgets.QApplication.translate("Form", "Subtract", None, -1))
self.normDivideRadio.setText(QtWidgets.QApplication.translate("Form", "Divide", None, -1))
self.label_5.setText(QtWidgets.QApplication.translate("Form", "Operation:", None, -1))
self.label_3.setText(QtWidgets.QApplication.translate("Form", "Mean:", None, -1))
self.label_4.setText(QtWidgets.QApplication.translate("Form", "Blur:", None, -1))
self.normROICheck.setText(QtWidgets.QApplication.translate("Form", "ROI", None, -1))
self.label_8.setText(QtWidgets.QApplication.translate("Form", "X", None, -1))
self.label_9.setText(QtWidgets.QApplication.translate("Form", "Y", None, -1))
self.label_10.setText(QtWidgets.QApplication.translate("Form", "T", None, -1))
self.normOffRadio.setText(QtWidgets.QApplication.translate("Form", "Off", None, -1))
self.normTimeRangeCheck.setText(QtWidgets.QApplication.translate("Form", "Time range", None, -1))
self.normFrameCheck.setText(QtWidgets.QApplication.translate("Form", "Frame", None, -1))
from ..widgets.HistogramLUTWidget import HistogramLUTWidget
from ..widgets.PlotWidget import PlotWidget
from ..widgets.GraphicsView import GraphicsView
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/imageview/ImageViewTemplate_pyqt5.py | .py | 8,275 | 157 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './pyqtgraph/imageview/ImageViewTemplate.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(726, 588)
self.gridLayout_3 = QtWidgets.QGridLayout(Form)
self.gridLayout_3.setContentsMargins(0, 0, 0, 0)
self.gridLayout_3.setSpacing(0)
self.gridLayout_3.setObjectName("gridLayout_3")
self.splitter = QtWidgets.QSplitter(Form)
self.splitter.setOrientation(QtCore.Qt.Vertical)
self.splitter.setObjectName("splitter")
self.layoutWidget = QtWidgets.QWidget(self.splitter)
self.layoutWidget.setObjectName("layoutWidget")
self.gridLayout = QtWidgets.QGridLayout(self.layoutWidget)
self.gridLayout.setSpacing(0)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setObjectName("gridLayout")
self.graphicsView = GraphicsView(self.layoutWidget)
self.graphicsView.setObjectName("graphicsView")
self.gridLayout.addWidget(self.graphicsView, 0, 0, 2, 1)
self.histogram = HistogramLUTWidget(self.layoutWidget)
self.histogram.setObjectName("histogram")
self.gridLayout.addWidget(self.histogram, 0, 1, 1, 2)
self.roiBtn = QtWidgets.QPushButton(self.layoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(1)
sizePolicy.setHeightForWidth(self.roiBtn.sizePolicy().hasHeightForWidth())
self.roiBtn.setSizePolicy(sizePolicy)
self.roiBtn.setCheckable(True)
self.roiBtn.setObjectName("roiBtn")
self.gridLayout.addWidget(self.roiBtn, 1, 1, 1, 1)
self.menuBtn = QtWidgets.QPushButton(self.layoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(1)
sizePolicy.setHeightForWidth(self.menuBtn.sizePolicy().hasHeightForWidth())
self.menuBtn.setSizePolicy(sizePolicy)
self.menuBtn.setCheckable(True)
self.menuBtn.setObjectName("menuBtn")
self.gridLayout.addWidget(self.menuBtn, 1, 2, 1, 1)
self.roiPlot = PlotWidget(self.splitter)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.roiPlot.sizePolicy().hasHeightForWidth())
self.roiPlot.setSizePolicy(sizePolicy)
self.roiPlot.setMinimumSize(QtCore.QSize(0, 40))
self.roiPlot.setObjectName("roiPlot")
self.gridLayout_3.addWidget(self.splitter, 0, 0, 1, 1)
self.normGroup = QtWidgets.QGroupBox(Form)
self.normGroup.setObjectName("normGroup")
self.gridLayout_2 = QtWidgets.QGridLayout(self.normGroup)
self.gridLayout_2.setContentsMargins(0, 0, 0, 0)
self.gridLayout_2.setSpacing(0)
self.gridLayout_2.setObjectName("gridLayout_2")
self.normSubtractRadio = QtWidgets.QRadioButton(self.normGroup)
self.normSubtractRadio.setObjectName("normSubtractRadio")
self.gridLayout_2.addWidget(self.normSubtractRadio, 0, 2, 1, 1)
self.normDivideRadio = QtWidgets.QRadioButton(self.normGroup)
self.normDivideRadio.setChecked(False)
self.normDivideRadio.setObjectName("normDivideRadio")
self.gridLayout_2.addWidget(self.normDivideRadio, 0, 1, 1, 1)
self.label_5 = QtWidgets.QLabel(self.normGroup)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_5.setFont(font)
self.label_5.setObjectName("label_5")
self.gridLayout_2.addWidget(self.label_5, 0, 0, 1, 1)
self.label_3 = QtWidgets.QLabel(self.normGroup)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_3.setFont(font)
self.label_3.setObjectName("label_3")
self.gridLayout_2.addWidget(self.label_3, 1, 0, 1, 1)
self.label_4 = QtWidgets.QLabel(self.normGroup)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_4.setFont(font)
self.label_4.setObjectName("label_4")
self.gridLayout_2.addWidget(self.label_4, 2, 0, 1, 1)
self.normROICheck = QtWidgets.QCheckBox(self.normGroup)
self.normROICheck.setObjectName("normROICheck")
self.gridLayout_2.addWidget(self.normROICheck, 1, 1, 1, 1)
self.normXBlurSpin = QtWidgets.QDoubleSpinBox(self.normGroup)
self.normXBlurSpin.setObjectName("normXBlurSpin")
self.gridLayout_2.addWidget(self.normXBlurSpin, 2, 2, 1, 1)
self.label_8 = QtWidgets.QLabel(self.normGroup)
self.label_8.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_8.setObjectName("label_8")
self.gridLayout_2.addWidget(self.label_8, 2, 1, 1, 1)
self.label_9 = QtWidgets.QLabel(self.normGroup)
self.label_9.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_9.setObjectName("label_9")
self.gridLayout_2.addWidget(self.label_9, 2, 3, 1, 1)
self.normYBlurSpin = QtWidgets.QDoubleSpinBox(self.normGroup)
self.normYBlurSpin.setObjectName("normYBlurSpin")
self.gridLayout_2.addWidget(self.normYBlurSpin, 2, 4, 1, 1)
self.label_10 = QtWidgets.QLabel(self.normGroup)
self.label_10.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_10.setObjectName("label_10")
self.gridLayout_2.addWidget(self.label_10, 2, 5, 1, 1)
self.normOffRadio = QtWidgets.QRadioButton(self.normGroup)
self.normOffRadio.setChecked(True)
self.normOffRadio.setObjectName("normOffRadio")
self.gridLayout_2.addWidget(self.normOffRadio, 0, 3, 1, 1)
self.normTimeRangeCheck = QtWidgets.QCheckBox(self.normGroup)
self.normTimeRangeCheck.setObjectName("normTimeRangeCheck")
self.gridLayout_2.addWidget(self.normTimeRangeCheck, 1, 3, 1, 1)
self.normFrameCheck = QtWidgets.QCheckBox(self.normGroup)
self.normFrameCheck.setObjectName("normFrameCheck")
self.gridLayout_2.addWidget(self.normFrameCheck, 1, 2, 1, 1)
self.normTBlurSpin = QtWidgets.QDoubleSpinBox(self.normGroup)
self.normTBlurSpin.setObjectName("normTBlurSpin")
self.gridLayout_2.addWidget(self.normTBlurSpin, 2, 6, 1, 1)
self.gridLayout_3.addWidget(self.normGroup, 1, 0, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.roiBtn.setText(_translate("Form", "ROI"))
self.menuBtn.setText(_translate("Form", "Norm"))
self.normGroup.setTitle(_translate("Form", "Normalization"))
self.normSubtractRadio.setText(_translate("Form", "Subtract"))
self.normDivideRadio.setText(_translate("Form", "Divide"))
self.label_5.setText(_translate("Form", "Operation:"))
self.label_3.setText(_translate("Form", "Mean:"))
self.label_4.setText(_translate("Form", "Blur:"))
self.normROICheck.setText(_translate("Form", "ROI"))
self.label_8.setText(_translate("Form", "X"))
self.label_9.setText(_translate("Form", "Y"))
self.label_10.setText(_translate("Form", "T"))
self.normOffRadio.setText(_translate("Form", "Off"))
self.normTimeRangeCheck.setText(_translate("Form", "Time range"))
self.normFrameCheck.setText(_translate("Form", "Frame"))
from ..widgets.HistogramLUTWidget import HistogramLUTWidget
from ..widgets.PlotWidget import PlotWidget
from ..widgets.GraphicsView import GraphicsView
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/imageview/ImageViewTemplate_pyside.py | .py | 8,928 | 155 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ImageViewTemplate.ui'
#
# Created: Thu May 1 15:20:42 2014
# by: pyside-uic 0.2.15 running on PySide 1.2.1
#
# 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(726, 588)
self.gridLayout_3 = QtGui.QGridLayout(Form)
self.gridLayout_3.setContentsMargins(0, 0, 0, 0)
self.gridLayout_3.setSpacing(0)
self.gridLayout_3.setObjectName("gridLayout_3")
self.splitter = QtGui.QSplitter(Form)
self.splitter.setOrientation(QtCore.Qt.Vertical)
self.splitter.setObjectName("splitter")
self.layoutWidget = QtGui.QWidget(self.splitter)
self.layoutWidget.setObjectName("layoutWidget")
self.gridLayout = QtGui.QGridLayout(self.layoutWidget)
self.gridLayout.setSpacing(0)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setObjectName("gridLayout")
self.graphicsView = GraphicsView(self.layoutWidget)
self.graphicsView.setObjectName("graphicsView")
self.gridLayout.addWidget(self.graphicsView, 0, 0, 2, 1)
self.histogram = HistogramLUTWidget(self.layoutWidget)
self.histogram.setObjectName("histogram")
self.gridLayout.addWidget(self.histogram, 0, 1, 1, 2)
self.roiBtn = QtGui.QPushButton(self.layoutWidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(1)
sizePolicy.setHeightForWidth(self.roiBtn.sizePolicy().hasHeightForWidth())
self.roiBtn.setSizePolicy(sizePolicy)
self.roiBtn.setCheckable(True)
self.roiBtn.setObjectName("roiBtn")
self.gridLayout.addWidget(self.roiBtn, 1, 1, 1, 1)
self.menuBtn = QtGui.QPushButton(self.layoutWidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(1)
sizePolicy.setHeightForWidth(self.menuBtn.sizePolicy().hasHeightForWidth())
self.menuBtn.setSizePolicy(sizePolicy)
self.menuBtn.setObjectName("menuBtn")
self.gridLayout.addWidget(self.menuBtn, 1, 2, 1, 1)
self.roiPlot = PlotWidget(self.splitter)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.roiPlot.sizePolicy().hasHeightForWidth())
self.roiPlot.setSizePolicy(sizePolicy)
self.roiPlot.setMinimumSize(QtCore.QSize(0, 40))
self.roiPlot.setObjectName("roiPlot")
self.gridLayout_3.addWidget(self.splitter, 0, 0, 1, 1)
self.normGroup = QtGui.QGroupBox(Form)
self.normGroup.setObjectName("normGroup")
self.gridLayout_2 = QtGui.QGridLayout(self.normGroup)
self.gridLayout_2.setContentsMargins(0, 0, 0, 0)
self.gridLayout_2.setSpacing(0)
self.gridLayout_2.setObjectName("gridLayout_2")
self.normSubtractRadio = QtGui.QRadioButton(self.normGroup)
self.normSubtractRadio.setObjectName("normSubtractRadio")
self.gridLayout_2.addWidget(self.normSubtractRadio, 0, 2, 1, 1)
self.normDivideRadio = QtGui.QRadioButton(self.normGroup)
self.normDivideRadio.setChecked(False)
self.normDivideRadio.setObjectName("normDivideRadio")
self.gridLayout_2.addWidget(self.normDivideRadio, 0, 1, 1, 1)
self.label_5 = QtGui.QLabel(self.normGroup)
font = QtGui.QFont()
font.setWeight(75)
font.setBold(True)
self.label_5.setFont(font)
self.label_5.setObjectName("label_5")
self.gridLayout_2.addWidget(self.label_5, 0, 0, 1, 1)
self.label_3 = QtGui.QLabel(self.normGroup)
font = QtGui.QFont()
font.setWeight(75)
font.setBold(True)
self.label_3.setFont(font)
self.label_3.setObjectName("label_3")
self.gridLayout_2.addWidget(self.label_3, 1, 0, 1, 1)
self.label_4 = QtGui.QLabel(self.normGroup)
font = QtGui.QFont()
font.setWeight(75)
font.setBold(True)
self.label_4.setFont(font)
self.label_4.setObjectName("label_4")
self.gridLayout_2.addWidget(self.label_4, 2, 0, 1, 1)
self.normROICheck = QtGui.QCheckBox(self.normGroup)
self.normROICheck.setObjectName("normROICheck")
self.gridLayout_2.addWidget(self.normROICheck, 1, 1, 1, 1)
self.normXBlurSpin = QtGui.QDoubleSpinBox(self.normGroup)
self.normXBlurSpin.setObjectName("normXBlurSpin")
self.gridLayout_2.addWidget(self.normXBlurSpin, 2, 2, 1, 1)
self.label_8 = QtGui.QLabel(self.normGroup)
self.label_8.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_8.setObjectName("label_8")
self.gridLayout_2.addWidget(self.label_8, 2, 1, 1, 1)
self.label_9 = QtGui.QLabel(self.normGroup)
self.label_9.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_9.setObjectName("label_9")
self.gridLayout_2.addWidget(self.label_9, 2, 3, 1, 1)
self.normYBlurSpin = QtGui.QDoubleSpinBox(self.normGroup)
self.normYBlurSpin.setObjectName("normYBlurSpin")
self.gridLayout_2.addWidget(self.normYBlurSpin, 2, 4, 1, 1)
self.label_10 = QtGui.QLabel(self.normGroup)
self.label_10.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_10.setObjectName("label_10")
self.gridLayout_2.addWidget(self.label_10, 2, 5, 1, 1)
self.normOffRadio = QtGui.QRadioButton(self.normGroup)
self.normOffRadio.setChecked(True)
self.normOffRadio.setObjectName("normOffRadio")
self.gridLayout_2.addWidget(self.normOffRadio, 0, 3, 1, 1)
self.normTimeRangeCheck = QtGui.QCheckBox(self.normGroup)
self.normTimeRangeCheck.setObjectName("normTimeRangeCheck")
self.gridLayout_2.addWidget(self.normTimeRangeCheck, 1, 3, 1, 1)
self.normFrameCheck = QtGui.QCheckBox(self.normGroup)
self.normFrameCheck.setObjectName("normFrameCheck")
self.gridLayout_2.addWidget(self.normFrameCheck, 1, 2, 1, 1)
self.normTBlurSpin = QtGui.QDoubleSpinBox(self.normGroup)
self.normTBlurSpin.setObjectName("normTBlurSpin")
self.gridLayout_2.addWidget(self.normTBlurSpin, 2, 6, 1, 1)
self.gridLayout_3.addWidget(self.normGroup, 1, 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.roiBtn.setText(QtGui.QApplication.translate("Form", "ROI", None, QtGui.QApplication.UnicodeUTF8))
self.menuBtn.setText(QtGui.QApplication.translate("Form", "Menu", None, QtGui.QApplication.UnicodeUTF8))
self.normGroup.setTitle(QtGui.QApplication.translate("Form", "Normalization", None, QtGui.QApplication.UnicodeUTF8))
self.normSubtractRadio.setText(QtGui.QApplication.translate("Form", "Subtract", None, QtGui.QApplication.UnicodeUTF8))
self.normDivideRadio.setText(QtGui.QApplication.translate("Form", "Divide", None, QtGui.QApplication.UnicodeUTF8))
self.label_5.setText(QtGui.QApplication.translate("Form", "Operation:", None, QtGui.QApplication.UnicodeUTF8))
self.label_3.setText(QtGui.QApplication.translate("Form", "Mean:", None, QtGui.QApplication.UnicodeUTF8))
self.label_4.setText(QtGui.QApplication.translate("Form", "Blur:", None, QtGui.QApplication.UnicodeUTF8))
self.normROICheck.setText(QtGui.QApplication.translate("Form", "ROI", None, QtGui.QApplication.UnicodeUTF8))
self.label_8.setText(QtGui.QApplication.translate("Form", "X", None, QtGui.QApplication.UnicodeUTF8))
self.label_9.setText(QtGui.QApplication.translate("Form", "Y", None, QtGui.QApplication.UnicodeUTF8))
self.label_10.setText(QtGui.QApplication.translate("Form", "T", None, QtGui.QApplication.UnicodeUTF8))
self.normOffRadio.setText(QtGui.QApplication.translate("Form", "Off", None, QtGui.QApplication.UnicodeUTF8))
self.normTimeRangeCheck.setText(QtGui.QApplication.translate("Form", "Time range", None, QtGui.QApplication.UnicodeUTF8))
self.normFrameCheck.setText(QtGui.QApplication.translate("Form", "Frame", None, QtGui.QApplication.UnicodeUTF8))
from ..widgets.HistogramLUTWidget import HistogramLUTWidget
from ..widgets.GraphicsView import GraphicsView
from ..widgets.PlotWidget import PlotWidget
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/imageview/tests/test_imageview.py | .py | 233 | 13 | import pyqtgraph as pg
import numpy as np
app = pg.mkQApp()
def test_nan_image():
img = np.ones((10,10))
img[0,0] = np.nan
v = pg.image(img)
v.imageItem.getHistogram()
app.processEvents()
v.window().close()
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/GraphicsScene/mouseEvents.py | .py | 14,192 | 380 | from ..Point import Point
from ..Qt import QtCore, QtGui
import weakref
from .. import ptime as ptime
class MouseDragEvent(object):
"""
Instances of this class are delivered to items in a :class:`GraphicsScene <pyqtgraph.GraphicsScene>` via their mouseDragEvent() method when the item is being mouse-dragged.
"""
def __init__(self, moveEvent, pressEvent, lastEvent, start=False, finish=False):
self.start = start
self.finish = finish
self.accepted = False
self.currentItem = None
self._buttonDownScenePos = {}
self._buttonDownScreenPos = {}
for btn in [QtCore.Qt.LeftButton, QtCore.Qt.MidButton, QtCore.Qt.RightButton]:
self._buttonDownScenePos[int(btn)] = moveEvent.buttonDownScenePos(btn)
self._buttonDownScreenPos[int(btn)] = moveEvent.buttonDownScreenPos(btn)
self._scenePos = moveEvent.scenePos()
self._screenPos = moveEvent.screenPos()
if lastEvent is None:
self._lastScenePos = pressEvent.scenePos()
self._lastScreenPos = pressEvent.screenPos()
else:
self._lastScenePos = lastEvent.scenePos()
self._lastScreenPos = lastEvent.screenPos()
self._buttons = moveEvent.buttons()
self._button = pressEvent.button()
self._modifiers = moveEvent.modifiers()
self.acceptedItem = None
def accept(self):
"""An item should call this method if it can handle the event. This will prevent the event being delivered to any other items."""
self.accepted = True
self.acceptedItem = self.currentItem
def ignore(self):
"""An item should call this method if it cannot handle the event. This will allow the event to be delivered to other items."""
self.accepted = False
def isAccepted(self):
return self.accepted
def scenePos(self):
"""Return the current scene position of the mouse."""
return Point(self._scenePos)
def screenPos(self):
"""Return the current screen position (pixels relative to widget) of the mouse."""
return Point(self._screenPos)
def buttonDownScenePos(self, btn=None):
"""
Return the scene position of the mouse at the time *btn* was pressed.
If *btn* is omitted, then the button that initiated the drag is assumed.
"""
if btn is None:
btn = self.button()
return Point(self._buttonDownScenePos[int(btn)])
def buttonDownScreenPos(self, btn=None):
"""
Return the screen position (pixels relative to widget) of the mouse at the time *btn* was pressed.
If *btn* is omitted, then the button that initiated the drag is assumed.
"""
if btn is None:
btn = self.button()
return Point(self._buttonDownScreenPos[int(btn)])
def lastScenePos(self):
"""
Return the scene position of the mouse immediately prior to this event.
"""
return Point(self._lastScenePos)
def lastScreenPos(self):
"""
Return the screen position of the mouse immediately prior to this event.
"""
return Point(self._lastScreenPos)
def buttons(self):
"""
Return the buttons currently pressed on the mouse.
(see QGraphicsSceneMouseEvent::buttons in the Qt documentation)
"""
return self._buttons
def button(self):
"""Return the button that initiated the drag (may be different from the buttons currently pressed)
(see QGraphicsSceneMouseEvent::button in the Qt documentation)
"""
return self._button
def pos(self):
"""
Return the current position of the mouse in the coordinate system of the item
that the event was delivered to.
"""
return Point(self.currentItem.mapFromScene(self._scenePos))
def lastPos(self):
"""
Return the previous position of the mouse in the coordinate system of the item
that the event was delivered to.
"""
return Point(self.currentItem.mapFromScene(self._lastScenePos))
def buttonDownPos(self, btn=None):
"""
Return the position of the mouse at the time the drag was initiated
in the coordinate system of the item that the event was delivered to.
"""
if btn is None:
btn = self.button()
return Point(self.currentItem.mapFromScene(self._buttonDownScenePos[int(btn)]))
def isStart(self):
"""Returns True if this event is the first since a drag was initiated."""
return self.start
def isFinish(self):
"""Returns False if this is the last event in a drag. Note that this
event will have the same position as the previous one."""
return self.finish
def __repr__(self):
if self.currentItem is None:
lp = self._lastScenePos
p = self._scenePos
else:
lp = self.lastPos()
p = self.pos()
return "<MouseDragEvent (%g,%g)->(%g,%g) buttons=%d start=%s finish=%s>" % (lp.x(), lp.y(), p.x(), p.y(), int(self.buttons()), str(self.isStart()), str(self.isFinish()))
def modifiers(self):
"""Return any keyboard modifiers currently pressed.
(see QGraphicsSceneMouseEvent::modifiers in the Qt documentation)
"""
return self._modifiers
class MouseClickEvent(object):
"""
Instances of this class are delivered to items in a :class:`GraphicsScene <pyqtgraph.GraphicsScene>` via their mouseClickEvent() method when the item is clicked.
"""
def __init__(self, pressEvent, double=False):
self.accepted = False
self.currentItem = None
self._double = double
self._scenePos = pressEvent.scenePos()
self._screenPos = pressEvent.screenPos()
self._button = pressEvent.button()
self._buttons = pressEvent.buttons()
self._modifiers = pressEvent.modifiers()
self._time = ptime.time()
self.acceptedItem = None
def accept(self):
"""An item should call this method if it can handle the event. This will prevent the event being delivered to any other items."""
self.accepted = True
self.acceptedItem = self.currentItem
def ignore(self):
"""An item should call this method if it cannot handle the event. This will allow the event to be delivered to other items."""
self.accepted = False
def isAccepted(self):
return self.accepted
def scenePos(self):
"""Return the current scene position of the mouse."""
return Point(self._scenePos)
def screenPos(self):
"""Return the current screen position (pixels relative to widget) of the mouse."""
return Point(self._screenPos)
def buttons(self):
"""
Return the buttons currently pressed on the mouse.
(see QGraphicsSceneMouseEvent::buttons in the Qt documentation)
"""
return self._buttons
def button(self):
"""Return the mouse button that generated the click event.
(see QGraphicsSceneMouseEvent::button in the Qt documentation)
"""
return self._button
def double(self):
"""Return True if this is a double-click."""
return self._double
def pos(self):
"""
Return the current position of the mouse in the coordinate system of the item
that the event was delivered to.
"""
return Point(self.currentItem.mapFromScene(self._scenePos))
def lastPos(self):
"""
Return the previous position of the mouse in the coordinate system of the item
that the event was delivered to.
"""
return Point(self.currentItem.mapFromScene(self._lastScenePos))
def modifiers(self):
"""Return any keyboard modifiers currently pressed.
(see QGraphicsSceneMouseEvent::modifiers in the Qt documentation)
"""
return self._modifiers
def __repr__(self):
try:
if self.currentItem is None:
p = self._scenePos
else:
p = self.pos()
return "<MouseClickEvent (%g,%g) button=%d>" % (p.x(), p.y(), int(self.button()))
except:
return "<MouseClickEvent button=%d>" % (int(self.button()))
def time(self):
return self._time
class HoverEvent(object):
"""
Instances of this class are delivered to items in a :class:`GraphicsScene <pyqtgraph.GraphicsScene>` via their hoverEvent() method when the mouse is hovering over the item.
This event class both informs items that the mouse cursor is nearby and allows items to
communicate with one another about whether each item will accept *potential* mouse events.
It is common for multiple overlapping items to receive hover events and respond by changing
their appearance. This can be misleading to the user since, in general, only one item will
respond to mouse events. To avoid this, items make calls to event.acceptClicks(button)
and/or acceptDrags(button).
Each item may make multiple calls to acceptClicks/Drags, each time for a different button.
If the method returns True, then the item is guaranteed to be
the recipient of the claimed event IF the user presses the specified mouse button before
moving. If claimEvent returns False, then this item is guaranteed NOT to get the specified
event (because another has already claimed it) and the item should change its appearance
accordingly.
event.isEnter() returns True if the mouse has just entered the item's shape;
event.isExit() returns True if the mouse has just left.
"""
def __init__(self, moveEvent, acceptable):
self.enter = False
self.acceptable = acceptable
self.exit = False
self.__clickItems = weakref.WeakValueDictionary()
self.__dragItems = weakref.WeakValueDictionary()
self.currentItem = None
if moveEvent is not None:
self._scenePos = moveEvent.scenePos()
self._screenPos = moveEvent.screenPos()
self._lastScenePos = moveEvent.lastScenePos()
self._lastScreenPos = moveEvent.lastScreenPos()
self._buttons = moveEvent.buttons()
self._modifiers = moveEvent.modifiers()
else:
self.exit = True
def isEnter(self):
"""Returns True if the mouse has just entered the item's shape"""
return self.enter
def isExit(self):
"""Returns True if the mouse has just exited the item's shape"""
return self.exit
def acceptClicks(self, button):
"""Inform the scene that the item (that the event was delivered to)
would accept a mouse click event if the user were to click before
moving the mouse again.
Returns True if the request is successful, otherwise returns False (indicating
that some other item would receive an incoming click).
"""
if not self.acceptable:
return False
if button not in self.__clickItems:
self.__clickItems[button] = self.currentItem
return True
return False
def acceptDrags(self, button):
"""Inform the scene that the item (that the event was delivered to)
would accept a mouse drag event if the user were to drag before
the next hover event.
Returns True if the request is successful, otherwise returns False (indicating
that some other item would receive an incoming drag event).
"""
if not self.acceptable:
return False
if button not in self.__dragItems:
self.__dragItems[button] = self.currentItem
return True
return False
def scenePos(self):
"""Return the current scene position of the mouse."""
return Point(self._scenePos)
def screenPos(self):
"""Return the current screen position of the mouse."""
return Point(self._screenPos)
def lastScenePos(self):
"""Return the previous scene position of the mouse."""
return Point(self._lastScenePos)
def lastScreenPos(self):
"""Return the previous screen position of the mouse."""
return Point(self._lastScreenPos)
def buttons(self):
"""
Return the buttons currently pressed on the mouse.
(see QGraphicsSceneMouseEvent::buttons in the Qt documentation)
"""
return self._buttons
def pos(self):
"""
Return the current position of the mouse in the coordinate system of the item
that the event was delivered to.
"""
return Point(self.currentItem.mapFromScene(self._scenePos))
def lastPos(self):
"""
Return the previous position of the mouse in the coordinate system of the item
that the event was delivered to.
"""
return Point(self.currentItem.mapFromScene(self._lastScenePos))
def __repr__(self):
if self.exit:
return "<HoverEvent exit=True>"
if self.currentItem is None:
lp = self._lastScenePos
p = self._scenePos
else:
lp = self.lastPos()
p = self.pos()
return "<HoverEvent (%g,%g)->(%g,%g) buttons=%d enter=%s exit=%s>" % (lp.x(), lp.y(), p.x(), p.y(), int(self.buttons()), str(self.isEnter()), str(self.isExit()))
def modifiers(self):
"""Return any keyboard modifiers currently pressed.
(see QGraphicsSceneMouseEvent::modifiers in the Qt documentation)
"""
return self._modifiers
def clickItems(self):
return self.__clickItems
def dragItems(self):
return self.__dragItems
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/GraphicsScene/exportDialogTemplate_pyside.py | .py | 3,149 | 64 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './pyqtgraph/GraphicsScene/exportDialogTemplate.ui'
#
# Created: Mon Dec 23 10:10:53 2013
# by: pyside-uic 0.2.14 running on PySide 1.1.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(241, 367)
self.gridLayout = QtGui.QGridLayout(Form)
self.gridLayout.setSpacing(0)
self.gridLayout.setObjectName("gridLayout")
self.label = QtGui.QLabel(Form)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 0, 0, 1, 3)
self.itemTree = QtGui.QTreeWidget(Form)
self.itemTree.setObjectName("itemTree")
self.itemTree.headerItem().setText(0, "1")
self.itemTree.header().setVisible(False)
self.gridLayout.addWidget(self.itemTree, 1, 0, 1, 3)
self.label_2 = QtGui.QLabel(Form)
self.label_2.setObjectName("label_2")
self.gridLayout.addWidget(self.label_2, 2, 0, 1, 3)
self.formatList = QtGui.QListWidget(Form)
self.formatList.setObjectName("formatList")
self.gridLayout.addWidget(self.formatList, 3, 0, 1, 3)
self.exportBtn = QtGui.QPushButton(Form)
self.exportBtn.setObjectName("exportBtn")
self.gridLayout.addWidget(self.exportBtn, 6, 1, 1, 1)
self.closeBtn = QtGui.QPushButton(Form)
self.closeBtn.setObjectName("closeBtn")
self.gridLayout.addWidget(self.closeBtn, 6, 2, 1, 1)
self.paramTree = ParameterTree(Form)
self.paramTree.setObjectName("paramTree")
self.paramTree.headerItem().setText(0, "1")
self.paramTree.header().setVisible(False)
self.gridLayout.addWidget(self.paramTree, 5, 0, 1, 3)
self.label_3 = QtGui.QLabel(Form)
self.label_3.setObjectName("label_3")
self.gridLayout.addWidget(self.label_3, 4, 0, 1, 3)
self.copyBtn = QtGui.QPushButton(Form)
self.copyBtn.setObjectName("copyBtn")
self.gridLayout.addWidget(self.copyBtn, 6, 0, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(QtGui.QApplication.translate("Form", "Export", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("Form", "Item to export:", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("Form", "Export format", None, QtGui.QApplication.UnicodeUTF8))
self.exportBtn.setText(QtGui.QApplication.translate("Form", "Export", None, QtGui.QApplication.UnicodeUTF8))
self.closeBtn.setText(QtGui.QApplication.translate("Form", "Close", None, QtGui.QApplication.UnicodeUTF8))
self.label_3.setText(QtGui.QApplication.translate("Form", "Export options", None, QtGui.QApplication.UnicodeUTF8))
self.copyBtn.setText(QtGui.QApplication.translate("Form", "Copy", None, QtGui.QApplication.UnicodeUTF8))
from ..parametertree import ParameterTree
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/GraphicsScene/__init__.py | .py | 29 | 2 | from .GraphicsScene import *
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/GraphicsScene/GraphicsScene.py | .py | 23,994 | 537 | # -*- coding: utf-8 -*-
import weakref
import warnings
from ..Qt import QtCore, QtGui
from ..Point import Point
from .. import functions as fn
from .. import ptime as ptime
from .mouseEvents import *
from .. import debug as debug
if hasattr(QtCore, 'PYQT_VERSION'):
try:
import sip
HAVE_SIP = True
except ImportError:
HAVE_SIP = False
else:
HAVE_SIP = False
__all__ = ['GraphicsScene']
class GraphicsScene(QtGui.QGraphicsScene):
"""
Extension of QGraphicsScene that implements a complete, parallel mouse event system.
(It would have been preferred to just alter the way QGraphicsScene creates and delivers
events, but this turned out to be impossible because the constructor for QGraphicsMouseEvent
is private)
* Generates MouseClicked events in addition to the usual press/move/release events.
(This works around a problem where it is impossible to have one item respond to a
drag if another is watching for a click.)
* Adjustable radius around click that will catch objects so you don't have to click *exactly* over small/thin objects
* Global context menu--if an item implements a context menu, then its parent(s) may also add items to the menu.
* Allows items to decide _before_ a mouse click which item will be the recipient of mouse events.
This lets us indicate unambiguously to the user which item they are about to click/drag on
* Eats mouseMove events that occur too soon after a mouse press.
* Reimplements items() and itemAt() to circumvent PyQt bug
====================== ==================================================================
**Signals**
sigMouseClicked(event) Emitted when the mouse is clicked over the scene. Use ev.pos() to
get the click position relative to the item that was clicked on,
or ev.scenePos() to get the click position in scene coordinates.
See :class:`pyqtgraph.GraphicsScene.MouseClickEvent`.
sigMouseMoved(pos) Emitted when the mouse cursor moves over the scene. The position
is given in scene coordinates.
sigMouseHover(items) Emitted when the mouse is moved over the scene. Items is a list
of items under the cursor.
====================== ==================================================================
Mouse interaction is as follows:
1) Every time the mouse moves, the scene delivers both the standard hoverEnter/Move/LeaveEvents
as well as custom HoverEvents.
2) Items are sent HoverEvents in Z-order and each item may optionally call event.acceptClicks(button),
acceptDrags(button) or both. If this method call returns True, this informs the item that _if_
the user clicks/drags the specified mouse button, the item is guaranteed to be the
recipient of click/drag events (the item may wish to change its appearance to indicate this).
If the call to acceptClicks/Drags returns False, then the item is guaranteed to *not* receive
the requested event (because another item has already accepted it).
3) If the mouse is clicked, a mousePressEvent is generated as usual. If any items accept this press event, then
No click/drag events will be generated and mouse interaction proceeds as defined by Qt. This allows
items to function properly if they are expecting the usual press/move/release sequence of events.
(It is recommended that items do NOT accept press events, and instead use click/drag events)
Note: The default implementation of QGraphicsItem.mousePressEvent will *accept* the event if the
item is has its Selectable or Movable flags enabled. You may need to override this behavior.
4) If no item accepts the mousePressEvent, then the scene will begin delivering mouseDrag and/or mouseClick events.
If the mouse is moved a sufficient distance (or moved slowly enough) before the button is released,
then a mouseDragEvent is generated.
If no drag events are generated before the button is released, then a mouseClickEvent is generated.
5) Click/drag events are delivered to the item that called acceptClicks/acceptDrags on the HoverEvent
in step 1. If no such items exist, then the scene attempts to deliver the events to items near the event.
ClickEvents may be delivered in this way even if no
item originally claimed it could accept the click. DragEvents may only be delivered this way if it is the initial
move in a drag.
"""
sigMouseHover = QtCore.Signal(object) ## emits a list of objects hovered over
sigMouseMoved = QtCore.Signal(object) ## emits position of mouse on every move
sigMouseClicked = QtCore.Signal(object) ## emitted when mouse is clicked. Check for event.isAccepted() to see whether the event has already been acted on.
sigPrepareForPaint = QtCore.Signal() ## emitted immediately before the scene is about to be rendered
_addressCache = weakref.WeakValueDictionary()
ExportDirectory = None
@classmethod
def registerObject(cls, obj):
warnings.warn(
"'registerObject' is deprecated and does nothing.",
DeprecationWarning, stacklevel=2
)
def __init__(self, clickRadius=2, moveDistance=5, parent=None):
QtGui.QGraphicsScene.__init__(self, parent)
self.setClickRadius(clickRadius)
self.setMoveDistance(moveDistance)
self.exportDirectory = None
self.clickEvents = []
self.dragButtons = []
self.mouseGrabber = None
self.dragItem = None
self.lastDrag = None
self.hoverItems = weakref.WeakKeyDictionary()
self.lastHoverEvent = None
self.minDragTime = 0.5 # drags shorter than 0.5 sec are interpreted as clicks
self.contextMenu = [QtGui.QAction("Export...", self)]
self.contextMenu[0].triggered.connect(self.showExportDialog)
self.exportDialog = None
def render(self, *args):
self.prepareForPaint()
return QtGui.QGraphicsScene.render(self, *args)
def prepareForPaint(self):
"""Called before every render. This method will inform items that the scene is about to
be rendered by emitting sigPrepareForPaint.
This allows items to delay expensive processing until they know a paint will be required."""
self.sigPrepareForPaint.emit()
def setClickRadius(self, r):
"""
Set the distance away from mouse clicks to search for interacting items.
When clicking, the scene searches first for items that directly intersect the click position
followed by any other items that are within a rectangle that extends r pixels away from the
click position.
"""
self._clickRadius = r
def setMoveDistance(self, d):
"""
Set the distance the mouse must move after a press before mouseMoveEvents will be delivered.
This ensures that clicks with a small amount of movement are recognized as clicks instead of
drags.
"""
self._moveDistance = d
def mousePressEvent(self, ev):
QtGui.QGraphicsScene.mousePressEvent(self, ev)
if self.mouseGrabberItem() is None: ## nobody claimed press; we are free to generate drag/click events
if self.lastHoverEvent is not None:
# If the mouse has moved since the last hover event, send a new one.
# This can happen if a context menu is open while the mouse is moving.
if ev.scenePos() != self.lastHoverEvent.scenePos():
self.sendHoverEvents(ev)
self.clickEvents.append(MouseClickEvent(ev))
## set focus on the topmost focusable item under this click
items = self.items(ev.scenePos())
for i in items:
if i.isEnabled() and i.isVisible() and int(i.flags() & i.ItemIsFocusable) > 0:
i.setFocus(QtCore.Qt.MouseFocusReason)
break
def mouseMoveEvent(self, ev):
self.sigMouseMoved.emit(ev.scenePos())
## First allow QGraphicsScene to deliver hoverEnter/Move/ExitEvents
QtGui.QGraphicsScene.mouseMoveEvent(self, ev)
## Next deliver our own HoverEvents
self.sendHoverEvents(ev)
if int(ev.buttons()) != 0: ## button is pressed; send mouseMoveEvents and mouseDragEvents
QtGui.QGraphicsScene.mouseMoveEvent(self, ev)
if self.mouseGrabberItem() is None:
now = ptime.time()
init = False
## keep track of which buttons are involved in dragging
for btn in [QtCore.Qt.LeftButton, QtCore.Qt.MidButton, QtCore.Qt.RightButton]:
if int(ev.buttons() & btn) == 0:
continue
if int(btn) not in self.dragButtons: ## see if we've dragged far enough yet
cev = [e for e in self.clickEvents if int(e.button()) == int(btn)]
if cev:
cev = cev[0]
dist = Point(ev.scenePos() - cev.scenePos()).length()
if dist == 0 or (dist < self._moveDistance and now - cev.time() < self.minDragTime):
continue
init = init or (len(self.dragButtons) == 0) ## If this is the first button to be dragged, then init=True
self.dragButtons.append(int(btn))
## If we have dragged buttons, deliver a drag event
if len(self.dragButtons) > 0:
if self.sendDragEvent(ev, init=init):
ev.accept()
def leaveEvent(self, ev): ## inform items that mouse is gone
if len(self.dragButtons) == 0:
self.sendHoverEvents(ev, exitOnly=True)
def mouseReleaseEvent(self, ev):
if self.mouseGrabberItem() is None:
if ev.button() in self.dragButtons:
if self.sendDragEvent(ev, final=True):
#print "sent drag event"
ev.accept()
self.dragButtons.remove(ev.button())
else:
cev = [e for e in self.clickEvents if int(e.button()) == int(ev.button())]
if cev:
if self.sendClickEvent(cev[0]):
#print "sent click event"
ev.accept()
self.clickEvents.remove(cev[0])
if int(ev.buttons()) == 0:
self.dragItem = None
self.dragButtons = []
self.clickEvents = []
self.lastDrag = None
QtGui.QGraphicsScene.mouseReleaseEvent(self, ev)
self.sendHoverEvents(ev) ## let items prepare for next click/drag
def mouseDoubleClickEvent(self, ev):
QtGui.QGraphicsScene.mouseDoubleClickEvent(self, ev)
if self.mouseGrabberItem() is None: ## nobody claimed press; we are free to generate drag/click events
self.clickEvents.append(MouseClickEvent(ev, double=True))
def sendHoverEvents(self, ev, exitOnly=False):
## if exitOnly, then just inform all previously hovered items that the mouse has left.
if exitOnly:
acceptable=False
items = []
event = HoverEvent(None, acceptable)
else:
acceptable = int(ev.buttons()) == 0 ## if we are in mid-drag, do not allow items to accept the hover event.
event = HoverEvent(ev, acceptable)
items = self.itemsNearEvent(event, hoverable=True)
self.sigMouseHover.emit(items)
prevItems = list(self.hoverItems.keys())
for item in items:
if hasattr(item, 'hoverEvent'):
event.currentItem = item
if item not in self.hoverItems:
self.hoverItems[item] = None
event.enter = True
else:
prevItems.remove(item)
event.enter = False
try:
item.hoverEvent(event)
except:
debug.printExc("Error sending hover event:")
event.enter = False
event.exit = True
#print "hover exit items:", prevItems
for item in prevItems:
event.currentItem = item
try:
if item.scene() is self:
item.hoverEvent(event)
except:
debug.printExc("Error sending hover exit event:")
finally:
del self.hoverItems[item]
# Update last hover event unless:
# - mouse is dragging (move+buttons); in this case we want the dragged
# item to continue receiving events until the drag is over
# - event is not a mouse event (QEvent.Leave sometimes appears here)
if (ev.type() == ev.GraphicsSceneMousePress or
(ev.type() == ev.GraphicsSceneMouseMove and int(ev.buttons()) == 0)):
self.lastHoverEvent = event ## save this so we can ask about accepted events later.
def sendDragEvent(self, ev, init=False, final=False):
## Send a MouseDragEvent to the current dragItem or to
## items near the beginning of the drag
event = MouseDragEvent(ev, self.clickEvents[0], self.lastDrag, start=init, finish=final)
#print "dragEvent: init=", init, 'final=', final, 'self.dragItem=', self.dragItem
if init and self.dragItem is None:
if self.lastHoverEvent is not None:
acceptedItem = self.lastHoverEvent.dragItems().get(event.button(), None)
else:
acceptedItem = None
if acceptedItem is not None and acceptedItem.scene() is self:
#print "Drag -> pre-selected item:", acceptedItem
self.dragItem = acceptedItem
event.currentItem = self.dragItem
try:
self.dragItem.mouseDragEvent(event)
except:
debug.printExc("Error sending drag event:")
else:
#print "drag -> new item"
for item in self.itemsNearEvent(event):
#print "check item:", item
if not item.isVisible() or not item.isEnabled():
continue
if hasattr(item, 'mouseDragEvent'):
event.currentItem = item
try:
item.mouseDragEvent(event)
except:
debug.printExc("Error sending drag event:")
if event.isAccepted():
#print " --> accepted"
self.dragItem = item
if int(item.flags() & item.ItemIsFocusable) > 0:
item.setFocus(QtCore.Qt.MouseFocusReason)
break
elif self.dragItem is not None:
event.currentItem = self.dragItem
try:
self.dragItem.mouseDragEvent(event)
except:
debug.printExc("Error sending hover exit event:")
self.lastDrag = event
return event.isAccepted()
def sendClickEvent(self, ev):
## if we are in mid-drag, click events may only go to the dragged item.
if self.dragItem is not None and hasattr(self.dragItem, 'mouseClickEvent'):
ev.currentItem = self.dragItem
self.dragItem.mouseClickEvent(ev)
## otherwise, search near the cursor
else:
if self.lastHoverEvent is not None:
acceptedItem = self.lastHoverEvent.clickItems().get(ev.button(), None)
else:
acceptedItem = None
if acceptedItem is not None:
ev.currentItem = acceptedItem
try:
acceptedItem.mouseClickEvent(ev)
except:
debug.printExc("Error sending click event:")
else:
for item in self.itemsNearEvent(ev):
if not item.isVisible() or not item.isEnabled():
continue
if hasattr(item, 'mouseClickEvent'):
ev.currentItem = item
try:
item.mouseClickEvent(ev)
except:
debug.printExc("Error sending click event:")
if ev.isAccepted():
if int(item.flags() & item.ItemIsFocusable) > 0:
item.setFocus(QtCore.Qt.MouseFocusReason)
break
self.sigMouseClicked.emit(ev)
return ev.isAccepted()
def items(self, *args):
items = QtGui.QGraphicsScene.items(self, *args)
return self.translateGraphicsItems(items)
def selectedItems(self, *args):
items = QtGui.QGraphicsScene.selectedItems(self, *args)
return self.translateGraphicsItems(items)
def itemAt(self, *args):
item = QtGui.QGraphicsScene.itemAt(self, *args)
return self.translateGraphicsItem(item)
def itemsNearEvent(self, event, selMode=QtCore.Qt.IntersectsItemShape, sortOrder=QtCore.Qt.DescendingOrder, hoverable=False):
"""
Return an iterator that iterates first through the items that directly intersect point (in Z order)
followed by any other items that are within the scene's click radius.
"""
#tr = self.getViewWidget(event.widget()).transform()
view = self.views()[0]
tr = view.viewportTransform()
r = self._clickRadius
rect = view.mapToScene(QtCore.QRect(0, 0, 2*r, 2*r)).boundingRect()
seen = set()
if hasattr(event, 'buttonDownScenePos'):
point = event.buttonDownScenePos()
else:
point = event.scenePos()
w = rect.width()
h = rect.height()
rgn = QtCore.QRectF(point.x()-w, point.y()-h, 2*w, 2*h)
#self.searchRect.setRect(rgn)
items = self.items(point, selMode, sortOrder, tr)
## remove items whose shape does not contain point (scene.items() apparently sucks at this)
items2 = []
for item in items:
if hoverable and not hasattr(item, 'hoverEvent'):
continue
if item.scene() is not self:
continue
shape = item.shape() # Note: default shape() returns boundingRect()
if shape is None:
continue
if shape.contains(item.mapFromScene(point)):
items2.append(item)
## Sort by descending Z-order (don't trust scene.itms() to do this either)
## use 'absolute' z value, which is the sum of all item/parent ZValues
def absZValue(item):
if item is None:
return 0
return item.zValue() + absZValue(item.parentItem())
items2.sort(key=absZValue, reverse=True)
return items2
#for item in items:
##seen.add(item)
#shape = item.mapToScene(item.shape())
#if not shape.contains(point):
#continue
#yield item
#for item in self.items(rgn, selMode, sortOrder, tr):
##if item not in seen:
#yield item
def getViewWidget(self):
return self.views()[0]
#def getViewWidget(self, widget):
### same pyqt bug -- mouseEvent.widget() doesn't give us the original python object.
### [[doesn't seem to work correctly]]
#if HAVE_SIP and isinstance(self, sip.wrapper):
#addr = sip.unwrapinstance(sip.cast(widget, QtGui.QWidget))
##print "convert", widget, addr
#for v in self.views():
#addr2 = sip.unwrapinstance(sip.cast(v, QtGui.QWidget))
##print " check:", v, addr2
#if addr2 == addr:
#return v
#else:
#return widget
def addParentContextMenus(self, item, menu, event):
"""
Can be called by any item in the scene to expand its context menu to include parent context menus.
Parents may implement getContextMenus to add new menus / actions to the existing menu.
getContextMenus must accept 1 argument (the event that generated the original menu) and
return a single QMenu or a list of QMenus.
The final menu will look like:
| Original Item 1
| Original Item 2
| ...
| Original Item N
| ------------------
| Parent Item 1
| Parent Item 2
| ...
| Grandparent Item 1
| ...
============== ==================================================
**Arguments:**
item The item that initially created the context menu
(This is probably the item making the call to this function)
menu The context menu being shown by the item
event The original event that triggered the menu to appear.
============== ==================================================
"""
menusToAdd = []
while item is not self:
item = item.parentItem()
if item is None:
item = self
if not hasattr(item, "getContextMenus"):
continue
subMenus = item.getContextMenus(event) or []
if isinstance(subMenus, list): ## so that some items (like FlowchartViewBox) can return multiple menus
menusToAdd.extend(subMenus)
else:
menusToAdd.append(subMenus)
if menusToAdd:
menu.addSeparator()
for m in menusToAdd:
if isinstance(m, QtGui.QMenu):
menu.addMenu(m)
elif isinstance(m, QtGui.QAction):
menu.addAction(m)
else:
raise Exception("Cannot add object %s (type=%s) to QMenu." % (str(m), str(type(m))))
return menu
def getContextMenus(self, event):
self.contextMenuItem = event.acceptedItem
return self.contextMenu
def showExportDialog(self):
if self.exportDialog is None:
from . import exportDialog
self.exportDialog = exportDialog.ExportDialog(self)
self.exportDialog.show(self.contextMenuItem)
@staticmethod
def translateGraphicsItem(item):
# This function is intended as a workaround for a problem with older
# versions of PyQt (< 4.9?), where methods returning 'QGraphicsItem *'
# lose the type of the QGraphicsObject subclasses and instead return
# generic QGraphicsItem wrappers.
if HAVE_SIP and isinstance(item, sip.wrapper):
obj = item.toGraphicsObject()
if obj is not None:
item = obj
return item
@staticmethod
def translateGraphicsItems(items):
return list(map(GraphicsScene.translateGraphicsItem, items))
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/GraphicsScene/exportDialogTemplate_pyqt5.py | .py | 2,846 | 65 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './pyqtgraph/GraphicsScene/exportDialogTemplate.ui'
#
# Created: Wed Mar 26 15:09:29 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(241, 367)
self.gridLayout = QtWidgets.QGridLayout(Form)
self.gridLayout.setSpacing(0)
self.gridLayout.setObjectName("gridLayout")
self.label = QtWidgets.QLabel(Form)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 0, 0, 1, 3)
self.itemTree = QtWidgets.QTreeWidget(Form)
self.itemTree.setObjectName("itemTree")
self.itemTree.headerItem().setText(0, "1")
self.itemTree.header().setVisible(False)
self.gridLayout.addWidget(self.itemTree, 1, 0, 1, 3)
self.label_2 = QtWidgets.QLabel(Form)
self.label_2.setObjectName("label_2")
self.gridLayout.addWidget(self.label_2, 2, 0, 1, 3)
self.formatList = QtWidgets.QListWidget(Form)
self.formatList.setObjectName("formatList")
self.gridLayout.addWidget(self.formatList, 3, 0, 1, 3)
self.exportBtn = QtWidgets.QPushButton(Form)
self.exportBtn.setObjectName("exportBtn")
self.gridLayout.addWidget(self.exportBtn, 6, 1, 1, 1)
self.closeBtn = QtWidgets.QPushButton(Form)
self.closeBtn.setObjectName("closeBtn")
self.gridLayout.addWidget(self.closeBtn, 6, 2, 1, 1)
self.paramTree = ParameterTree(Form)
self.paramTree.setObjectName("paramTree")
self.paramTree.headerItem().setText(0, "1")
self.paramTree.header().setVisible(False)
self.gridLayout.addWidget(self.paramTree, 5, 0, 1, 3)
self.label_3 = QtWidgets.QLabel(Form)
self.label_3.setObjectName("label_3")
self.gridLayout.addWidget(self.label_3, 4, 0, 1, 3)
self.copyBtn = QtWidgets.QPushButton(Form)
self.copyBtn.setObjectName("copyBtn")
self.gridLayout.addWidget(self.copyBtn, 6, 0, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Export"))
self.label.setText(_translate("Form", "Item to export:"))
self.label_2.setText(_translate("Form", "Export format"))
self.exportBtn.setText(_translate("Form", "Export"))
self.closeBtn.setText(_translate("Form", "Close"))
self.label_3.setText(_translate("Form", "Export options"))
self.copyBtn.setText(_translate("Form", "Copy"))
from ..parametertree import ParameterTree
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/GraphicsScene/exportDialogTemplate_pyside2.py | .py | 3,006 | 64 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'exportDialogTemplate.ui'
#
# Created: Sun Sep 18 19:19:58 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(241, 367)
self.gridLayout = QtWidgets.QGridLayout(Form)
self.gridLayout.setSpacing(0)
self.gridLayout.setObjectName("gridLayout")
self.label = QtWidgets.QLabel(Form)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 0, 0, 1, 3)
self.itemTree = QtWidgets.QTreeWidget(Form)
self.itemTree.setObjectName("itemTree")
self.itemTree.headerItem().setText(0, "1")
self.itemTree.header().setVisible(False)
self.gridLayout.addWidget(self.itemTree, 1, 0, 1, 3)
self.label_2 = QtWidgets.QLabel(Form)
self.label_2.setObjectName("label_2")
self.gridLayout.addWidget(self.label_2, 2, 0, 1, 3)
self.formatList = QtWidgets.QListWidget(Form)
self.formatList.setObjectName("formatList")
self.gridLayout.addWidget(self.formatList, 3, 0, 1, 3)
self.exportBtn = QtWidgets.QPushButton(Form)
self.exportBtn.setObjectName("exportBtn")
self.gridLayout.addWidget(self.exportBtn, 6, 1, 1, 1)
self.closeBtn = QtWidgets.QPushButton(Form)
self.closeBtn.setObjectName("closeBtn")
self.gridLayout.addWidget(self.closeBtn, 6, 2, 1, 1)
self.paramTree = ParameterTree(Form)
self.paramTree.setObjectName("paramTree")
self.paramTree.headerItem().setText(0, "1")
self.paramTree.header().setVisible(False)
self.gridLayout.addWidget(self.paramTree, 5, 0, 1, 3)
self.label_3 = QtWidgets.QLabel(Form)
self.label_3.setObjectName("label_3")
self.gridLayout.addWidget(self.label_3, 4, 0, 1, 3)
self.copyBtn = QtWidgets.QPushButton(Form)
self.copyBtn.setObjectName("copyBtn")
self.gridLayout.addWidget(self.copyBtn, 6, 0, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(QtWidgets.QApplication.translate("Form", "Export", None, -1))
self.label.setText(QtWidgets.QApplication.translate("Form", "Item to export:", None, -1))
self.label_2.setText(QtWidgets.QApplication.translate("Form", "Export format", None, -1))
self.exportBtn.setText(QtWidgets.QApplication.translate("Form", "Export", None, -1))
self.closeBtn.setText(QtWidgets.QApplication.translate("Form", "Close", None, -1))
self.label_3.setText(QtWidgets.QApplication.translate("Form", "Export options", None, -1))
self.copyBtn.setText(QtWidgets.QApplication.translate("Form", "Copy", None, -1))
from ..parametertree import ParameterTree
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/GraphicsScene/exportDialogTemplate_pyqt.py | .py | 3,351 | 78 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './pyqtgraph/GraphicsScene/exportDialogTemplate.ui'
#
# Created: Mon Dec 23 10:10:52 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(241, 367)
self.gridLayout = QtGui.QGridLayout(Form)
self.gridLayout.setSpacing(0)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.label = QtGui.QLabel(Form)
self.label.setObjectName(_fromUtf8("label"))
self.gridLayout.addWidget(self.label, 0, 0, 1, 3)
self.itemTree = QtGui.QTreeWidget(Form)
self.itemTree.setObjectName(_fromUtf8("itemTree"))
self.itemTree.headerItem().setText(0, _fromUtf8("1"))
self.itemTree.header().setVisible(False)
self.gridLayout.addWidget(self.itemTree, 1, 0, 1, 3)
self.label_2 = QtGui.QLabel(Form)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.gridLayout.addWidget(self.label_2, 2, 0, 1, 3)
self.formatList = QtGui.QListWidget(Form)
self.formatList.setObjectName(_fromUtf8("formatList"))
self.gridLayout.addWidget(self.formatList, 3, 0, 1, 3)
self.exportBtn = QtGui.QPushButton(Form)
self.exportBtn.setObjectName(_fromUtf8("exportBtn"))
self.gridLayout.addWidget(self.exportBtn, 6, 1, 1, 1)
self.closeBtn = QtGui.QPushButton(Form)
self.closeBtn.setObjectName(_fromUtf8("closeBtn"))
self.gridLayout.addWidget(self.closeBtn, 6, 2, 1, 1)
self.paramTree = ParameterTree(Form)
self.paramTree.setObjectName(_fromUtf8("paramTree"))
self.paramTree.headerItem().setText(0, _fromUtf8("1"))
self.paramTree.header().setVisible(False)
self.gridLayout.addWidget(self.paramTree, 5, 0, 1, 3)
self.label_3 = QtGui.QLabel(Form)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.gridLayout.addWidget(self.label_3, 4, 0, 1, 3)
self.copyBtn = QtGui.QPushButton(Form)
self.copyBtn.setObjectName(_fromUtf8("copyBtn"))
self.gridLayout.addWidget(self.copyBtn, 6, 0, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Export", None))
self.label.setText(_translate("Form", "Item to export:", None))
self.label_2.setText(_translate("Form", "Export format", None))
self.exportBtn.setText(_translate("Form", "Export", None))
self.closeBtn.setText(_translate("Form", "Close", None))
self.label_3.setText(_translate("Form", "Export options", None))
self.copyBtn.setText(_translate("Form", "Copy", None))
from ..parametertree import ParameterTree
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/GraphicsScene/exportDialog.py | .py | 5,839 | 160 | from ..Qt import QtCore, QtGui, QT_LIB
from .. import exporters as exporters
from .. import functions as fn
from ..graphicsItems.ViewBox import ViewBox
from ..graphicsItems.PlotItem import PlotItem
if QT_LIB == 'PySide':
from . import exportDialogTemplate_pyside as exportDialogTemplate
elif QT_LIB == 'PySide2':
from . import exportDialogTemplate_pyside2 as exportDialogTemplate
elif QT_LIB == 'PyQt5':
from . import exportDialogTemplate_pyqt5 as exportDialogTemplate
else:
from . import exportDialogTemplate_pyqt as exportDialogTemplate
class ExportDialog(QtGui.QWidget):
def __init__(self, scene):
QtGui.QWidget.__init__(self)
self.setVisible(False)
self.setWindowTitle("Export")
self.shown = False
self.currentExporter = None
self.scene = scene
self.exporterParameters = {}
self.selectBox = QtGui.QGraphicsRectItem()
self.selectBox.setPen(fn.mkPen('y', width=3, style=QtCore.Qt.DashLine))
self.selectBox.hide()
self.scene.addItem(self.selectBox)
self.ui = exportDialogTemplate.Ui_Form()
self.ui.setupUi(self)
self.ui.closeBtn.clicked.connect(self.close)
self.ui.exportBtn.clicked.connect(self.exportClicked)
self.ui.copyBtn.clicked.connect(self.copyClicked)
self.ui.itemTree.currentItemChanged.connect(self.exportItemChanged)
self.ui.formatList.currentItemChanged.connect(self.exportFormatChanged)
def show(self, item=None):
if item is not None:
## Select next exportable parent of the item originally clicked on
while not isinstance(item, ViewBox) and not isinstance(item, PlotItem) and item is not None:
item = item.parentItem()
## if this is a ViewBox inside a PlotItem, select the parent instead.
if isinstance(item, ViewBox) and isinstance(item.parentItem(), PlotItem):
item = item.parentItem()
self.updateItemList(select=item)
self.setVisible(True)
self.activateWindow()
self.raise_()
self.selectBox.setVisible(True)
if not self.shown:
self.shown = True
vcenter = self.scene.getViewWidget().geometry().center()
self.setGeometry(vcenter.x()-self.width()/2, vcenter.y()-self.height()/2, self.width(), self.height())
def updateItemList(self, select=None):
self.ui.itemTree.clear()
si = QtGui.QTreeWidgetItem(["Entire Scene"])
si.gitem = self.scene
self.ui.itemTree.addTopLevelItem(si)
self.ui.itemTree.setCurrentItem(si)
si.setExpanded(True)
for child in self.scene.items():
if child.parentItem() is None:
self.updateItemTree(child, si, select=select)
def updateItemTree(self, item, treeItem, select=None):
si = None
if isinstance(item, ViewBox):
si = QtGui.QTreeWidgetItem(['ViewBox'])
elif isinstance(item, PlotItem):
si = QtGui.QTreeWidgetItem(['Plot'])
if si is not None:
si.gitem = item
treeItem.addChild(si)
treeItem = si
if si.gitem is select:
self.ui.itemTree.setCurrentItem(si)
for ch in item.childItems():
self.updateItemTree(ch, treeItem, select=select)
def exportItemChanged(self, item, prev):
if item is None:
return
if item.gitem is self.scene:
newBounds = self.scene.views()[0].viewRect()
else:
newBounds = item.gitem.sceneBoundingRect()
self.selectBox.setRect(newBounds)
self.selectBox.show()
self.updateFormatList()
def updateFormatList(self):
current = self.ui.formatList.currentItem()
if current is not None:
current = str(current.text())
self.ui.formatList.clear()
self.exporterClasses = {}
gotCurrent = False
for exp in exporters.listExporters():
self.ui.formatList.addItem(exp.Name)
self.exporterClasses[exp.Name] = exp
if exp.Name == current:
self.ui.formatList.setCurrentRow(self.ui.formatList.count()-1)
gotCurrent = True
if not gotCurrent:
self.ui.formatList.setCurrentRow(0)
def exportFormatChanged(self, item, prev):
if item is None:
self.currentExporter = None
self.ui.paramTree.clear()
return
expClass = self.exporterClasses[str(item.text())]
exp = expClass(item=self.ui.itemTree.currentItem().gitem)
if prev:
oldtext = str(prev.text())
self.exporterParameters[oldtext] = self.currentExporter.parameters()
newtext = str(item.text())
if newtext in self.exporterParameters.keys():
params = self.exporterParameters[newtext]
exp.params = params
else:
params = exp.parameters()
self.exporterParameters[newtext] = params
if params is None:
self.ui.paramTree.clear()
else:
self.ui.paramTree.setParameters(params)
self.currentExporter = exp
self.ui.copyBtn.setEnabled(exp.allowCopy)
def exportClicked(self):
self.selectBox.hide()
self.currentExporter.export()
def copyClicked(self):
self.selectBox.hide()
self.currentExporter.export(copy=True)
def close(self):
self.selectBox.setVisible(False)
self.setVisible(False)
def closeEvent(self, event):
self.close()
QtGui.QWidget.closeEvent(self, event)
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/multiprocess/remoteproxy.py | .py | 48,600 | 1,132 | import os, time, sys, traceback, weakref
import numpy as np
import threading
import warnings
try:
import __builtin__ as builtins
import cPickle as pickle
except ImportError:
import builtins
import pickle
# color printing for debugging
from ..util import cprint
class ClosedError(Exception):
"""Raised when an event handler receives a request to close the connection
or discovers that the connection has been closed."""
pass
class NoResultError(Exception):
"""Raised when a request for the return value of a remote call fails
because the call has not yet returned."""
pass
class RemoteExceptionWarning(UserWarning):
"""Emitted when a request to a remote object results in an Exception """
pass
class RemoteEventHandler(object):
"""
This class handles communication between two processes. One instance is present on
each process and listens for communication from the other process. This enables
(amongst other things) ObjectProxy instances to look up their attributes and call
their methods.
This class is responsible for carrying out actions on behalf of the remote process.
Each instance holds one end of a Connection which allows python
objects to be passed between processes.
For the most common operations, see _import(), close(), and transfer()
To handle and respond to incoming requests, RemoteEventHandler requires that its
processRequests method is called repeatedly (this is usually handled by the Process
classes defined in multiprocess.processes).
"""
handlers = {} ## maps {process ID : handler}. This allows unpickler to determine which process
## an object proxy belongs to
def __init__(self, connection, name, pid, debug=False):
self.debug = debug
self.conn = connection
self.name = name
self.results = {} ## reqId: (status, result); cache of request results received from the remote process
## status is either 'result' or 'error'
## if 'error', then result will be (exception, formatted exceprion)
## where exception may be None if it could not be passed through the Connection.
self.resultLock = threading.RLock()
self.proxies = {} ## maps {weakref(proxy): proxyId}; used to inform the remote process when a proxy has been deleted.
self.proxyLock = threading.RLock()
## attributes that affect the behavior of the proxy.
## See ObjectProxy._setProxyOptions for description
self.proxyOptions = {
'callSync': 'sync', ## 'sync', 'async', 'off'
'timeout': 10, ## float
'returnType': 'auto', ## 'proxy', 'value', 'auto'
'autoProxy': False, ## bool
'deferGetattr': False, ## True, False
'noProxyTypes': [ type(None), str, int, float, tuple, list, dict, LocalObjectProxy, ObjectProxy ],
}
if int(sys.version[0]) < 3:
self.proxyOptions['noProxyTypes'].append(unicode)
else:
self.proxyOptions['noProxyTypes'].append(bytes)
self.optsLock = threading.RLock()
self.nextRequestId = 0
self.exited = False
# Mutexes to help prevent issues when multiple threads access the same RemoteEventHandler
self.processLock = threading.RLock()
self.sendLock = threading.RLock()
RemoteEventHandler.handlers[pid] = self ## register this handler as the one communicating with pid
@classmethod
def getHandler(cls, pid):
try:
return cls.handlers[pid]
except:
print(pid, cls.handlers)
raise
def debugMsg(self, msg, *args):
if not self.debug:
return
cprint.cout(self.debug, "[%d] %s\n" % (os.getpid(), str(msg)%args), -1)
def getProxyOption(self, opt):
with self.optsLock:
return self.proxyOptions[opt]
def setProxyOptions(self, **kwds):
"""
Set the default behavior options for object proxies.
See ObjectProxy._setProxyOptions for more info.
"""
with self.optsLock:
self.proxyOptions.update(kwds)
def processRequests(self):
"""Process all pending requests from the pipe, return
after no more events are immediately available. (non-blocking)
Returns the number of events processed.
"""
with self.processLock:
if self.exited:
self.debugMsg(' processRequests: exited already; raise ClosedError.')
raise ClosedError()
numProcessed = 0
while self.conn.poll():
#try:
#poll = self.conn.poll()
#if not poll:
#break
#except IOError: # this can happen if the remote process dies.
## might it also happen in other circumstances?
#raise ClosedError()
try:
self.handleRequest()
numProcessed += 1
except ClosedError:
self.debugMsg('processRequests: got ClosedError from handleRequest; setting exited=True.')
self.exited = True
raise
#except IOError as err: ## let handleRequest take care of this.
#self.debugMsg(' got IOError from handleRequest; try again.')
#if err.errno == 4: ## interrupted system call; try again
#continue
#else:
#raise
except:
print("Error in process %s" % self.name)
sys.excepthook(*sys.exc_info())
if numProcessed > 0:
self.debugMsg('processRequests: finished %d requests', numProcessed)
return numProcessed
def handleRequest(self):
"""Handle a single request from the remote process.
Blocks until a request is available."""
result = None
while True:
try:
## args, kwds are double-pickled to ensure this recv() call never fails
cmd, reqId, nByteMsgs, optStr = self.conn.recv()
break
except EOFError:
self.debugMsg(' handleRequest: got EOFError from recv; raise ClosedError.')
## remote process has shut down; end event loop
raise ClosedError()
except IOError as err:
if err.errno == 4: ## interrupted system call; try again
self.debugMsg(' handleRequest: got IOError 4 from recv; try again.')
continue
else:
self.debugMsg(' handleRequest: got IOError %d from recv (%s); raise ClosedError.', err.errno, err.strerror)
raise ClosedError()
self.debugMsg(" handleRequest: received %s %s", cmd, reqId)
## read byte messages following the main request
byteData = []
if nByteMsgs > 0:
self.debugMsg(" handleRequest: reading %d byte messages", nByteMsgs)
for i in range(nByteMsgs):
while True:
try:
byteData.append(self.conn.recv_bytes())
break
except EOFError:
self.debugMsg(" handleRequest: got EOF while reading byte messages; raise ClosedError.")
raise ClosedError()
except IOError as err:
if err.errno == 4:
self.debugMsg(" handleRequest: got IOError 4 while reading byte messages; try again.")
continue
else:
self.debugMsg(" handleRequest: got IOError while reading byte messages; raise ClosedError.")
raise ClosedError()
try:
if cmd == 'result' or cmd == 'error':
resultId = reqId
reqId = None ## prevents attempt to return information from this request
## (this is already a return from a previous request)
opts = pickle.loads(optStr)
self.debugMsg(" handleRequest: id=%s opts=%s", reqId, opts)
#print os.getpid(), "received request:", cmd, reqId, opts
returnType = opts.get('returnType', 'auto')
if cmd == 'result':
with self.resultLock:
self.results[resultId] = ('result', opts['result'])
elif cmd == 'error':
with self.resultLock:
self.results[resultId] = ('error', (opts['exception'], opts['excString']))
elif cmd == 'getObjAttr':
result = getattr(opts['obj'], opts['attr'])
elif cmd == 'callObj':
obj = opts['obj']
fnargs = opts['args']
fnkwds = opts['kwds']
## If arrays were sent as byte messages, they must be re-inserted into the
## arguments
if len(byteData) > 0:
for i,arg in enumerate(fnargs):
if isinstance(arg, tuple) and len(arg) > 0 and arg[0] == '__byte_message__':
ind = arg[1]
dtype, shape = arg[2]
fnargs[i] = np.fromstring(byteData[ind], dtype=dtype).reshape(shape)
for k,arg in fnkwds.items():
if isinstance(arg, tuple) and len(arg) > 0 and arg[0] == '__byte_message__':
ind = arg[1]
dtype, shape = arg[2]
fnkwds[k] = np.fromstring(byteData[ind], dtype=dtype).reshape(shape)
if len(fnkwds) == 0: ## need to do this because some functions do not allow keyword arguments.
try:
result = obj(*fnargs)
except:
print("Failed to call object %s: %d, %s" % (obj, len(fnargs), fnargs[1:]))
raise
else:
result = obj(*fnargs, **fnkwds)
elif cmd == 'getObjValue':
result = opts['obj'] ## has already been unpickled into its local value
returnType = 'value'
elif cmd == 'transfer':
result = opts['obj']
returnType = 'proxy'
elif cmd == 'transferArray':
## read array data from next message:
result = np.fromstring(byteData[0], dtype=opts['dtype']).reshape(opts['shape'])
returnType = 'proxy'
elif cmd == 'import':
name = opts['module']
fromlist = opts.get('fromlist', [])
mod = builtins.__import__(name, fromlist=fromlist)
if len(fromlist) == 0:
parts = name.lstrip('.').split('.')
result = mod
for part in parts[1:]:
result = getattr(result, part)
else:
result = map(mod.__getattr__, fromlist)
elif cmd == 'del':
LocalObjectProxy.releaseProxyId(opts['proxyId'])
#del self.proxiedObjects[opts['objId']]
elif cmd == 'close':
if reqId is not None:
result = True
returnType = 'value'
exc = None
except:
exc = sys.exc_info()
if reqId is not None:
if exc is None:
self.debugMsg(" handleRequest: sending return value for %d: %s", reqId, result)
#print "returnValue:", returnValue, result
if returnType == 'auto':
with self.optsLock:
noProxyTypes = self.proxyOptions['noProxyTypes']
result = self.autoProxy(result, noProxyTypes)
elif returnType == 'proxy':
result = LocalObjectProxy(result)
try:
self.replyResult(reqId, result)
except:
sys.excepthook(*sys.exc_info())
self.replyError(reqId, *sys.exc_info())
else:
self.debugMsg(" handleRequest: returning exception for %d", reqId)
self.replyError(reqId, *exc)
elif exc is not None:
sys.excepthook(*exc)
if cmd == 'close':
if opts.get('noCleanup', False) is True:
os._exit(0) ## exit immediately, do not pass GO, do not collect $200.
## (more importantly, do not call any code that would
## normally be invoked at exit)
else:
raise ClosedError()
def replyResult(self, reqId, result):
self.send(request='result', reqId=reqId, callSync='off', opts=dict(result=result))
def replyError(self, reqId, *exc):
print("error: %s %s %s" % (self.name, str(reqId), str(exc[1])))
excStr = traceback.format_exception(*exc)
try:
self.send(request='error', reqId=reqId, callSync='off', opts=dict(exception=exc[1], excString=excStr))
except:
self.send(request='error', reqId=reqId, callSync='off', opts=dict(exception=None, excString=excStr))
def send(self, request, opts=None, reqId=None, callSync='sync', timeout=10, returnType=None, byteData=None, **kwds):
"""Send a request or return packet to the remote process.
Generally it is not necessary to call this method directly; it is for internal use.
(The docstring has information that is nevertheless useful to the programmer
as it describes the internal protocol used to communicate between processes)
============== ====================================================================
**Arguments:**
request String describing the type of request being sent (see below)
reqId Integer uniquely linking a result back to the request that generated
it. (most requests leave this blank)
callSync 'sync': return the actual result of the request
'async': return a Request object which can be used to look up the
result later
'off': return no result
timeout Time in seconds to wait for a response when callSync=='sync'
opts Extra arguments sent to the remote process that determine the way
the request will be handled (see below)
returnType 'proxy', 'value', or 'auto'
byteData If specified, this is a list of objects to be sent as byte messages
to the remote process.
This is used to send large arrays without the cost of pickling.
============== ====================================================================
Description of request strings and options allowed for each:
============= ============= ========================================================
request option description
------------- ------------- --------------------------------------------------------
getObjAttr Request the remote process return (proxy to) an
attribute of an object.
obj reference to object whose attribute should be
returned
attr string name of attribute to return
returnValue bool or 'auto' indicating whether to return a proxy or
the actual value.
callObj Request the remote process call a function or
method. If a request ID is given, then the call's
return value will be sent back (or information
about the error that occurred while running the
function)
obj the (reference to) object to call
args tuple of arguments to pass to callable
kwds dict of keyword arguments to pass to callable
returnValue bool or 'auto' indicating whether to return a proxy or
the actual value.
getObjValue Request the remote process return the value of
a proxied object (must be picklable)
obj reference to object whose value should be returned
transfer Copy an object to the remote process and request
it return a proxy for the new object.
obj The object to transfer.
import Request the remote process import new symbols
and return proxy(ies) to the imported objects
module the string name of the module to import
fromlist optional list of string names to import from module
del Inform the remote process that a proxy has been
released (thus the remote process may be able to
release the original object)
proxyId id of proxy which is no longer referenced by
remote host
close Instruct the remote process to stop its event loop
and exit. Optionally, this request may return a
confirmation.
result Inform the remote process that its request has
been processed
result return value of a request
error Inform the remote process that its request failed
exception the Exception that was raised (or None if the
exception could not be pickled)
excString string-formatted version of the exception and
traceback
============= =====================================================================
"""
if self.exited:
self.debugMsg(' send: exited already; raise ClosedError.')
raise ClosedError()
with self.sendLock:
#if len(kwds) > 0:
#print "Warning: send() ignored args:", kwds
if opts is None:
opts = {}
assert callSync in ['off', 'sync', 'async'], 'callSync must be one of "off", "sync", or "async" (got %r)' % callSync
if reqId is None:
if callSync != 'off': ## requested return value; use the next available request ID
reqId = self.nextRequestId
self.nextRequestId += 1
else:
## If requestId is provided, this _must_ be a response to a previously received request.
assert request in ['result', 'error']
if returnType is not None:
opts['returnType'] = returnType
#print os.getpid(), "send request:", request, reqId, opts
## double-pickle args to ensure that at least status and request ID get through
try:
optStr = pickle.dumps(opts)
except:
print("==== Error pickling this object: ====")
print(opts)
print("=======================================")
raise
nByteMsgs = 0
if byteData is not None:
nByteMsgs = len(byteData)
## Send primary request
request = (request, reqId, nByteMsgs, optStr)
self.debugMsg('send request: cmd=%s nByteMsgs=%d id=%s opts=%s', request[0], nByteMsgs, reqId, opts)
self.conn.send(request)
## follow up by sending byte messages
if byteData is not None:
for obj in byteData: ## Remote process _must_ be prepared to read the same number of byte messages!
self.conn.send_bytes(bytes(obj))
self.debugMsg(' sent %d byte messages', len(byteData))
self.debugMsg(' call sync: %s', callSync)
if callSync == 'off':
return
req = Request(self, reqId, description=str(request), timeout=timeout)
if callSync == 'async':
return req
if callSync == 'sync':
return req.result()
def close(self, callSync='off', noCleanup=False, **kwds):
try:
self.send(request='close', opts=dict(noCleanup=noCleanup), callSync=callSync, **kwds)
self.exited = True
except ClosedError:
pass
def getResult(self, reqId):
## raises NoResultError if the result is not available yet
#print self.results.keys(), os.getpid()
with self.resultLock:
haveResult = reqId in self.results
if not haveResult:
try:
self.processRequests()
except ClosedError: ## even if remote connection has closed, we may have
## received new data during this call to processRequests()
pass
with self.resultLock:
if reqId not in self.results:
raise NoResultError()
status, result = self.results.pop(reqId)
if status == 'result':
return result
elif status == 'error':
#print ''.join(result)
exc, excStr = result
if exc is not None:
warnings.warn("===== Remote process raised exception on request: =====", RemoteExceptionWarning)
warnings.warn(''.join(excStr), RemoteExceptionWarning)
warnings.warn("===== Local Traceback to request follows: =====", RemoteExceptionWarning)
raise exc
else:
print(''.join(excStr))
raise Exception("Error getting result. See above for exception from remote process.")
else:
raise Exception("Internal error.")
def _import(self, mod, **kwds):
"""
Request the remote process import a module (or symbols from a module)
and return the proxied results. Uses built-in __import__() function, but
adds a bit more processing:
_import('module') => returns module
_import('module.submodule') => returns submodule
(note this differs from behavior of __import__)
_import('module', fromlist=[name1, name2, ...]) => returns [module.name1, module.name2, ...]
(this also differs from behavior of __import__)
"""
return self.send(request='import', callSync='sync', opts=dict(module=mod), **kwds)
def getObjAttr(self, obj, attr, **kwds):
return self.send(request='getObjAttr', opts=dict(obj=obj, attr=attr), **kwds)
def getObjValue(self, obj, **kwds):
return self.send(request='getObjValue', opts=dict(obj=obj), **kwds)
def callObj(self, obj, args, kwds, **opts):
opts = opts.copy()
args = list(args)
## Decide whether to send arguments by value or by proxy
with self.optsLock:
noProxyTypes = opts.pop('noProxyTypes', None)
if noProxyTypes is None:
noProxyTypes = self.proxyOptions['noProxyTypes']
autoProxy = opts.pop('autoProxy', self.proxyOptions['autoProxy'])
if autoProxy is True:
args = [self.autoProxy(v, noProxyTypes) for v in args]
for k, v in kwds.items():
opts[k] = self.autoProxy(v, noProxyTypes)
byteMsgs = []
## If there are arrays in the arguments, send those as byte messages.
## We do this because pickling arrays is too expensive.
for i,arg in enumerate(args):
if arg.__class__ == np.ndarray:
args[i] = ("__byte_message__", len(byteMsgs), (arg.dtype, arg.shape))
byteMsgs.append(arg)
for k,v in kwds.items():
if v.__class__ == np.ndarray:
kwds[k] = ("__byte_message__", len(byteMsgs), (v.dtype, v.shape))
byteMsgs.append(v)
return self.send(request='callObj', opts=dict(obj=obj, args=args, kwds=kwds), byteData=byteMsgs, **opts)
def registerProxy(self, proxy):
with self.proxyLock:
ref = weakref.ref(proxy, self.deleteProxy)
self.proxies[ref] = proxy._proxyId
def deleteProxy(self, ref):
if self.send is None:
# this can happen during shutdown
return
with self.proxyLock:
proxyId = self.proxies.pop(ref)
try:
self.send(request='del', opts=dict(proxyId=proxyId), callSync='off')
except ClosedError: ## if remote process has closed down, there is no need to send delete requests anymore
pass
def transfer(self, obj, **kwds):
"""
Transfer an object by value to the remote host (the object must be picklable)
and return a proxy for the new remote object.
"""
if obj.__class__ is np.ndarray:
opts = {'dtype': obj.dtype, 'shape': obj.shape}
return self.send(request='transferArray', opts=opts, byteData=[obj], **kwds)
else:
return self.send(request='transfer', opts=dict(obj=obj), **kwds)
def autoProxy(self, obj, noProxyTypes):
## Return object wrapped in LocalObjectProxy _unless_ its type is in noProxyTypes.
for typ in noProxyTypes:
if isinstance(obj, typ):
return obj
return LocalObjectProxy(obj)
class Request(object):
"""
Request objects are returned when calling an ObjectProxy in asynchronous mode
or if a synchronous call has timed out. Use hasResult() to ask whether
the result of the call has been returned yet. Use result() to get
the returned value.
"""
def __init__(self, process, reqId, description=None, timeout=10):
self.proc = process
self.description = description
self.reqId = reqId
self.gotResult = False
self._result = None
self.timeout = timeout
def result(self, block=True, timeout=None):
"""
Return the result for this request.
If block is True, wait until the result has arrived or *timeout* seconds passes.
If the timeout is reached, raise NoResultError. (use timeout=None to disable)
If block is False, raise NoResultError immediately if the result has not arrived yet.
If the process's connection has closed before the result arrives, raise ClosedError.
"""
if self.gotResult:
return self._result
if timeout is None:
timeout = self.timeout
if block:
start = time.time()
while not self.hasResult():
if self.proc.exited:
raise ClosedError()
time.sleep(0.005)
if timeout >= 0 and time.time() - start > timeout:
print("Request timed out: %s" % self.description)
import traceback
traceback.print_stack()
raise NoResultError()
return self._result
else:
self._result = self.proc.getResult(self.reqId) ## raises NoResultError if result is not available yet
self.gotResult = True
return self._result
def hasResult(self):
"""Returns True if the result for this request has arrived."""
try:
self.result(block=False)
except NoResultError:
pass
return self.gotResult
class LocalObjectProxy(object):
"""
Used for wrapping local objects to ensure that they are send by proxy to a remote host.
Note that 'proxy' is just a shorter alias for LocalObjectProxy.
For example::
data = [1,2,3,4,5]
remotePlot.plot(data) ## by default, lists are pickled and sent by value
remotePlot.plot(proxy(data)) ## force the object to be sent by proxy
"""
nextProxyId = 0
proxiedObjects = {} ## maps {proxyId: object}
@classmethod
def registerObject(cls, obj):
## assign it a unique ID so we can keep a reference to the local object
pid = cls.nextProxyId
cls.nextProxyId += 1
cls.proxiedObjects[pid] = obj
#print "register:", cls.proxiedObjects
return pid
@classmethod
def lookupProxyId(cls, pid):
return cls.proxiedObjects[pid]
@classmethod
def releaseProxyId(cls, pid):
del cls.proxiedObjects[pid]
#print "release:", cls.proxiedObjects
def __init__(self, obj, **opts):
"""
Create a 'local' proxy object that, when sent to a remote host,
will appear as a normal ObjectProxy to *obj*.
Any extra keyword arguments are passed to proxy._setProxyOptions()
on the remote side.
"""
self.processId = os.getpid()
#self.objectId = id(obj)
self.typeStr = repr(obj)
#self.handler = handler
self.obj = obj
self.opts = opts
def __reduce__(self):
## a proxy is being pickled and sent to a remote process.
## every time this happens, a new proxy will be generated in the remote process,
## so we keep a new ID so we can track when each is released.
pid = LocalObjectProxy.registerObject(self.obj)
return (unpickleObjectProxy, (self.processId, pid, self.typeStr, None, self.opts))
## alias
proxy = LocalObjectProxy
def unpickleObjectProxy(processId, proxyId, typeStr, attributes=None, opts=None):
if processId == os.getpid():
obj = LocalObjectProxy.lookupProxyId(proxyId)
if attributes is not None:
for attr in attributes:
obj = getattr(obj, attr)
return obj
else:
proxy = ObjectProxy(processId, proxyId=proxyId, typeStr=typeStr)
if opts is not None:
proxy._setProxyOptions(**opts)
return proxy
class ObjectProxy(object):
"""
Proxy to an object stored by the remote process. Proxies are created
by calling Process._import(), Process.transfer(), or by requesting/calling
attributes on existing proxy objects.
For the most part, this object can be used exactly as if it
were a local object::
rsys = proc._import('sys') # returns proxy to sys module on remote process
rsys.stdout # proxy to remote sys.stdout
rsys.stdout.write # proxy to remote sys.stdout.write
rsys.stdout.write('hello') # calls sys.stdout.write('hello') on remote machine
# and returns the result (None)
When calling a proxy to a remote function, the call can be made synchronous
(result of call is returned immediately), asynchronous (result is returned later),
or return can be disabled entirely::
ros = proc._import('os')
## synchronous call; result is returned immediately
pid = ros.getpid()
## asynchronous call
request = ros.getpid(_callSync='async')
while not request.hasResult():
time.sleep(0.01)
pid = request.result()
## disable return when we know it isn't needed
rsys.stdout.write('hello', _callSync='off')
Additionally, values returned from a remote function call are automatically
returned either by value (must be picklable) or by proxy.
This behavior can be forced::
rnp = proc._import('numpy')
arrProxy = rnp.array([1,2,3,4], _returnType='proxy')
arrValue = rnp.array([1,2,3,4], _returnType='value')
The default callSync and returnType behaviors (as well as others) can be set
for each proxy individually using ObjectProxy._setProxyOptions() or globally using
proc.setProxyOptions().
"""
def __init__(self, processId, proxyId, typeStr='', parent=None):
object.__init__(self)
## can't set attributes directly because setattr is overridden.
self.__dict__['_processId'] = processId
self.__dict__['_typeStr'] = typeStr
self.__dict__['_proxyId'] = proxyId
self.__dict__['_attributes'] = ()
## attributes that affect the behavior of the proxy.
## in all cases, a value of None causes the proxy to ask
## its parent event handler to make the decision
self.__dict__['_proxyOptions'] = {
'callSync': None, ## 'sync', 'async', None
'timeout': None, ## float, None
'returnType': None, ## 'proxy', 'value', 'auto', None
'deferGetattr': None, ## True, False, None
'noProxyTypes': None, ## list of types to send by value instead of by proxy
'autoProxy': None,
}
self.__dict__['_handler'] = RemoteEventHandler.getHandler(processId)
self.__dict__['_handler'].registerProxy(self) ## handler will watch proxy; inform remote process when the proxy is deleted.
def _setProxyOptions(self, **kwds):
"""
Change the behavior of this proxy. For all options, a value of None
will cause the proxy to instead use the default behavior defined
by its parent Process.
Options are:
============= =============================================================
callSync 'sync', 'async', 'off', or None.
If 'async', then calling methods will return a Request object
which can be used to inquire later about the result of the
method call.
If 'sync', then calling a method
will block until the remote process has returned its result
or the timeout has elapsed (in this case, a Request object
is returned instead).
If 'off', then the remote process is instructed _not_ to
reply and the method call will return None immediately.
returnType 'auto', 'proxy', 'value', or None.
If 'proxy', then the value returned when calling a method
will be a proxy to the object on the remote process.
If 'value', then attempt to pickle the returned object and
send it back.
If 'auto', then the decision is made by consulting the
'noProxyTypes' option.
autoProxy bool or None. If True, arguments to __call__ are
automatically converted to proxy unless their type is
listed in noProxyTypes (see below). If False, arguments
are left untouched. Use proxy(obj) to manually convert
arguments before sending.
timeout float or None. Length of time to wait during synchronous
requests before returning a Request object instead.
deferGetattr True, False, or None.
If False, all attribute requests will be sent to the remote
process immediately and will block until a response is
received (or timeout has elapsed).
If True, requesting an attribute from the proxy returns a
new proxy immediately. The remote process is _not_ contacted
to make this request. This is faster, but it is possible to
request an attribute that does not exist on the proxied
object. In this case, AttributeError will not be raised
until an attempt is made to look up the attribute on the
remote process.
noProxyTypes List of object types that should _not_ be proxied when
sent to the remote process.
============= =============================================================
"""
for k in kwds:
if k not in self._proxyOptions:
raise KeyError("Unrecognized proxy option '%s'" % k)
self._proxyOptions.update(kwds)
def _getValue(self):
"""
Return the value of the proxied object
(the remote object must be picklable)
"""
return self._handler.getObjValue(self)
def _getProxyOption(self, opt):
val = self._proxyOptions[opt]
if val is None:
return self._handler.getProxyOption(opt)
return val
def _getProxyOptions(self):
return dict([(k, self._getProxyOption(k)) for k in self._proxyOptions])
def __reduce__(self):
return (unpickleObjectProxy, (self._processId, self._proxyId, self._typeStr, self._attributes))
def __repr__(self):
#objRepr = self.__getattr__('__repr__')(callSync='value')
return "<ObjectProxy for process %d, object 0x%x: %s >" % (self._processId, self._proxyId, self._typeStr)
def __getattr__(self, attr, **kwds):
"""
Calls __getattr__ on the remote object and returns the attribute
by value or by proxy depending on the options set (see
ObjectProxy._setProxyOptions and RemoteEventHandler.setProxyOptions)
If the option 'deferGetattr' is True for this proxy, then a new proxy object
is returned _without_ asking the remote object whether the named attribute exists.
This can save time when making multiple chained attribute requests,
but may also defer a possible AttributeError until later, making
them more difficult to debug.
"""
opts = self._getProxyOptions()
for k in opts:
if '_'+k in kwds:
opts[k] = kwds.pop('_'+k)
if opts['deferGetattr'] is True:
return self._deferredAttr(attr)
else:
#opts = self._getProxyOptions()
return self._handler.getObjAttr(self, attr, **opts)
def _deferredAttr(self, attr):
return DeferredObjectProxy(self, attr)
def __call__(self, *args, **kwds):
"""
Attempts to call the proxied object from the remote process.
Accepts extra keyword arguments:
_callSync 'off', 'sync', or 'async'
_returnType 'value', 'proxy', or 'auto'
If the remote call raises an exception on the remote process,
it will be re-raised on the local process.
"""
opts = self._getProxyOptions()
for k in opts:
if '_'+k in kwds:
opts[k] = kwds.pop('_'+k)
return self._handler.callObj(obj=self, args=args, kwds=kwds, **opts)
## Explicitly proxy special methods. Is there a better way to do this??
def _getSpecialAttr(self, attr):
## this just gives us an easy way to change the behavior of the special methods
return self._deferredAttr(attr)
def __getitem__(self, *args):
return self._getSpecialAttr('__getitem__')(*args)
def __setitem__(self, *args):
return self._getSpecialAttr('__setitem__')(*args, _callSync='off')
def __setattr__(self, *args):
return self._getSpecialAttr('__setattr__')(*args, _callSync='off')
def __str__(self, *args):
return self._getSpecialAttr('__str__')(*args, _returnType='value')
def __len__(self, *args):
return self._getSpecialAttr('__len__')(*args)
def __add__(self, *args):
return self._getSpecialAttr('__add__')(*args)
def __sub__(self, *args):
return self._getSpecialAttr('__sub__')(*args)
def __div__(self, *args):
return self._getSpecialAttr('__div__')(*args)
def __truediv__(self, *args):
return self._getSpecialAttr('__truediv__')(*args)
def __floordiv__(self, *args):
return self._getSpecialAttr('__floordiv__')(*args)
def __mul__(self, *args):
return self._getSpecialAttr('__mul__')(*args)
def __pow__(self, *args):
return self._getSpecialAttr('__pow__')(*args)
def __iadd__(self, *args):
return self._getSpecialAttr('__iadd__')(*args, _callSync='off')
def __isub__(self, *args):
return self._getSpecialAttr('__isub__')(*args, _callSync='off')
def __idiv__(self, *args):
return self._getSpecialAttr('__idiv__')(*args, _callSync='off')
def __itruediv__(self, *args):
return self._getSpecialAttr('__itruediv__')(*args, _callSync='off')
def __ifloordiv__(self, *args):
return self._getSpecialAttr('__ifloordiv__')(*args, _callSync='off')
def __imul__(self, *args):
return self._getSpecialAttr('__imul__')(*args, _callSync='off')
def __ipow__(self, *args):
return self._getSpecialAttr('__ipow__')(*args, _callSync='off')
def __rshift__(self, *args):
return self._getSpecialAttr('__rshift__')(*args)
def __lshift__(self, *args):
return self._getSpecialAttr('__lshift__')(*args)
def __irshift__(self, *args):
return self._getSpecialAttr('__irshift__')(*args, _callSync='off')
def __ilshift__(self, *args):
return self._getSpecialAttr('__ilshift__')(*args, _callSync='off')
def __eq__(self, *args):
return self._getSpecialAttr('__eq__')(*args)
def __ne__(self, *args):
return self._getSpecialAttr('__ne__')(*args)
def __lt__(self, *args):
return self._getSpecialAttr('__lt__')(*args)
def __gt__(self, *args):
return self._getSpecialAttr('__gt__')(*args)
def __le__(self, *args):
return self._getSpecialAttr('__le__')(*args)
def __ge__(self, *args):
return self._getSpecialAttr('__ge__')(*args)
def __and__(self, *args):
return self._getSpecialAttr('__and__')(*args)
def __or__(self, *args):
return self._getSpecialAttr('__or__')(*args)
def __xor__(self, *args):
return self._getSpecialAttr('__xor__')(*args)
def __iand__(self, *args):
return self._getSpecialAttr('__iand__')(*args, _callSync='off')
def __ior__(self, *args):
return self._getSpecialAttr('__ior__')(*args, _callSync='off')
def __ixor__(self, *args):
return self._getSpecialAttr('__ixor__')(*args, _callSync='off')
def __mod__(self, *args):
return self._getSpecialAttr('__mod__')(*args)
def __radd__(self, *args):
return self._getSpecialAttr('__radd__')(*args)
def __rsub__(self, *args):
return self._getSpecialAttr('__rsub__')(*args)
def __rdiv__(self, *args):
return self._getSpecialAttr('__rdiv__')(*args)
def __rfloordiv__(self, *args):
return self._getSpecialAttr('__rfloordiv__')(*args)
def __rtruediv__(self, *args):
return self._getSpecialAttr('__rtruediv__')(*args)
def __rmul__(self, *args):
return self._getSpecialAttr('__rmul__')(*args)
def __rpow__(self, *args):
return self._getSpecialAttr('__rpow__')(*args)
def __rrshift__(self, *args):
return self._getSpecialAttr('__rrshift__')(*args)
def __rlshift__(self, *args):
return self._getSpecialAttr('__rlshift__')(*args)
def __rand__(self, *args):
return self._getSpecialAttr('__rand__')(*args)
def __ror__(self, *args):
return self._getSpecialAttr('__ror__')(*args)
def __rxor__(self, *args):
return self._getSpecialAttr('__ror__')(*args)
def __rmod__(self, *args):
return self._getSpecialAttr('__rmod__')(*args)
def __hash__(self):
## Required for python3 since __eq__ is defined.
return id(self)
class DeferredObjectProxy(ObjectProxy):
"""
This class represents an attribute (or sub-attribute) of a proxied object.
It is used to speed up attribute requests. Take the following scenario::
rsys = proc._import('sys')
rsys.stdout.write('hello')
For this simple example, a total of 4 synchronous requests are made to
the remote process:
1) import sys
2) getattr(sys, 'stdout')
3) getattr(stdout, 'write')
4) write('hello')
This takes a lot longer than running the equivalent code locally. To
speed things up, we can 'defer' the two attribute lookups so they are
only carried out when neccessary::
rsys = proc._import('sys')
rsys._setProxyOptions(deferGetattr=True)
rsys.stdout.write('hello')
This example only makes two requests to the remote process; the two
attribute lookups immediately return DeferredObjectProxy instances
immediately without contacting the remote process. When the call
to write() is made, all attribute requests are processed at the same time.
Note that if the attributes requested do not exist on the remote object,
making the call to write() will raise an AttributeError.
"""
def __init__(self, parentProxy, attribute):
## can't set attributes directly because setattr is overridden.
for k in ['_processId', '_typeStr', '_proxyId', '_handler']:
self.__dict__[k] = getattr(parentProxy, k)
self.__dict__['_parent'] = parentProxy ## make sure parent stays alive
self.__dict__['_attributes'] = parentProxy._attributes + (attribute,)
self.__dict__['_proxyOptions'] = parentProxy._proxyOptions.copy()
def __repr__(self):
return ObjectProxy.__repr__(self) + '.' + '.'.join(self._attributes)
def _undefer(self):
"""
Return a non-deferred ObjectProxy referencing the same object
"""
return self._parent.__getattr__(self._attributes[-1], _deferGetattr=False)
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/multiprocess/parallelizer.py | .py | 12,494 | 339 | # -*- coding: utf-8 -*-
import os, sys, time, multiprocessing, re
from .processes import ForkedProcess
from .remoteproxy import ClosedError
from ..python2_3 import basestring, xrange
class CanceledError(Exception):
"""Raised when the progress dialog is canceled during a processing operation."""
pass
class Parallelize(object):
"""
Class for ultra-simple inline parallelization on multi-core CPUs
Example::
## Here is the serial (single-process) task:
tasks = [1, 2, 4, 8]
results = []
for task in tasks:
result = processTask(task)
results.append(result)
print(results)
## Here is the parallelized version:
tasks = [1, 2, 4, 8]
results = []
with Parallelize(tasks, workers=4, results=results) as tasker:
for task in tasker:
result = processTask(task)
tasker.results.append(result)
print(results)
The only major caveat is that *result* in the example above must be picklable,
since it is automatically sent via pipe back to the parent process.
"""
def __init__(self, tasks=None, workers=None, block=True, progressDialog=None, randomReseed=True, **kwds):
"""
=============== ===================================================================
**Arguments:**
tasks list of objects to be processed (Parallelize will determine how to
distribute the tasks). If unspecified, then each worker will receive
a single task with a unique id number.
workers number of worker processes or None to use number of CPUs in the
system
progressDialog optional dict of arguments for ProgressDialog
to update while tasks are processed
randomReseed If True, each forked process will reseed its random number generator
to ensure independent results. Works with the built-in random
and numpy.random.
kwds objects to be shared by proxy with child processes (they will
appear as attributes of the tasker)
=============== ===================================================================
"""
## Generate progress dialog.
## Note that we want to avoid letting forked child processes play with progress dialogs..
self.showProgress = False
if progressDialog is not None:
self.showProgress = True
if isinstance(progressDialog, basestring):
progressDialog = {'labelText': progressDialog}
from ..widgets.ProgressDialog import ProgressDialog
self.progressDlg = ProgressDialog(**progressDialog)
if workers is None:
workers = self.suggestedWorkerCount()
if not hasattr(os, 'fork'):
workers = 1
self.workers = workers
if tasks is None:
tasks = range(workers)
self.tasks = list(tasks)
self.reseed = randomReseed
self.kwds = kwds.copy()
self.kwds['_taskStarted'] = self._taskStarted
def __enter__(self):
self.proc = None
if self.workers == 1:
return self.runSerial()
else:
return self.runParallel()
def __exit__(self, *exc_info):
if self.proc is not None: ## worker
exceptOccurred = exc_info[0] is not None ## hit an exception during processing.
try:
if exceptOccurred:
sys.excepthook(*exc_info)
finally:
#print os.getpid(), 'exit'
os._exit(1 if exceptOccurred else 0)
else: ## parent
if self.showProgress:
try:
self.progressDlg.__exit__(None, None, None)
except Exception:
pass
def runSerial(self):
if self.showProgress:
self.progressDlg.__enter__()
self.progressDlg.setMaximum(len(self.tasks))
self.progress = {os.getpid(): []}
return Tasker(self, None, self.tasks, self.kwds)
def runParallel(self):
self.childs = []
## break up tasks into one set per worker
workers = self.workers
chunks = [[] for i in xrange(workers)]
i = 0
for i in range(len(self.tasks)):
chunks[i%workers].append(self.tasks[i])
## fork and assign tasks to each worker
for i in range(workers):
proc = ForkedProcess(target=None, preProxy=self.kwds, randomReseed=self.reseed)
if not proc.isParent:
self.proc = proc
return Tasker(self, proc, chunks[i], proc.forkedProxies)
else:
self.childs.append(proc)
## Keep track of the progress of each worker independently.
self.progress = dict([(ch.childPid, []) for ch in self.childs])
## for each child process, self.progress[pid] is a list
## of task indexes. The last index is the task currently being
## processed; all others are finished.
try:
if self.showProgress:
self.progressDlg.__enter__()
self.progressDlg.setMaximum(len(self.tasks))
## process events from workers until all have exited.
activeChilds = self.childs[:]
self.exitCodes = []
pollInterval = 0.01
while len(activeChilds) > 0:
waitingChildren = 0
rem = []
for ch in activeChilds:
try:
n = ch.processRequests()
if n > 0:
waitingChildren += 1
except ClosedError:
#print ch.childPid, 'process finished'
rem.append(ch)
if self.showProgress:
self.progressDlg += 1
#print "remove:", [ch.childPid for ch in rem]
for ch in rem:
activeChilds.remove(ch)
while True:
try:
pid, exitcode = os.waitpid(ch.childPid, 0)
self.exitCodes.append(exitcode)
break
except OSError as ex:
if ex.errno == 4: ## If we get this error, just try again
continue
#print "Ignored system call interruption"
else:
raise
#print [ch.childPid for ch in activeChilds]
if self.showProgress and self.progressDlg.wasCanceled():
for ch in activeChilds:
ch.kill()
raise CanceledError()
## adjust polling interval--prefer to get exactly 1 event per poll cycle.
if waitingChildren > 1:
pollInterval *= 0.7
elif waitingChildren == 0:
pollInterval /= 0.7
pollInterval = max(min(pollInterval, 0.5), 0.0005) ## but keep it within reasonable limits
time.sleep(pollInterval)
finally:
if self.showProgress:
self.progressDlg.__exit__(None, None, None)
for ch in self.childs:
ch.join()
if len(self.exitCodes) < len(self.childs):
raise Exception("Parallelizer started %d processes but only received exit codes from %d." % (len(self.childs), len(self.exitCodes)))
for code in self.exitCodes:
if code != 0:
raise Exception("Error occurred in parallel-executed subprocess (console output may have more information).")
return [] ## no tasks for parent process.
@staticmethod
def suggestedWorkerCount():
if 'linux' in sys.platform:
## I think we can do a little better here..
## cpu_count does not consider that there is little extra benefit to using hyperthreaded cores.
try:
cores = {}
pid = None
with open('/proc/cpuinfo') as fd:
for line in fd:
m = re.match(r'physical id\s+:\s+(\d+)', line)
if m is not None:
pid = m.groups()[0]
m = re.match(r'cpu cores\s+:\s+(\d+)', line)
if m is not None:
cores[pid] = int(m.groups()[0])
return sum(cores.values())
except:
return multiprocessing.cpu_count()
else:
return multiprocessing.cpu_count()
def _taskStarted(self, pid, i, **kwds):
## called remotely by tasker to indicate it has started working on task i
#print pid, 'reported starting task', i
if self.showProgress:
if len(self.progress[pid]) > 0:
self.progressDlg += 1
if pid == os.getpid(): ## single-worker process
if self.progressDlg.wasCanceled():
raise CanceledError()
self.progress[pid].append(i)
class Tasker(object):
def __init__(self, parallelizer, process, tasks, kwds):
self.proc = process
self.par = parallelizer
self.tasks = tasks
for k, v in kwds.items():
setattr(self, k, v)
def __iter__(self):
## we could fix this up such that tasks are retrieved from the parent process one at a time..
for i, task in enumerate(self.tasks):
self.index = i
#print os.getpid(), 'starting task', i
self._taskStarted(os.getpid(), i, _callSync='off')
yield task
if self.proc is not None:
#print os.getpid(), 'no more tasks'
self.proc.close()
def process(self):
"""
Process requests from parent.
Usually it is not necessary to call this unless you would like to
receive messages (such as exit requests) during an iteration.
"""
if self.proc is not None:
self.proc.processRequests()
def numWorkers(self):
"""
Return the number of parallel workers
"""
return self.par.workers
#class Parallelizer:
#"""
#Use::
#p = Parallelizer()
#with p(4) as i:
#p.finish(do_work(i))
#print p.results()
#"""
#def __init__(self):
#pass
#def __call__(self, n):
#self.replies = []
#self.conn = None ## indicates this is the parent process
#return Session(self, n)
#def finish(self, data):
#if self.conn is None:
#self.replies.append((self.i, data))
#else:
##print "send", self.i, data
#self.conn.send((self.i, data))
#os._exit(0)
#def result(self):
#print self.replies
#class Session:
#def __init__(self, par, n):
#self.par = par
#self.n = n
#def __enter__(self):
#self.childs = []
#for i in range(1, self.n):
#c1, c2 = multiprocessing.Pipe()
#pid = os.fork()
#if pid == 0: ## child
#self.par.i = i
#self.par.conn = c2
#self.childs = None
#c1.close()
#return i
#else:
#self.childs.append(c1)
#c2.close()
#self.par.i = 0
#return 0
#def __exit__(self, *exc_info):
#if exc_info[0] is not None:
#sys.excepthook(*exc_info)
#if self.childs is not None:
#self.par.replies.extend([conn.recv() for conn in self.childs])
#else:
#self.par.finish(None)
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/multiprocess/__init__.py | .py | 921 | 25 | """
Multiprocessing utility library
(parallelization done the way I like it)
Luke Campagnola
2012.06.10
This library provides:
- simple mechanism for starting a new python interpreter process that can be controlled from the original process
(this allows, for example, displaying and manipulating plots in a remote process
while the parent process is free to do other work)
- proxy system that allows objects hosted in the remote process to be used as if they were local
- Qt signal connection between processes
- very simple in-line parallelization (fork only; does not work on windows) for number-crunching
TODO:
allow remote processes to serve as rendering engines that pass pixmaps back to the parent process for display
(RemoteGraphicsView class)
"""
from .processes import *
from .parallelizer import Parallelize, CanceledError
from .remoteproxy import proxy, ClosedError, NoResultError
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/multiprocess/bootstrap.py | .py | 1,725 | 48 | """For starting up remote processes"""
import sys, pickle, os
if __name__ == '__main__':
if hasattr(os, 'setpgrp'):
os.setpgrp() ## prevents signals (notably keyboard interrupt) being forwarded from parent to this process
if sys.version[0] == '3':
#name, port, authkey, ppid, targetStr, path, pyside = pickle.load(sys.stdin.buffer)
opts = pickle.load(sys.stdin.buffer)
else:
#name, port, authkey, ppid, targetStr, path, pyside = pickle.load(sys.stdin)
opts = pickle.load(sys.stdin)
#print "key:", ' '.join([str(ord(x)) for x in authkey])
path = opts.pop('path', None)
if path is not None:
if isinstance(path, str):
# if string, just insert this into the path
sys.path.insert(0, path)
else:
# if list, then replace the entire sys.path
## modify sys.path in place--no idea who already has a reference to the existing list.
while len(sys.path) > 0:
sys.path.pop()
sys.path.extend(path)
pyqtapis = opts.pop('pyqtapis', None)
if pyqtapis is not None:
import sip
for k,v in pyqtapis.items():
sip.setapi(k, v)
qt_lib = opts.pop('qt_lib', None)
if qt_lib == 'PySide':
import PySide
elif qt_lib == 'PySide2':
import PySide2
elif qt_lib == 'PyQt5':
import PyQt5
targetStr = opts.pop('targetStr')
try:
target = pickle.loads(targetStr) ## unpickling the target should import everything we need
except:
print("Current sys.path:", sys.path)
raise
target(**opts) ## Send all other options to the target function
sys.exit(0)
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/multiprocess/processes.py | .py | 22,127 | 505 | import subprocess, atexit, os, sys, time, random, socket, signal, inspect
import multiprocessing.connection
try:
import cPickle as pickle
except ImportError:
import pickle
from .remoteproxy import RemoteEventHandler, ClosedError, NoResultError, LocalObjectProxy, ObjectProxy
from ..Qt import QT_LIB
from ..util import cprint # color printing for debugging
__all__ = ['Process', 'QtProcess', 'ForkedProcess', 'ClosedError', 'NoResultError']
class Process(RemoteEventHandler):
"""
Bases: RemoteEventHandler
This class is used to spawn and control a new python interpreter.
It uses subprocess.Popen to start the new process and communicates with it
using multiprocessing.Connection objects over a network socket.
By default, the remote process will immediately enter an event-processing
loop that carries out requests send from the parent process.
Remote control works mainly through proxy objects::
proc = Process() ## starts process, returns handle
rsys = proc._import('sys') ## asks remote process to import 'sys', returns
## a proxy which references the imported module
rsys.stdout.write('hello\n') ## This message will be printed from the remote
## process. Proxy objects can usually be used
## exactly as regular objects are.
proc.close() ## Request the remote process shut down
Requests made via proxy objects may be synchronous or asynchronous and may
return objects either by proxy or by value (if they are picklable). See
ProxyObject for more information.
"""
_process_count = 1 # just used for assigning colors to each process for debugging
def __init__(self, name=None, target=None, executable=None, copySysPath=True, debug=False, timeout=20, wrapStdout=None, pyqtapis=None):
"""
============== =============================================================
**Arguments:**
name Optional name for this process used when printing messages
from the remote process.
target Optional function to call after starting remote process.
By default, this is startEventLoop(), which causes the remote
process to handle requests from the parent process until it
is asked to quit. If you wish to specify a different target,
it must be picklable (bound methods are not).
copySysPath If True, copy the contents of sys.path to the remote process.
If False, then only the path required to import pyqtgraph is
added.
debug If True, print detailed information about communication
with the child process.
wrapStdout If True (default on windows) then stdout and stderr from the
child process will be caught by the parent process and
forwarded to its stdout/stderr. This provides a workaround
for a python bug: http://bugs.python.org/issue3905
but has the side effect that child output is significantly
delayed relative to the parent output.
pyqtapis Optional dictionary of PyQt API version numbers to set before
importing pyqtgraph in the remote process.
============== =============================================================
"""
if target is None:
target = startEventLoop
if name is None:
name = str(self)
if executable is None:
executable = sys.executable
self.debug = 7 if debug is True else False # 7 causes printing in white
## random authentication key
authkey = os.urandom(20)
## Windows seems to have a hard time with hmac
if sys.platform.startswith('win'):
authkey = None
#print "key:", ' '.join([str(ord(x)) for x in authkey])
## Listen for connection from remote process (and find free port number)
l = multiprocessing.connection.Listener(('localhost', 0), authkey=authkey)
port = l.address[1]
## start remote process, instruct it to run target function
if copySysPath:
sysPath = sys.path
else:
# what path do we need to make target importable?
mod = inspect.getmodule(target)
modroot = sys.modules[mod.__name__.split('.')[0]]
sysPath = os.path.abspath(os.path.join(os.path.dirname(modroot.__file__), '..'))
bootstrap = os.path.abspath(os.path.join(os.path.dirname(__file__), 'bootstrap.py'))
self.debugMsg('Starting child process (%s %s)' % (executable, bootstrap))
# Decide on printing color for this process
if debug:
procDebug = (Process._process_count%6) + 1 # pick a color for this process to print in
Process._process_count += 1
else:
procDebug = False
if wrapStdout is None:
wrapStdout = sys.platform.startswith('win')
if wrapStdout:
## note: we need all three streams to have their own PIPE due to this bug:
## http://bugs.python.org/issue3905
stdout = subprocess.PIPE
stderr = subprocess.PIPE
self.proc = subprocess.Popen((executable, bootstrap), stdin=subprocess.PIPE, stdout=stdout, stderr=stderr)
## to circumvent the bug and still make the output visible, we use
## background threads to pass data from pipes to stdout/stderr
self._stdoutForwarder = FileForwarder(self.proc.stdout, "stdout", procDebug)
self._stderrForwarder = FileForwarder(self.proc.stderr, "stderr", procDebug)
else:
self.proc = subprocess.Popen((executable, bootstrap), stdin=subprocess.PIPE)
targetStr = pickle.dumps(target) ## double-pickle target so that child has a chance to
## set its sys.path properly before unpickling the target
pid = os.getpid() # we must send pid to child because windows does not have getppid
## Send everything the remote process needs to start correctly
data = dict(
name=name+'_child',
port=port,
authkey=authkey,
ppid=pid,
targetStr=targetStr,
path=sysPath,
qt_lib=QT_LIB,
debug=procDebug,
pyqtapis=pyqtapis,
)
pickle.dump(data, self.proc.stdin)
self.proc.stdin.close()
## open connection for remote process
self.debugMsg('Listening for child process on port %d, authkey=%s..' % (port, repr(authkey)))
while True:
try:
conn = l.accept()
break
except IOError as err:
if err.errno == 4: # interrupted; try again
continue
else:
raise
RemoteEventHandler.__init__(self, conn, name+'_parent', pid=self.proc.pid, debug=self.debug)
self.debugMsg('Connected to child process.')
atexit.register(self.join)
def join(self, timeout=10):
self.debugMsg('Joining child process..')
if self.proc.poll() is None:
self.close()
start = time.time()
while self.proc.poll() is None:
if timeout is not None and time.time() - start > timeout:
raise Exception('Timed out waiting for remote process to end.')
time.sleep(0.05)
self.conn.close()
# Close remote polling threads, otherwise they will spin continuously
if hasattr(self, "_stdoutForwarder"):
self._stdoutForwarder.finish.set()
self._stderrForwarder.finish.set()
self._stdoutForwarder.join()
self._stderrForwarder.join()
self.debugMsg('Child process exited. (%d)' % self.proc.returncode)
def debugMsg(self, msg, *args):
if hasattr(self, '_stdoutForwarder'):
## Lock output from subprocess to make sure we do not get line collisions
with self._stdoutForwarder.lock:
with self._stderrForwarder.lock:
RemoteEventHandler.debugMsg(self, msg, *args)
else:
RemoteEventHandler.debugMsg(self, msg, *args)
def startEventLoop(name, port, authkey, ppid, debug=False):
if debug:
import os
cprint.cout(debug, '[%d] connecting to server at port localhost:%d, authkey=%s..\n'
% (os.getpid(), port, repr(authkey)), -1)
conn = multiprocessing.connection.Client(('localhost', int(port)), authkey=authkey)
if debug:
cprint.cout(debug, '[%d] connected; starting remote proxy.\n' % os.getpid(), -1)
global HANDLER
#ppid = 0 if not hasattr(os, 'getppid') else os.getppid()
HANDLER = RemoteEventHandler(conn, name, ppid, debug=debug)
while True:
try:
HANDLER.processRequests() # exception raised when the loop should exit
time.sleep(0.01)
except ClosedError:
HANDLER.debugMsg('Exiting server loop.')
sys.exit(0)
class ForkedProcess(RemoteEventHandler):
"""
ForkedProcess is a substitute for Process that uses os.fork() to generate a new process.
This is much faster than starting a completely new interpreter and child processes
automatically have a copy of the entire program state from before the fork. This
makes it an appealing approach when parallelizing expensive computations. (see
also Parallelizer)
However, fork() comes with some caveats and limitations:
- fork() is not available on Windows.
- It is not possible to have a QApplication in both parent and child process
(unless both QApplications are created _after_ the call to fork())
Attempts by the forked process to access Qt GUI elements created by the parent
will most likely cause the child to crash.
- Likewise, database connections are unlikely to function correctly in a forked child.
- Threads are not copied by fork(); the new process
will have only one thread that starts wherever fork() was called in the parent process.
- Forked processes are unceremoniously terminated when join() is called; they are not
given any opportunity to clean up. (This prevents them calling any cleanup code that
was only intended to be used by the parent process)
- Normally when fork()ing, open file handles are shared with the parent process,
which is potentially dangerous. ForkedProcess is careful to close all file handles
that are not explicitly needed--stdout, stderr, and a single pipe to the parent
process.
"""
def __init__(self, name=None, target=0, preProxy=None, randomReseed=True):
"""
When initializing, an optional target may be given.
If no target is specified, self.eventLoop will be used.
If None is given, no target will be called (and it will be up
to the caller to properly shut down the forked process)
preProxy may be a dict of values that will appear as ObjectProxy
in the remote process (but do not need to be sent explicitly since
they are available immediately before the call to fork().
Proxies will be availabe as self.proxies[name].
If randomReseed is True, the built-in random and numpy.random generators
will be reseeded in the child process.
"""
self.hasJoined = False
if target == 0:
target = self.eventLoop
if name is None:
name = str(self)
conn, remoteConn = multiprocessing.Pipe()
proxyIDs = {}
if preProxy is not None:
for k, v in preProxy.items():
proxyId = LocalObjectProxy.registerObject(v)
proxyIDs[k] = proxyId
ppid = os.getpid() # write this down now; windows doesn't have getppid
pid = os.fork()
if pid == 0:
self.isParent = False
## We are now in the forked process; need to be extra careful what we touch while here.
## - no reading/writing file handles/sockets owned by parent process (stdout is ok)
## - don't touch QtGui or QApplication at all; these are landmines.
## - don't let the process call exit handlers
os.setpgrp() ## prevents signals (notably keyboard interrupt) being forwarded from parent to this process
## close all file handles we do not want shared with parent
conn.close()
sys.stdin.close() ## otherwise we screw with interactive prompts.
fid = remoteConn.fileno()
os.closerange(3, fid)
os.closerange(fid+1, 4096) ## just guessing on the maximum descriptor count..
## Override any custom exception hooks
def excepthook(*args):
import traceback
traceback.print_exception(*args)
sys.excepthook = excepthook
## Make it harder to access QApplication instance
for qtlib in ('PyQt4', 'PySide', 'PyQt5'):
if qtlib in sys.modules:
sys.modules[qtlib+'.QtGui'].QApplication = None
sys.modules.pop(qtlib+'.QtGui', None)
sys.modules.pop(qtlib+'.QtCore', None)
## sabotage atexit callbacks
atexit._exithandlers = []
atexit.register(lambda: os._exit(0))
if randomReseed:
if 'numpy.random' in sys.modules:
sys.modules['numpy.random'].seed(os.getpid() ^ int(time.time()*10000%10000))
if 'random' in sys.modules:
sys.modules['random'].seed(os.getpid() ^ int(time.time()*10000%10000))
#ppid = 0 if not hasattr(os, 'getppid') else os.getppid()
RemoteEventHandler.__init__(self, remoteConn, name+'_child', pid=ppid)
self.forkedProxies = {}
for name, proxyId in proxyIDs.items():
self.forkedProxies[name] = ObjectProxy(ppid, proxyId=proxyId, typeStr=repr(preProxy[name]))
if target is not None:
target()
else:
self.isParent = True
self.childPid = pid
remoteConn.close()
RemoteEventHandler.handlers = {} ## don't want to inherit any of this from the parent.
RemoteEventHandler.__init__(self, conn, name+'_parent', pid=pid)
atexit.register(self.join)
def eventLoop(self):
while True:
try:
self.processRequests() # exception raised when the loop should exit
time.sleep(0.01)
except ClosedError:
break
except:
print("Error occurred in forked event loop:")
sys.excepthook(*sys.exc_info())
sys.exit(0)
def join(self, timeout=10):
if self.hasJoined:
return
#os.kill(pid, 9)
try:
self.close(callSync='sync', timeout=timeout, noCleanup=True) ## ask the child process to exit and require that it return a confirmation.
except IOError: ## probably remote process has already quit
pass
try:
os.waitpid(self.childPid, 0)
except OSError: ## probably remote process has already quit
pass
self.conn.close() # don't leak file handles!
self.hasJoined = True
def kill(self):
"""Immediately kill the forked remote process.
This is generally safe because forked processes are already
expected to _avoid_ any cleanup at exit."""
os.kill(self.childPid, signal.SIGKILL)
self.hasJoined = True
##Special set of subclasses that implement a Qt event loop instead.
class RemoteQtEventHandler(RemoteEventHandler):
def __init__(self, *args, **kwds):
RemoteEventHandler.__init__(self, *args, **kwds)
def startEventTimer(self):
from ..Qt import QtGui, QtCore
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.processRequests)
self.timer.start(10)
def processRequests(self):
try:
RemoteEventHandler.processRequests(self)
except ClosedError:
from ..Qt import QtGui, QtCore
QtGui.QApplication.instance().quit()
self.timer.stop()
#raise SystemExit
class QtProcess(Process):
"""
QtProcess is essentially the same as Process, with two major differences:
- The remote process starts by running startQtEventLoop() which creates a
QApplication in the remote process and uses a QTimer to trigger
remote event processing. This allows the remote process to have its own
GUI.
- A QTimer is also started on the parent process which polls for requests
from the child process. This allows Qt signals emitted within the child
process to invoke slots on the parent process and vice-versa. This can
be disabled using processRequests=False in the constructor.
Example::
proc = QtProcess()
rQtGui = proc._import('PyQt4.QtGui')
btn = rQtGui.QPushButton('button on child process')
btn.show()
def slot():
print('slot invoked on parent process')
btn.clicked.connect(proxy(slot)) # be sure to send a proxy of the slot
"""
def __init__(self, **kwds):
if 'target' not in kwds:
kwds['target'] = startQtEventLoop
from ..Qt import QtGui ## avoid module-level import to keep bootstrap snappy.
self._processRequests = kwds.pop('processRequests', True)
if self._processRequests and QtGui.QApplication.instance() is None:
raise Exception("Must create QApplication before starting QtProcess, or use QtProcess(processRequests=False)")
Process.__init__(self, **kwds)
self.startEventTimer()
def startEventTimer(self):
from ..Qt import QtCore ## avoid module-level import to keep bootstrap snappy.
self.timer = QtCore.QTimer()
if self._processRequests:
self.startRequestProcessing()
def startRequestProcessing(self, interval=0.01):
"""Start listening for requests coming from the child process.
This allows signals to be connected from the child process to the parent.
"""
self.timer.timeout.connect(self.processRequests)
self.timer.start(interval*1000)
def stopRequestProcessing(self):
self.timer.stop()
def processRequests(self):
try:
Process.processRequests(self)
except ClosedError:
self.timer.stop()
def startQtEventLoop(name, port, authkey, ppid, debug=False):
if debug:
import os
cprint.cout(debug, '[%d] connecting to server at port localhost:%d, authkey=%s..\n' % (os.getpid(), port, repr(authkey)), -1)
conn = multiprocessing.connection.Client(('localhost', int(port)), authkey=authkey)
if debug:
cprint.cout(debug, '[%d] connected; starting remote proxy.\n' % os.getpid(), -1)
from ..Qt import QtGui, QtCore
app = QtGui.QApplication.instance()
#print app
if app is None:
app = QtGui.QApplication([])
app.setQuitOnLastWindowClosed(False) ## generally we want the event loop to stay open
## until it is explicitly closed by the parent process.
global HANDLER
HANDLER = RemoteQtEventHandler(conn, name, ppid, debug=debug)
HANDLER.startEventTimer()
app.exec_()
import threading
class FileForwarder(threading.Thread):
"""
Background thread that forwards data from one pipe to another.
This is used to catch data from stdout/stderr of the child process
and print it back out to stdout/stderr. We need this because this
bug: http://bugs.python.org/issue3905 _requires_ us to catch
stdout/stderr.
*output* may be a file or 'stdout' or 'stderr'. In the latter cases,
sys.stdout/stderr are retrieved once for every line that is output,
which ensures that the correct behavior is achieved even if
sys.stdout/stderr are replaced at runtime.
"""
def __init__(self, input, output, color):
threading.Thread.__init__(self)
self.input = input
self.output = output
self.lock = threading.Lock()
self.daemon = True
self.color = color
self.finish = threading.Event()
self.start()
def run(self):
if self.output == 'stdout' and self.color is not False:
while not self.finish.is_set():
line = self.input.readline()
with self.lock:
cprint.cout(self.color, line, -1)
elif self.output == 'stderr' and self.color is not False:
while not self.finish.is_set():
line = self.input.readline()
with self.lock:
cprint.cerr(self.color, line, -1)
else:
if isinstance(self.output, str):
self.output = getattr(sys, self.output)
while not self.finish.is_set():
line = self.input.readline()
with self.lock:
self.output.write(line.decode('utf8'))
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/dockarea/DockDrop.py | .py | 4,087 | 129 | # -*- coding: utf-8 -*-
from ..Qt import QtCore, QtGui
class DockDrop(object):
"""Provides dock-dropping methods"""
def __init__(self, allowedAreas=None):
object.__init__(self)
if allowedAreas is None:
allowedAreas = ['center', 'right', 'left', 'top', 'bottom']
self.allowedAreas = set(allowedAreas)
self.setAcceptDrops(True)
self.dropArea = None
self.overlay = DropAreaOverlay(self)
self.overlay.raise_()
def resizeOverlay(self, size):
self.overlay.resize(size)
def raiseOverlay(self):
self.overlay.raise_()
def dragEnterEvent(self, ev):
src = ev.source()
if hasattr(src, 'implements') and src.implements('dock'):
#print "drag enter accept"
ev.accept()
else:
#print "drag enter ignore"
ev.ignore()
def dragMoveEvent(self, ev):
#print "drag move"
ld = ev.pos().x()
rd = self.width() - ld
td = ev.pos().y()
bd = self.height() - td
mn = min(ld, rd, td, bd)
if mn > 30:
self.dropArea = "center"
elif (ld == mn or td == mn) and mn > self.height()/3.:
self.dropArea = "center"
elif (rd == mn or ld == mn) and mn > self.width()/3.:
self.dropArea = "center"
elif rd == mn:
self.dropArea = "right"
elif ld == mn:
self.dropArea = "left"
elif td == mn:
self.dropArea = "top"
elif bd == mn:
self.dropArea = "bottom"
if ev.source() is self and self.dropArea == 'center':
#print " no self-center"
self.dropArea = None
ev.ignore()
elif self.dropArea not in self.allowedAreas:
#print " not allowed"
self.dropArea = None
ev.ignore()
else:
#print " ok"
ev.accept()
self.overlay.setDropArea(self.dropArea)
def dragLeaveEvent(self, ev):
self.dropArea = None
self.overlay.setDropArea(self.dropArea)
def dropEvent(self, ev):
area = self.dropArea
if area is None:
return
if area == 'center':
area = 'above'
self.area.moveDock(ev.source(), area, self)
self.dropArea = None
self.overlay.setDropArea(self.dropArea)
class DropAreaOverlay(QtGui.QWidget):
"""Overlay widget that draws drop areas during a drag-drop operation"""
def __init__(self, parent):
QtGui.QWidget.__init__(self, parent)
self.dropArea = None
self.hide()
self.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents)
def setDropArea(self, area):
self.dropArea = area
if area is None:
self.hide()
else:
## Resize overlay to just the region where drop area should be displayed.
## This works around a Qt bug--can't display transparent widgets over QGLWidget
prgn = self.parent().rect()
rgn = QtCore.QRect(prgn)
w = min(30, prgn.width()/3.)
h = min(30, prgn.height()/3.)
if self.dropArea == 'left':
rgn.setWidth(w)
elif self.dropArea == 'right':
rgn.setLeft(rgn.left() + prgn.width() - w)
elif self.dropArea == 'top':
rgn.setHeight(h)
elif self.dropArea == 'bottom':
rgn.setTop(rgn.top() + prgn.height() - h)
elif self.dropArea == 'center':
rgn.adjust(w, h, -w, -h)
self.setGeometry(rgn)
self.show()
self.update()
def paintEvent(self, ev):
if self.dropArea is None:
return
p = QtGui.QPainter(self)
rgn = self.rect()
p.setBrush(QtGui.QBrush(QtGui.QColor(100, 100, 255, 50)))
p.setPen(QtGui.QPen(QtGui.QColor(50, 50, 150), 3))
p.drawRect(rgn)
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/dockarea/Container.py | .py | 9,003 | 284 | # -*- coding: utf-8 -*-
from ..Qt import QtCore, QtGui
import weakref
class Container(object):
#sigStretchChanged = QtCore.Signal() ## can't do this here; not a QObject.
def __init__(self, area):
object.__init__(self)
self.area = area
self._container = None
self._stretch = (10, 10)
self.stretches = weakref.WeakKeyDictionary()
def container(self):
return self._container
def containerChanged(self, c):
self._container = c
if c is None:
self.area = None
else:
self.area = c.area
def type(self):
return None
def insert(self, new, pos=None, neighbor=None):
if not isinstance(new, list):
new = [new]
for n in new:
# remove from existing parent first
n.setParent(None)
if neighbor is None:
if pos == 'before':
index = 0
else:
index = self.count()
else:
index = self.indexOf(neighbor)
if index == -1:
index = 0
if pos == 'after':
index += 1
for n in new:
#print "insert", n, " -> ", self, index
self._insertItem(n, index)
#print "change container", n, " -> ", self
n.containerChanged(self)
index += 1
n.sigStretchChanged.connect(self.childStretchChanged)
#print "child added", self
self.updateStretch()
def apoptose(self, propagate=True):
# if there is only one (or zero) item in this container, disappear.
# if propagate is True, then also attempt to apoptose parent containers.
cont = self._container
c = self.count()
if c > 1:
return
if c == 1: ## if there is one item, give it to the parent container (unless this is the top)
ch = self.widget(0)
if (self.area is not None and self is self.area.topContainer and not isinstance(ch, Container)) or self.container() is None:
return
self.container().insert(ch, 'before', self)
#print "apoptose:", self
self.close()
if propagate and cont is not None:
cont.apoptose()
def close(self):
self.setParent(None)
if self.area is not None and self.area.topContainer is self:
self.area.topContainer = None
self.containerChanged(None)
def childEvent(self, ev):
ch = ev.child()
if ev.removed() and hasattr(ch, 'sigStretchChanged'):
#print "Child", ev.child(), "removed, updating", self
try:
ch.sigStretchChanged.disconnect(self.childStretchChanged)
except:
pass
self.updateStretch()
def childStretchChanged(self):
#print "child", QtCore.QObject.sender(self), "changed shape, updating", self
self.updateStretch()
def setStretch(self, x=None, y=None):
#print "setStretch", self, x, y
self._stretch = (x, y)
self.sigStretchChanged.emit()
def updateStretch(self):
###Set the stretch values for this container to reflect its contents
pass
def stretch(self):
"""Return the stretch factors for this container"""
return self._stretch
class SplitContainer(Container, QtGui.QSplitter):
"""Horizontal or vertical splitter with some changes:
- save/restore works correctly
"""
sigStretchChanged = QtCore.Signal()
def __init__(self, area, orientation):
QtGui.QSplitter.__init__(self)
self.setOrientation(orientation)
Container.__init__(self, area)
#self.splitterMoved.connect(self.restretchChildren)
def _insertItem(self, item, index):
self.insertWidget(index, item)
item.show() ## need to show since it may have been previously hidden by tab
def saveState(self):
sizes = self.sizes()
if all([x == 0 for x in sizes]):
sizes = [10] * len(sizes)
return {'sizes': sizes}
def restoreState(self, state):
sizes = state['sizes']
self.setSizes(sizes)
for i in range(len(sizes)):
self.setStretchFactor(i, sizes[i])
def childEvent(self, ev):
QtGui.QSplitter.childEvent(self, ev)
Container.childEvent(self, ev)
#def restretchChildren(self):
#sizes = self.sizes()
#tot = sum(sizes)
class HContainer(SplitContainer):
def __init__(self, area):
SplitContainer.__init__(self, area, QtCore.Qt.Horizontal)
def type(self):
return 'horizontal'
def updateStretch(self):
##Set the stretch values for this container to reflect its contents
#print "updateStretch", self
x = 0
y = 0
sizes = []
for i in range(self.count()):
wx, wy = self.widget(i).stretch()
x += wx
y = max(y, wy)
sizes.append(wx)
#print " child", self.widget(i), wx, wy
self.setStretch(x, y)
#print sizes
tot = float(sum(sizes))
if tot == 0:
scale = 1.0
else:
scale = self.width() / tot
self.setSizes([int(s*scale) for s in sizes])
class VContainer(SplitContainer):
def __init__(self, area):
SplitContainer.__init__(self, area, QtCore.Qt.Vertical)
def type(self):
return 'vertical'
def updateStretch(self):
##Set the stretch values for this container to reflect its contents
#print "updateStretch", self
x = 0
y = 0
sizes = []
for i in range(self.count()):
wx, wy = self.widget(i).stretch()
y += wy
x = max(x, wx)
sizes.append(wy)
#print " child", self.widget(i), wx, wy
self.setStretch(x, y)
#print sizes
tot = float(sum(sizes))
if tot == 0:
scale = 1.0
else:
scale = self.height() / tot
self.setSizes([int(s*scale) for s in sizes])
class TContainer(Container, QtGui.QWidget):
sigStretchChanged = QtCore.Signal()
def __init__(self, area):
QtGui.QWidget.__init__(self)
Container.__init__(self, area)
self.layout = QtGui.QGridLayout()
self.layout.setSpacing(0)
self.layout.setContentsMargins(0,0,0,0)
self.setLayout(self.layout)
self.hTabLayout = QtGui.QHBoxLayout()
self.hTabBox = QtGui.QWidget()
self.hTabBox.setLayout(self.hTabLayout)
self.hTabLayout.setSpacing(2)
self.hTabLayout.setContentsMargins(0,0,0,0)
self.layout.addWidget(self.hTabBox, 0, 1)
self.stack = QtGui.QStackedWidget()
self.layout.addWidget(self.stack, 1, 1)
self.stack.childEvent = self.stackChildEvent
self.setLayout(self.layout)
for n in ['count', 'widget', 'indexOf']:
setattr(self, n, getattr(self.stack, n))
def _insertItem(self, item, index):
if not isinstance(item, Dock.Dock):
raise Exception("Tab containers may hold only docks, not other containers.")
self.stack.insertWidget(index, item)
self.hTabLayout.insertWidget(index, item.label)
#QtCore.QObject.connect(item.label, QtCore.SIGNAL('clicked'), self.tabClicked)
item.label.sigClicked.connect(self.tabClicked)
self.tabClicked(item.label)
def tabClicked(self, tab, ev=None):
if ev is None or ev.button() == QtCore.Qt.LeftButton:
for i in range(self.count()):
w = self.widget(i)
if w is tab.dock:
w.label.setDim(False)
self.stack.setCurrentIndex(i)
else:
w.label.setDim(True)
def raiseDock(self, dock):
"""Move *dock* to the top of the stack"""
self.stack.currentWidget().label.setDim(True)
self.stack.setCurrentWidget(dock)
dock.label.setDim(False)
def type(self):
return 'tab'
def saveState(self):
return {'index': self.stack.currentIndex()}
def restoreState(self, state):
self.stack.setCurrentIndex(state['index'])
def updateStretch(self):
##Set the stretch values for this container to reflect its contents
x = 0
y = 0
for i in range(self.count()):
wx, wy = self.widget(i).stretch()
x = max(x, wx)
y = max(y, wy)
self.setStretch(x, y)
def stackChildEvent(self, ev):
QtGui.QStackedWidget.childEvent(self.stack, ev)
Container.childEvent(self, ev)
from . import Dock
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/dockarea/__init__.py | .py | 53 | 2 | from .DockArea import DockArea
from .Dock import Dock | Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/dockarea/Dock.py | .py | 11,570 | 350 | from ..Qt import QtCore, QtGui
from .DockDrop import *
from ..widgets.VerticalLabel import VerticalLabel
from ..python2_3 import asUnicode
class Dock(QtGui.QWidget, DockDrop):
sigStretchChanged = QtCore.Signal()
sigClosed = QtCore.Signal(object)
def __init__(self, name, area=None, size=(10, 10), widget=None, hideTitle=False, autoOrientation=True, closable=False):
QtGui.QWidget.__init__(self)
DockDrop.__init__(self)
self._container = None
self._name = name
self.area = area
self.label = DockLabel(name, self, closable)
if closable:
self.label.sigCloseClicked.connect(self.close)
self.labelHidden = False
self.moveLabel = True ## If false, the dock is no longer allowed to move the label.
self.autoOrient = autoOrientation
self.orientation = 'horizontal'
#self.label.setAlignment(QtCore.Qt.AlignHCenter)
self.topLayout = QtGui.QGridLayout()
self.topLayout.setContentsMargins(0, 0, 0, 0)
self.topLayout.setSpacing(0)
self.setLayout(self.topLayout)
self.topLayout.addWidget(self.label, 0, 1)
self.widgetArea = QtGui.QWidget()
self.topLayout.addWidget(self.widgetArea, 1, 1)
self.layout = QtGui.QGridLayout()
self.layout.setContentsMargins(0, 0, 0, 0)
self.layout.setSpacing(0)
self.widgetArea.setLayout(self.layout)
self.widgetArea.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
self.widgets = []
self._container = None
self.currentRow = 0
#self.titlePos = 'top'
self.raiseOverlay()
self.hStyle = """
Dock > QWidget {
border: 1px solid #000;
border-radius: 5px;
border-top-left-radius: 0px;
border-top-right-radius: 0px;
border-top-width: 0px;
}"""
self.vStyle = """
Dock > QWidget {
border: 1px solid #000;
border-radius: 5px;
border-top-left-radius: 0px;
border-bottom-left-radius: 0px;
border-left-width: 0px;
}"""
self.nStyle = """
Dock > QWidget {
border: 1px solid #000;
border-radius: 5px;
}"""
self.dragStyle = """
Dock > QWidget {
border: 4px solid #00F;
border-radius: 5px;
}"""
self.setAutoFillBackground(False)
self.widgetArea.setStyleSheet(self.hStyle)
self.setStretch(*size)
if widget is not None:
self.addWidget(widget)
if hideTitle:
self.hideTitleBar()
def implements(self, name=None):
if name is None:
return ['dock']
else:
return name == 'dock'
def setStretch(self, x=None, y=None):
"""
Set the 'target' size for this Dock.
The actual size will be determined by comparing this Dock's
stretch value to the rest of the docks it shares space with.
"""
if x is None:
x = 0
if y is None:
y = 0
self._stretch = (x, y)
self.sigStretchChanged.emit()
def stretch(self):
return self._stretch
def hideTitleBar(self):
"""
Hide the title bar for this Dock.
This will prevent the Dock being moved by the user.
"""
self.label.hide()
self.labelHidden = True
if 'center' in self.allowedAreas:
self.allowedAreas.remove('center')
self.updateStyle()
def showTitleBar(self):
"""
Show the title bar for this Dock.
"""
self.label.show()
self.labelHidden = False
self.allowedAreas.add('center')
self.updateStyle()
def title(self):
"""
Gets the text displayed in the title bar for this dock.
"""
return asUnicode(self.label.text())
def setTitle(self, text):
"""
Sets the text displayed in title bar for this Dock.
"""
self.label.setText(text)
def setOrientation(self, o='auto', force=False):
"""
Sets the orientation of the title bar for this Dock.
Must be one of 'auto', 'horizontal', or 'vertical'.
By default ('auto'), the orientation is determined
based on the aspect ratio of the Dock.
"""
if o == 'auto' and self.autoOrient:
if self.container().type() == 'tab':
o = 'horizontal'
elif self.width() > self.height()*1.5:
o = 'vertical'
else:
o = 'horizontal'
if force or self.orientation != o:
self.orientation = o
self.label.setOrientation(o)
self.updateStyle()
def updateStyle(self):
## updates orientation and appearance of title bar
if self.labelHidden:
self.widgetArea.setStyleSheet(self.nStyle)
elif self.orientation == 'vertical':
self.label.setOrientation('vertical')
if self.moveLabel:
self.topLayout.addWidget(self.label, 1, 0)
self.widgetArea.setStyleSheet(self.vStyle)
else:
self.label.setOrientation('horizontal')
if self.moveLabel:
self.topLayout.addWidget(self.label, 0, 1)
self.widgetArea.setStyleSheet(self.hStyle)
def resizeEvent(self, ev):
self.setOrientation()
self.resizeOverlay(self.size())
def name(self):
return self._name
def addWidget(self, widget, row=None, col=0, rowspan=1, colspan=1):
"""
Add a new widget to the interior of this Dock.
Each Dock uses a QGridLayout to arrange widgets within.
"""
if row is None:
row = self.currentRow
self.currentRow = max(row+1, self.currentRow)
self.widgets.append(widget)
self.layout.addWidget(widget, row, col, rowspan, colspan)
self.raiseOverlay()
def startDrag(self):
self.drag = QtGui.QDrag(self)
mime = QtCore.QMimeData()
self.drag.setMimeData(mime)
self.widgetArea.setStyleSheet(self.dragStyle)
self.update()
action = self.drag.exec_()
self.updateStyle()
def float(self):
self.area.floatDock(self)
def container(self):
return self._container
def containerChanged(self, c):
if self._container is not None:
# ask old container to close itself if it is no longer needed
self._container.apoptose()
self._container = c
if c is None:
self.area = None
else:
self.area = c.area
if c.type() != 'tab':
self.moveLabel = True
self.label.setDim(False)
else:
self.moveLabel = False
self.setOrientation(force=True)
def raiseDock(self):
"""If this Dock is stacked underneath others, raise it to the top."""
self.container().raiseDock(self)
def close(self):
"""Remove this dock from the DockArea it lives inside."""
self.setParent(None)
self.label.setParent(None)
self._container.apoptose()
self._container = None
self.sigClosed.emit(self)
def __repr__(self):
return "<Dock %s %s>" % (self.name(), self.stretch())
## PySide bug: We need to explicitly redefine these methods
## or else drag/drop events will not be delivered.
def dragEnterEvent(self, *args):
DockDrop.dragEnterEvent(self, *args)
def dragMoveEvent(self, *args):
DockDrop.dragMoveEvent(self, *args)
def dragLeaveEvent(self, *args):
DockDrop.dragLeaveEvent(self, *args)
def dropEvent(self, *args):
DockDrop.dropEvent(self, *args)
class DockLabel(VerticalLabel):
sigClicked = QtCore.Signal(object, object)
sigCloseClicked = QtCore.Signal()
def __init__(self, text, dock, showCloseButton):
self.dim = False
self.fixedWidth = False
VerticalLabel.__init__(self, text, orientation='horizontal', forceWidth=False)
self.setAlignment(QtCore.Qt.AlignTop|QtCore.Qt.AlignHCenter)
self.dock = dock
self.updateStyle()
self.setAutoFillBackground(False)
self.startedDrag = False
self.closeButton = None
if showCloseButton:
self.closeButton = QtGui.QToolButton(self)
self.closeButton.clicked.connect(self.sigCloseClicked)
self.closeButton.setIcon(QtGui.QApplication.style().standardIcon(QtGui.QStyle.SP_TitleBarCloseButton))
def updateStyle(self):
r = '3px'
if self.dim:
fg = '#aaa'
bg = '#44a'
border = '#339'
else:
fg = '#fff'
bg = '#66c'
border = '#55B'
if self.orientation == 'vertical':
self.vStyle = """DockLabel {
background-color : %s;
color : %s;
border-top-right-radius: 0px;
border-top-left-radius: %s;
border-bottom-right-radius: 0px;
border-bottom-left-radius: %s;
border-width: 0px;
border-right: 2px solid %s;
padding-top: 3px;
padding-bottom: 3px;
}""" % (bg, fg, r, r, border)
self.setStyleSheet(self.vStyle)
else:
self.hStyle = """DockLabel {
background-color : %s;
color : %s;
border-top-right-radius: %s;
border-top-left-radius: %s;
border-bottom-right-radius: 0px;
border-bottom-left-radius: 0px;
border-width: 0px;
border-bottom: 2px solid %s;
padding-left: 3px;
padding-right: 3px;
}""" % (bg, fg, r, r, border)
self.setStyleSheet(self.hStyle)
def setDim(self, d):
if self.dim != d:
self.dim = d
self.updateStyle()
def setOrientation(self, o):
VerticalLabel.setOrientation(self, o)
self.updateStyle()
def mousePressEvent(self, ev):
if ev.button() == QtCore.Qt.LeftButton:
self.pressPos = ev.pos()
self.startedDrag = False
ev.accept()
def mouseMoveEvent(self, ev):
if not self.startedDrag and (ev.pos() - self.pressPos).manhattanLength() > QtGui.QApplication.startDragDistance():
self.dock.startDrag()
ev.accept()
def mouseReleaseEvent(self, ev):
ev.accept()
if not self.startedDrag:
self.sigClicked.emit(self, ev)
def mouseDoubleClickEvent(self, ev):
if ev.button() == QtCore.Qt.LeftButton:
self.dock.float()
def resizeEvent (self, ev):
if self.closeButton:
if self.orientation == 'vertical':
size = ev.size().width()
pos = QtCore.QPoint(0, 0)
else:
size = ev.size().height()
pos = QtCore.QPoint(ev.size().width() - size, 0)
self.closeButton.setFixedSize(QtCore.QSize(size, size))
self.closeButton.move(pos)
super(DockLabel,self).resizeEvent(ev)
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/dockarea/DockArea.py | .py | 14,065 | 386 | # -*- coding: utf-8 -*-
import weakref
from ..Qt import QtCore, QtGui
from .Container import *
from .DockDrop import *
from .Dock import Dock
from .. import debug as debug
from ..python2_3 import basestring
class DockArea(Container, QtGui.QWidget, DockDrop):
def __init__(self, parent=None, temporary=False, home=None):
Container.__init__(self, self)
QtGui.QWidget.__init__(self, parent=parent)
DockDrop.__init__(self, allowedAreas=['left', 'right', 'top', 'bottom'])
self.layout = QtGui.QVBoxLayout()
self.layout.setContentsMargins(0,0,0,0)
self.layout.setSpacing(0)
self.setLayout(self.layout)
self.docks = weakref.WeakValueDictionary()
self.topContainer = None
self.raiseOverlay()
self.temporary = temporary
self.tempAreas = []
self.home = home
def type(self):
return "top"
def addDock(self, dock=None, position='bottom', relativeTo=None, **kwds):
"""Adds a dock to this area.
============== =================================================================
**Arguments:**
dock The new Dock object to add. If None, then a new Dock will be
created.
position 'bottom', 'top', 'left', 'right', 'above', or 'below'
relativeTo If relativeTo is None, then the new Dock is added to fill an
entire edge of the window. If relativeTo is another Dock, then
the new Dock is placed adjacent to it (or in a tabbed
configuration for 'above' and 'below').
============== =================================================================
All extra keyword arguments are passed to Dock.__init__() if *dock* is
None.
"""
if dock is None:
dock = Dock(**kwds)
# store original area that the dock will return to when un-floated
if not self.temporary:
dock.orig_area = self
## Determine the container to insert this dock into.
## If there is no neighbor, then the container is the top.
if relativeTo is None or relativeTo is self:
if self.topContainer is None:
container = self
neighbor = None
else:
container = self.topContainer
neighbor = None
else:
if isinstance(relativeTo, basestring):
relativeTo = self.docks[relativeTo]
container = self.getContainer(relativeTo)
if container is None:
raise TypeError("Dock %s is not contained in a DockArea; cannot add another dock relative to it." % relativeTo)
neighbor = relativeTo
## what container type do we need?
neededContainer = {
'bottom': 'vertical',
'top': 'vertical',
'left': 'horizontal',
'right': 'horizontal',
'above': 'tab',
'below': 'tab'
}[position]
## Can't insert new containers into a tab container; insert outside instead.
if neededContainer != container.type() and container.type() == 'tab':
neighbor = container
container = container.container()
## Decide if the container we have is suitable.
## If not, insert a new container inside.
if neededContainer != container.type():
if neighbor is None:
container = self.addContainer(neededContainer, self.topContainer)
else:
container = self.addContainer(neededContainer, neighbor)
## Insert the new dock before/after its neighbor
insertPos = {
'bottom': 'after',
'top': 'before',
'left': 'before',
'right': 'after',
'above': 'before',
'below': 'after'
}[position]
#print "request insert", dock, insertPos, neighbor
old = dock.container()
container.insert(dock, insertPos, neighbor)
self.docks[dock.name()] = dock
if old is not None:
old.apoptose()
return dock
def moveDock(self, dock, position, neighbor):
"""
Move an existing Dock to a new location.
"""
## Moving to the edge of a tabbed dock causes a drop outside the tab box
if position in ['left', 'right', 'top', 'bottom'] and neighbor is not None and neighbor.container() is not None and neighbor.container().type() == 'tab':
neighbor = neighbor.container()
self.addDock(dock, position, neighbor)
def getContainer(self, obj):
if obj is None:
return self
return obj.container()
def makeContainer(self, typ):
if typ == 'vertical':
new = VContainer(self)
elif typ == 'horizontal':
new = HContainer(self)
elif typ == 'tab':
new = TContainer(self)
return new
def addContainer(self, typ, obj):
"""Add a new container around obj"""
new = self.makeContainer(typ)
container = self.getContainer(obj)
container.insert(new, 'before', obj)
#print "Add container:", new, " -> ", container
if obj is not None:
new.insert(obj)
self.raiseOverlay()
return new
def insert(self, new, pos=None, neighbor=None):
if self.topContainer is not None:
# Adding new top-level container; addContainer() should
# take care of giving the old top container a new home.
self.topContainer.containerChanged(None)
self.layout.addWidget(new)
new.containerChanged(self)
self.topContainer = new
self.raiseOverlay()
def count(self):
if self.topContainer is None:
return 0
return 1
def resizeEvent(self, ev):
self.resizeOverlay(self.size())
def addTempArea(self):
if self.home is None:
area = DockArea(temporary=True, home=self)
self.tempAreas.append(area)
win = TempAreaWindow(area)
area.win = win
win.show()
else:
area = self.home.addTempArea()
#print "added temp area", area, area.window()
return area
def floatDock(self, dock):
"""Removes *dock* from this DockArea and places it in a new window."""
area = self.addTempArea()
area.win.resize(dock.size())
area.moveDock(dock, 'top', None)
def removeTempArea(self, area):
self.tempAreas.remove(area)
#print "close window", area.window()
area.window().close()
def saveState(self):
"""
Return a serialized (storable) representation of the state of
all Docks in this DockArea."""
if self.topContainer is None:
main = None
else:
main = self.childState(self.topContainer)
state = {'main': main, 'float': []}
for a in self.tempAreas:
geo = a.win.geometry()
geo = (geo.x(), geo.y(), geo.width(), geo.height())
state['float'].append((a.saveState(), geo))
return state
def childState(self, obj):
if isinstance(obj, Dock):
return ('dock', obj.name(), {})
else:
childs = []
for i in range(obj.count()):
childs.append(self.childState(obj.widget(i)))
return (obj.type(), childs, obj.saveState())
def restoreState(self, state, missing='error', extra='bottom'):
"""
Restore Dock configuration as generated by saveState.
This function does not create any Docks--it will only
restore the arrangement of an existing set of Docks.
By default, docks that are described in *state* but do not exist
in the dock area will cause an exception to be raised. This behavior
can be changed by setting *missing* to 'ignore' or 'create'.
Extra docks that are in the dockarea but that are not mentioned in
*state* will be added to the bottom of the dockarea, unless otherwise
specified by the *extra* argument.
"""
## 1) make dict of all docks and list of existing containers
containers, docks = self.findAll()
oldTemps = self.tempAreas[:]
#print "found docks:", docks
## 2) create container structure, move docks into new containers
if state['main'] is not None:
self.buildFromState(state['main'], docks, self, missing=missing)
## 3) create floating areas, populate
for s in state['float']:
a = self.addTempArea()
a.buildFromState(s[0]['main'], docks, a, missing=missing)
a.win.setGeometry(*s[1])
a.apoptose() # ask temp area to close itself if it is empty
## 4) Add any remaining docks to a float
for d in docks.values():
if extra == 'float':
a = self.addTempArea()
a.addDock(d, 'below')
else:
self.moveDock(d, extra, None)
#print "\nKill old containers:"
## 5) kill old containers
for c in containers:
c.close()
for a in oldTemps:
a.apoptose()
def buildFromState(self, state, docks, root, depth=0, missing='error'):
typ, contents, state = state
pfx = " " * depth
if typ == 'dock':
try:
obj = docks[contents]
del docks[contents]
except KeyError:
if missing == 'error':
raise Exception('Cannot restore dock state; no dock with name "%s"' % contents)
elif missing == 'create':
obj = Dock(name=contents)
elif missing == 'ignore':
return
else:
raise ValueError('"missing" argument must be one of "error", "create", or "ignore".')
else:
obj = self.makeContainer(typ)
root.insert(obj, 'after')
#print pfx+"Add:", obj, " -> ", root
if typ != 'dock':
for o in contents:
self.buildFromState(o, docks, obj, depth+1, missing=missing)
# remove this container if possible. (there are valid situations when a restore will
# generate empty containers, such as when using missing='ignore')
obj.apoptose(propagate=False)
obj.restoreState(state) ## this has to be done later?
def findAll(self, obj=None, c=None, d=None):
if obj is None:
obj = self.topContainer
## check all temp areas first
if c is None:
c = []
d = {}
for a in self.tempAreas:
c1, d1 = a.findAll()
c.extend(c1)
d.update(d1)
if isinstance(obj, Dock):
d[obj.name()] = obj
elif obj is not None:
c.append(obj)
for i in range(obj.count()):
o2 = obj.widget(i)
c2, d2 = self.findAll(o2)
c.extend(c2)
d.update(d2)
return (c, d)
def apoptose(self, propagate=True):
# remove top container if possible, close this area if it is temporary.
#print "apoptose area:", self.temporary, self.topContainer, self.topContainer.count()
if self.topContainer is None or self.topContainer.count() == 0:
self.topContainer = None
if self.temporary:
self.home.removeTempArea(self)
#self.close()
def clear(self):
docks = self.findAll()[1]
for dock in docks.values():
dock.close()
## PySide bug: We need to explicitly redefine these methods
## or else drag/drop events will not be delivered.
def dragEnterEvent(self, *args):
DockDrop.dragEnterEvent(self, *args)
def dragMoveEvent(self, *args):
DockDrop.dragMoveEvent(self, *args)
def dragLeaveEvent(self, *args):
DockDrop.dragLeaveEvent(self, *args)
def dropEvent(self, *args):
DockDrop.dropEvent(self, *args)
def printState(self, state=None, name='Main'):
# for debugging
if state is None:
state = self.saveState()
print("=== %s dock area ===" % name)
if state['main'] is None:
print(" (empty)")
else:
self._printAreaState(state['main'])
for i, float in enumerate(state['float']):
self.printState(float[0], name='float %d' % i)
def _printAreaState(self, area, indent=0):
if area[0] == 'dock':
print(" " * indent + area[0] + " " + str(area[1:]))
return
else:
print(" " * indent + area[0])
for ch in area[1]:
self._printAreaState(ch, indent+1)
class TempAreaWindow(QtGui.QWidget):
def __init__(self, area, **kwargs):
QtGui.QWidget.__init__(self, **kwargs)
self.layout = QtGui.QGridLayout()
self.setLayout(self.layout)
self.layout.setContentsMargins(0, 0, 0, 0)
self.dockarea = area
self.layout.addWidget(area)
def closeEvent(self, *args):
# restore docks to their original area
docks = self.dockarea.findAll()[1]
for dock in docks.values():
if hasattr(dock, 'orig_area'):
dock.orig_area.addDock(dock, )
# clear dock area, and close remaining docks
self.dockarea.clear()
QtGui.QWidget.closeEvent(self, *args)
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/dockarea/tests/test_dockarea.py | .py | 6,186 | 190 | # -*- coding: utf-8 -*-
import pytest
import pyqtgraph as pg
from pyqtgraph.ordereddict import OrderedDict
pg.mkQApp()
import pyqtgraph.dockarea as da
def test_dockarea():
a = da.DockArea()
d1 = da.Dock("dock 1")
a.addDock(d1, 'left')
assert a.topContainer is d1.container()
assert d1.container().container() is a
assert d1.area is a
assert a.topContainer.widget(0) is d1
d2 = da.Dock("dock 2")
a.addDock(d2, 'right')
assert a.topContainer is d1.container()
assert a.topContainer is d2.container()
assert d1.container().container() is a
assert d2.container().container() is a
assert d2.area is a
assert a.topContainer.widget(0) is d1
assert a.topContainer.widget(1) is d2
d3 = da.Dock("dock 3")
a.addDock(d3, 'bottom')
assert a.topContainer is d3.container()
assert d2.container().container() is d3.container()
assert d1.container().container() is d3.container()
assert d1.container().container().container() is a
assert d2.container().container().container() is a
assert d3.container().container() is a
assert d3.area is a
assert d2.area is a
assert a.topContainer.widget(0) is d1.container()
assert a.topContainer.widget(1) is d3
d4 = da.Dock("dock 4")
a.addDock(d4, 'below', d3)
assert d4.container().type() == 'tab'
assert d4.container() is d3.container()
assert d3.container().container() is d2.container().container()
assert d4.area is a
a.printState()
# layout now looks like:
# vcontainer
# hcontainer
# dock 1
# dock 2
# tcontainer
# dock 3
# dock 4
# test save/restore state
state = a.saveState()
a2 = da.DockArea()
# default behavior is to raise exception if docks are missing
with pytest.raises(Exception):
a2.restoreState(state)
# test restore with ignore missing
a2.restoreState(state, missing='ignore')
assert a2.topContainer is None
# test restore with auto-create
a2.restoreState(state, missing='create')
assert a2.saveState() == state
a2.printState()
# double-check that state actually matches the output of saveState()
c1 = a2.topContainer
assert c1.type() == 'vertical'
c2 = c1.widget(0)
c3 = c1.widget(1)
assert c2.type() == 'horizontal'
assert c2.widget(0).name() == 'dock 1'
assert c2.widget(1).name() == 'dock 2'
assert c3.type() == 'tab'
assert c3.widget(0).name() == 'dock 3'
assert c3.widget(1).name() == 'dock 4'
# test restore with docks already present
a3 = da.DockArea()
a3docks = []
for i in range(1, 5):
dock = da.Dock('dock %d' % i)
a3docks.append(dock)
a3.addDock(dock, 'right')
a3.restoreState(state)
assert a3.saveState() == state
# test restore with extra docks present
a3 = da.DockArea()
a3docks = []
for i in [1, 2, 5, 4, 3]:
dock = da.Dock('dock %d' % i)
a3docks.append(dock)
a3.addDock(dock, 'left')
a3.restoreState(state)
a3.printState()
# test a more complex restore
a4 = da.DockArea()
state1 = {'float': [], 'main':
('horizontal', [
('vertical', [
('horizontal', [
('tab', [
('dock', 'dock1', {}),
('dock', 'dock2', {}),
('dock', 'dock3', {}),
('dock', 'dock4', {})
], {'index': 1}),
('vertical', [
('dock', 'dock5', {}),
('horizontal', [
('dock', 'dock6', {}),
('dock', 'dock7', {})
], {'sizes': [184, 363]})
], {'sizes': [355, 120]})
], {'sizes': [9, 552]})
], {'sizes': [480]}),
('dock', 'dock8', {})
], {'sizes': [566, 69]})
}
state2 = {'float': [], 'main':
('horizontal', [
('vertical', [
('horizontal', [
('dock', 'dock2', {}),
('vertical', [
('dock', 'dock5', {}),
('horizontal', [
('dock', 'dock6', {}),
('dock', 'dock7', {})
], {'sizes': [492, 485]})
], {'sizes': [936, 0]})
], {'sizes': [172, 982]})
], {'sizes': [941]}),
('vertical', [
('dock', 'dock8', {}),
('dock', 'dock4', {}),
('dock', 'dock1', {})
], {'sizes': [681, 225, 25]})
], {'sizes': [1159, 116]})}
a4.restoreState(state1, missing='create')
# dock3 not mentioned in restored state; stays in dockarea by default
c, d = a4.findAll()
assert d['dock3'].area is a4
a4.restoreState(state2, missing='ignore', extra='float')
a4.printState()
c, d = a4.findAll()
# dock3 not mentioned in restored state; goes to float due to `extra` argument
assert d['dock3'].area is not a4
assert d['dock1'].container() is d['dock4'].container() is d['dock8'].container()
assert d['dock6'].container() is d['dock7'].container()
assert a4 is d['dock2'].area is d['dock2'].container().container().container()
assert a4 is d['dock5'].area is d['dock5'].container().container().container().container()
# States should be the same with two exceptions:
# dock3 is in a float because it does not appear in state2
# a superfluous vertical splitter in state2 has been removed
state4 = a4.saveState()
state4['main'][1][0] = state4['main'][1][0][1][0]
assert clean_state(state4['main']) == clean_state(state2['main'])
def clean_state(state):
# return state dict with sizes removed
ch = [clean_state(x) for x in state[1]] if isinstance(state[1], list) else state[1]
state = (state[0], ch, {})
if __name__ == '__main__':
test_dockarea()
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/dockarea/tests/test_dock.py | .py | 669 | 29 | # -*- coding: utf-8 -*-
#import sip
#sip.setapi('QString', 1)
import pyqtgraph as pg
pg.mkQApp()
import pyqtgraph.dockarea as da
def test_dock():
name = pg.asUnicode("évènts_zàhéér")
dock = da.Dock(name=name)
# make sure unicode names work correctly
assert dock.name() == name
# no surprises in return type.
assert type(dock.name()) == type(name)
def test_closable_dock():
name = "Test close dock"
dock = da.Dock(name=name, closable=True)
assert dock.label.closeButton != None
def test_hide_title_dock():
name = "Test hide title dock"
dock = da.Dock(name=name, hideTitle=True)
assert dock.labelHidden == True
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/tests/test_reload.py | .py | 3,536 | 118 | import tempfile, os, sys, shutil
import pyqtgraph as pg
import pyqtgraph.reload
pgpath = os.path.join(os.path.dirname(pg.__file__), '..')
pgpath_repr = repr(pgpath)
# make temporary directory to write module code
path = None
def setup_module():
# make temporary directory to write module code
global path
path = tempfile.mkdtemp()
sys.path.insert(0, path)
def teardown_module():
global path
shutil.rmtree(path)
sys.path.remove(path)
code = """
import sys
sys.path.append({path_repr})
import pyqtgraph as pg
class C(pg.QtCore.QObject):
sig = pg.QtCore.Signal()
def fn(self):
print("{msg}")
"""
def remove_cache(mod):
if os.path.isfile(mod+'c'):
os.remove(mod+'c')
cachedir = os.path.join(os.path.dirname(mod), '__pycache__')
if os.path.isdir(cachedir):
shutil.rmtree(cachedir)
def test_reload():
py3 = sys.version_info >= (3,)
# write a module
mod = os.path.join(path, 'reload_test_mod.py')
print("\nRELOAD FILE:", mod)
open(mod, 'w').write(code.format(path_repr=pgpath_repr, msg="C.fn() Version1"))
# import the new module
import reload_test_mod
print("RELOAD MOD:", reload_test_mod.__file__)
c = reload_test_mod.C()
c.sig.connect(c.fn)
if py3:
v1 = (reload_test_mod.C, reload_test_mod.C.sig, reload_test_mod.C.fn, c.sig, c.fn, c.fn.__func__)
else:
v1 = (reload_test_mod.C, reload_test_mod.C.sig, reload_test_mod.C.fn, reload_test_mod.C.fn.__func__, c.sig, c.fn, c.fn.__func__)
# write again and reload
open(mod, 'w').write(code.format(path_repr=pgpath_repr, msg="C.fn() Version2"))
remove_cache(mod)
pg.reload.reloadAll(path, debug=True)
if py3:
v2 = (reload_test_mod.C, reload_test_mod.C.sig, reload_test_mod.C.fn, c.sig, c.fn, c.fn.__func__)
else:
v2 = (reload_test_mod.C, reload_test_mod.C.sig, reload_test_mod.C.fn, reload_test_mod.C.fn.__func__, c.sig, c.fn, c.fn.__func__)
if not py3:
assert c.fn.im_class is v2[0]
oldcfn = pg.reload.getPreviousVersion(c.fn)
if oldcfn is None:
# Function did not reload; are we using pytest's assertion rewriting?
raise Exception("Function did not reload. (This can happen when using py.test"
" with assertion rewriting; use --assert=plain for this test.)")
if py3:
assert oldcfn.__func__ is v1[2]
else:
assert oldcfn.im_class is v1[0]
assert oldcfn.__func__ is v1[2].__func__
assert oldcfn.__self__ is c
# write again and reload
open(mod, 'w').write(code.format(path_repr=pgpath_repr, msg="C.fn() Version2"))
remove_cache(mod)
pg.reload.reloadAll(path, debug=True)
if py3:
v3 = (reload_test_mod.C, reload_test_mod.C.sig, reload_test_mod.C.fn, c.sig, c.fn, c.fn.__func__)
else:
v3 = (reload_test_mod.C, reload_test_mod.C.sig, reload_test_mod.C.fn, reload_test_mod.C.fn.__func__, c.sig, c.fn, c.fn.__func__)
#for i in range(len(old)):
#print id(old[i]), id(new1[i]), id(new2[i]), old[i], new1[i]
cfn1 = pg.reload.getPreviousVersion(c.fn)
cfn2 = pg.reload.getPreviousVersion(cfn1)
if py3:
assert cfn1.__func__ is v2[2]
assert cfn2.__func__ is v1[2]
else:
assert cfn1.__func__ is v2[2].__func__
assert cfn2.__func__ is v1[2].__func__
assert cfn1.im_class is v2[0]
assert cfn2.im_class is v1[0]
assert cfn1.__self__ is c
assert cfn2.__self__ is c
pg.functions.disconnect(c.sig, c.fn)
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/tests/test_exit_crash.py | .py | 2,006 | 81 | # -*- coding: utf-8 -*-
import os
import sys
import subprocess
import tempfile
import pyqtgraph as pg
import six
import pytest
import textwrap
import time
code = """
import sys
sys.path.insert(0, '{path}')
import pyqtgraph as pg
app = pg.mkQApp()
w = pg.{classname}({args})
"""
skipmessage = ('unclear why this test is failing. skipping until someone has'
' time to fix it')
def call_with_timeout(*args, **kwargs):
"""Mimic subprocess.call with timeout for python < 3.3"""
wait_per_poll = 0.1
try:
timeout = kwargs.pop('timeout')
except KeyError:
timeout = 10
rc = None
p = subprocess.Popen(*args, **kwargs)
for i in range(int(timeout/wait_per_poll)):
rc = p.poll()
if rc is not None:
break
time.sleep(wait_per_poll)
return rc
@pytest.mark.skipif(True, reason=skipmessage)
def test_exit_crash():
# For each Widget subclass, run a simple python script that creates an
# instance and then shuts down. The intent is to check for segmentation
# faults when each script exits.
tmp = tempfile.mktemp(".py")
path = os.path.dirname(pg.__file__)
initArgs = {
'CheckTable': "[]",
'ProgressDialog': '"msg"',
'VerticalLabel': '"msg"',
}
for name in dir(pg):
obj = getattr(pg, name)
if not isinstance(obj, type) or not issubclass(obj, pg.QtGui.QWidget):
continue
print(name)
argstr = initArgs.get(name, "")
with open(tmp, 'w') as f:
f.write(code.format(path=path, classname=name, args=argstr))
proc = subprocess.Popen([sys.executable, tmp])
assert proc.wait() == 0
os.remove(tmp)
def test_pg_exit():
# test the pg.exit() function
code = textwrap.dedent("""
import pyqtgraph as pg
app = pg.mkQApp()
pg.plot()
pg.exit()
""")
rc = call_with_timeout([sys.executable, '-c', code], timeout=5, shell=False)
assert rc == 0
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/tests/test_configparser.py | .py | 832 | 37 | from pyqtgraph import configfile
import numpy as np
import tempfile, os
def test_longArrays():
"""
Test config saving and loading of long arrays.
"""
tmp = tempfile.mktemp(".cfg")
arr = np.arange(20)
configfile.writeConfigFile({'arr':arr}, tmp)
config = configfile.readConfigFile(tmp)
assert all(config['arr'] == arr)
os.remove(tmp)
def test_multipleParameters():
"""
Test config saving and loading of multiple parameters.
"""
tmp = tempfile.mktemp(".cfg")
par1 = [1,2,3]
par2 = "Test"
par3 = {'a':3,'b':'c'}
configfile.writeConfigFile({'par1':par1, 'par2':par2, 'par3':par3}, tmp)
config = configfile.readConfigFile(tmp)
assert config['par1'] == par1
assert config['par2'] == par2
assert config['par3'] == par3
os.remove(tmp)
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/tests/ui_testing.py | .py | 2,920 | 76 | import time
from ..Qt import QtCore, QtGui, QtTest, QT_LIB
def resizeWindow(win, w, h, timeout=2.0):
"""Resize a window and wait until it has the correct size.
This is required for unit testing on some platforms that do not guarantee
immediate response from the windowing system.
"""
QtGui.QApplication.processEvents()
# Sometimes the window size will switch multiple times before settling
# on its final size. Adding qWaitForWindowShown seems to help with this.
QtTest.QTest.qWaitForWindowShown(win)
win.resize(w, h)
start = time.time()
while True:
w1, h1 = win.width(), win.height()
if (w,h) == (w1,h1):
return
QtTest.QTest.qWait(10)
if time.time()-start > timeout:
raise TimeoutError("Window resize failed (requested %dx%d, got %dx%d)" % (w, h, w1, h1))
# Functions for generating user input events.
# We would like to use QTest for this purpose, but it seems to be broken.
# See: http://stackoverflow.com/questions/16299779/qt-qgraphicsview-unit-testing-how-to-keep-the-mouse-in-a-pressed-state
def mousePress(widget, pos, button, modifier=None):
if isinstance(widget, QtGui.QGraphicsView):
widget = widget.viewport()
if modifier is None:
modifier = QtCore.Qt.NoModifier
if QT_LIB != 'PyQt5' and isinstance(pos, QtCore.QPointF):
pos = pos.toPoint()
event = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, button, QtCore.Qt.NoButton, modifier)
QtGui.QApplication.sendEvent(widget, event)
def mouseRelease(widget, pos, button, modifier=None):
if isinstance(widget, QtGui.QGraphicsView):
widget = widget.viewport()
if modifier is None:
modifier = QtCore.Qt.NoModifier
if QT_LIB != 'PyQt5' and isinstance(pos, QtCore.QPointF):
pos = pos.toPoint()
event = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, button, QtCore.Qt.NoButton, modifier)
QtGui.QApplication.sendEvent(widget, event)
def mouseMove(widget, pos, buttons=None, modifier=None):
if isinstance(widget, QtGui.QGraphicsView):
widget = widget.viewport()
if modifier is None:
modifier = QtCore.Qt.NoModifier
if buttons is None:
buttons = QtCore.Qt.NoButton
if QT_LIB != 'PyQt5' and isinstance(pos, QtCore.QPointF):
pos = pos.toPoint()
event = QtGui.QMouseEvent(QtCore.QEvent.MouseMove, pos, QtCore.Qt.NoButton, buttons, modifier)
QtGui.QApplication.sendEvent(widget, event)
def mouseDrag(widget, pos1, pos2, button, modifier=None):
mouseMove(widget, pos1)
mousePress(widget, pos1, button, modifier)
mouseMove(widget, pos2, button, modifier)
mouseRelease(widget, pos2, button, modifier)
def mouseClick(widget, pos, button, modifier=None):
mouseMove(widget, pos)
mousePress(widget, pos, button, modifier)
mouseRelease(widget, pos, button, modifier)
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/tests/test_functions.py | .py | 14,754 | 416 | # -*- coding: utf-8 -*-
import pyqtgraph as pg
import numpy as np
import sys
from copy import deepcopy
from collections import OrderedDict
from numpy.testing import assert_array_almost_equal, assert_almost_equal
import pytest
np.random.seed(12345)
def testSolve3D():
p1 = np.array([[0,0,0,1],
[1,0,0,1],
[0,1,0,1],
[0,0,1,1]], dtype=float)
# transform points through random matrix
tr = np.random.normal(size=(4, 4))
tr[3] = (0,0,0,1)
p2 = np.dot(tr, p1.T).T[:,:3]
# solve to see if we can recover the transformation matrix.
tr2 = pg.solve3DTransform(p1, p2)
assert_array_almost_equal(tr[:3], tr2[:3])
def test_interpolateArray_order0():
check_interpolateArray(order=0)
def test_interpolateArray_order1():
check_interpolateArray(order=1)
def check_interpolateArray(order):
def interpolateArray(data, x):
result = pg.interpolateArray(data, x, order=order)
assert result.shape == x.shape[:-1] + data.shape[x.shape[-1]:]
return result
data = np.array([[ 1., 2., 4. ],
[ 10., 20., 40. ],
[ 100., 200., 400.]])
# test various x shapes
interpolateArray(data, np.ones((1,)))
interpolateArray(data, np.ones((2,)))
interpolateArray(data, np.ones((1, 1)))
interpolateArray(data, np.ones((1, 2)))
interpolateArray(data, np.ones((5, 1)))
interpolateArray(data, np.ones((5, 2)))
interpolateArray(data, np.ones((5, 5, 1)))
interpolateArray(data, np.ones((5, 5, 2)))
with pytest.raises(TypeError):
interpolateArray(data, np.ones((3,)))
with pytest.raises(TypeError):
interpolateArray(data, np.ones((1, 3,)))
with pytest.raises(TypeError):
interpolateArray(data, np.ones((5, 5, 3,)))
x = np.array([[ 0.3, 0.6],
[ 1. , 1. ],
[ 0.501, 1. ], # NOTE: testing at exactly 0.5 can yield different results from map_coordinates
[ 0.501, 2.501], # due to differences in rounding
[ 10. , 10. ]])
result = interpolateArray(data, x)
# make sure results match ndimage.map_coordinates
import scipy.ndimage
spresult = scipy.ndimage.map_coordinates(data, x.T, order=order)
#spresult = np.array([ 5.92, 20. , 11. , 0. , 0. ]) # generated with the above line
assert_array_almost_equal(result, spresult)
# test mapping when x.shape[-1] < data.ndim
x = np.array([[ 0.3, 0],
[ 0.3, 1],
[ 0.3, 2]])
r1 = interpolateArray(data, x)
x = np.array([0.3]) # should broadcast across axis 1
r2 = interpolateArray(data, x)
assert_array_almost_equal(r1, r2)
# test mapping 2D array of locations
x = np.array([[[0.501, 0.501], [0.501, 1.0], [0.501, 1.501]],
[[1.501, 0.501], [1.501, 1.0], [1.501, 1.501]]])
r1 = interpolateArray(data, x)
r2 = scipy.ndimage.map_coordinates(data, x.transpose(2,0,1), order=order)
#r2 = np.array([[ 8.25, 11. , 16.5 ], # generated with the above line
#[ 82.5 , 110. , 165. ]])
assert_array_almost_equal(r1, r2)
def test_subArray():
a = np.array([0, 0, 111, 112, 113, 0, 121, 122, 123, 0, 0, 0, 211, 212, 213, 0, 221, 222, 223, 0, 0, 0, 0])
b = pg.subArray(a, offset=2, shape=(2,2,3), stride=(10,4,1))
c = np.array([[[111,112,113], [121,122,123]], [[211,212,213], [221,222,223]]])
assert np.all(b == c)
# operate over first axis; broadcast over the rest
aa = np.vstack([a, a/100.]).T
cc = np.empty(c.shape + (2,))
cc[..., 0] = c
cc[..., 1] = c / 100.
bb = pg.subArray(aa, offset=2, shape=(2,2,3), stride=(10,4,1))
assert np.all(bb == cc)
def test_rescaleData():
dtypes = map(np.dtype, ('ubyte', 'uint16', 'byte', 'int16', 'int', 'float'))
for dtype1 in dtypes:
for dtype2 in dtypes:
data = (np.random.random(size=10) * 2**32 - 2**31).astype(dtype1)
for scale, offset in [(10, 0), (10., 0.), (1, -50), (0.2, 0.5), (0.001, 0)]:
if dtype2.kind in 'iu':
lim = np.iinfo(dtype2)
lim = lim.min, lim.max
else:
lim = (-np.inf, np.inf)
s1 = np.clip(float(scale) * (data-float(offset)), *lim).astype(dtype2)
s2 = pg.rescaleData(data, scale, offset, dtype2)
assert s1.dtype == s2.dtype
if dtype2.kind in 'iu':
assert np.all(s1 == s2)
else:
assert np.allclose(s1, s2)
def test_makeARGB():
# Many parameters to test here:
# * data dtype (ubyte, uint16, float, others)
# * data ndim (2 or 3)
# * levels (None, 1D, or 2D)
# * lut dtype
# * lut size
# * lut ndim (1 or 2)
# * useRGBA argument
# Need to check that all input values map to the correct output values, especially
# at and beyond the edges of the level range.
def checkArrays(a, b):
# because py.test output is difficult to read for arrays
if not np.all(a == b):
comp = []
for i in range(a.shape[0]):
if a.shape[1] > 1:
comp.append('[')
for j in range(a.shape[1]):
m = a[i,j] == b[i,j]
comp.append('%d,%d %s %s %s%s' %
(i, j, str(a[i,j]).ljust(15), str(b[i,j]).ljust(15),
m, ' ********' if not np.all(m) else ''))
if a.shape[1] > 1:
comp.append(']')
raise Exception("arrays do not match:\n%s" % '\n'.join(comp))
def checkImage(img, check, alpha, alphaCheck):
assert img.dtype == np.ubyte
assert alpha is alphaCheck
if alpha is False:
checkArrays(img[..., 3], 255)
if np.isscalar(check) or check.ndim == 3:
checkArrays(img[..., :3], check)
elif check.ndim == 2:
checkArrays(img[..., :3], check[..., np.newaxis])
elif check.ndim == 1:
checkArrays(img[..., :3], check[..., np.newaxis, np.newaxis])
else:
raise Exception('invalid check array ndim')
# uint8 data tests
im1 = np.arange(256).astype('ubyte').reshape(256, 1)
im2, alpha = pg.makeARGB(im1, levels=(0, 255))
checkImage(im2, im1, alpha, False)
im3, alpha = pg.makeARGB(im1, levels=(0.0, 255.0))
checkImage(im3, im1, alpha, False)
im4, alpha = pg.makeARGB(im1, levels=(255, 0))
checkImage(im4, 255-im1, alpha, False)
im5, alpha = pg.makeARGB(np.concatenate([im1]*3, axis=1), levels=[(0, 255), (0.0, 255.0), (255, 0)])
checkImage(im5, np.concatenate([im1, im1, 255-im1], axis=1), alpha, False)
im2, alpha = pg.makeARGB(im1, levels=(128,383))
checkImage(im2[:128], 0, alpha, False)
checkImage(im2[128:], im1[:128], alpha, False)
# uint8 data + uint8 LUT
lut = np.arange(256)[::-1].astype(np.uint8)
im2, alpha = pg.makeARGB(im1, lut=lut)
checkImage(im2, lut, alpha, False)
# lut larger than maxint
lut = np.arange(511).astype(np.uint8)
im2, alpha = pg.makeARGB(im1, lut=lut)
checkImage(im2, lut[::2], alpha, False)
# lut smaller than maxint
lut = np.arange(128).astype(np.uint8)
im2, alpha = pg.makeARGB(im1, lut=lut)
checkImage(im2, np.linspace(0, 127.5, 256, dtype='ubyte'), alpha, False)
# lut + levels
lut = np.arange(256)[::-1].astype(np.uint8)
im2, alpha = pg.makeARGB(im1, lut=lut, levels=[-128, 384])
checkImage(im2, np.linspace(191.5, 64.5, 256, dtype='ubyte'), alpha, False)
im2, alpha = pg.makeARGB(im1, lut=lut, levels=[64, 192])
checkImage(im2, np.clip(np.linspace(384.5, -127.5, 256), 0, 255).astype('ubyte'), alpha, False)
# uint8 data + uint16 LUT
lut = np.arange(4096)[::-1].astype(np.uint16) // 16
im2, alpha = pg.makeARGB(im1, lut=lut)
checkImage(im2, np.arange(256)[::-1].astype('ubyte'), alpha, False)
# uint8 data + float LUT
lut = np.linspace(10., 137., 256)
im2, alpha = pg.makeARGB(im1, lut=lut)
checkImage(im2, lut.astype('ubyte'), alpha, False)
# uint8 data + 2D LUT
lut = np.zeros((256, 3), dtype='ubyte')
lut[:,0] = np.arange(256)
lut[:,1] = np.arange(256)[::-1]
lut[:,2] = 7
im2, alpha = pg.makeARGB(im1, lut=lut)
checkImage(im2, lut[:,None,::-1], alpha, False)
# check useRGBA
im2, alpha = pg.makeARGB(im1, lut=lut, useRGBA=True)
checkImage(im2, lut[:,None,:], alpha, False)
# uint16 data tests
im1 = np.arange(0, 2**16, 256).astype('uint16')[:, None]
im2, alpha = pg.makeARGB(im1, levels=(512, 2**16))
checkImage(im2, np.clip(np.linspace(-2, 253, 256), 0, 255).astype('ubyte'), alpha, False)
lut = (np.arange(512, 2**16)[::-1] // 256).astype('ubyte')
im2, alpha = pg.makeARGB(im1, lut=lut, levels=(512, 2**16-256))
checkImage(im2, np.clip(np.linspace(257, 2, 256), 0, 255).astype('ubyte'), alpha, False)
lut = np.zeros(2**16, dtype='ubyte')
lut[1000:1256] = np.arange(256)
lut[1256:] = 255
im1 = np.arange(1000, 1256).astype('uint16')[:, None]
im2, alpha = pg.makeARGB(im1, lut=lut)
checkImage(im2, np.arange(256).astype('ubyte'), alpha, False)
# float data tests
im1 = np.linspace(1.0, 17.0, 256)[:, None]
im2, alpha = pg.makeARGB(im1, levels=(5.0, 13.0))
checkImage(im2, np.clip(np.linspace(-128, 383, 256), 0, 255).astype('ubyte'), alpha, False)
lut = (np.arange(1280)[::-1] // 10).astype('ubyte')
im2, alpha = pg.makeARGB(im1, lut=lut, levels=(1, 17))
checkImage(im2, np.linspace(127.5, 0, 256).astype('ubyte'), alpha, False)
# nans in image
# 2d input image, one pixel is nan
im1 = np.ones((10, 12))
im1[3, 5] = np.nan
im2, alpha = pg.makeARGB(im1, levels=(0, 1))
assert alpha
assert im2[3, 5, 3] == 0 # nan pixel is transparent
assert im2[0, 0, 3] == 255 # doesn't affect other pixels
# 3d RGB input image, any color channel of a pixel is nan
im1 = np.ones((10, 12, 3))
im1[3, 5, 1] = np.nan
im2, alpha = pg.makeARGB(im1, levels=(0, 1))
assert alpha
assert im2[3, 5, 3] == 0 # nan pixel is transparent
assert im2[0, 0, 3] == 255 # doesn't affect other pixels
# 3d RGBA input image, any color channel of a pixel is nan
im1 = np.ones((10, 12, 4))
im1[3, 5, 1] = np.nan
im2, alpha = pg.makeARGB(im1, levels=(0, 1), useRGBA=True)
assert alpha
assert im2[3, 5, 3] == 0 # nan pixel is transparent
# test sanity checks
class AssertExc(object):
def __init__(self, exc=Exception):
self.exc = exc
def __enter__(self):
return self
def __exit__(self, *args):
assert args[0] is self.exc, "Should have raised %s (got %s)" % (self.exc, args[0])
return True
with AssertExc(TypeError): # invalid image shape
pg.makeARGB(np.zeros((2,), dtype='float'))
with AssertExc(TypeError): # invalid image shape
pg.makeARGB(np.zeros((2,2,7), dtype='float'))
with AssertExc(): # float images require levels arg
pg.makeARGB(np.zeros((2,2), dtype='float'))
with AssertExc(): # bad levels arg
pg.makeARGB(np.zeros((2,2), dtype='float'), levels=[1])
with AssertExc(): # bad levels arg
pg.makeARGB(np.zeros((2,2), dtype='float'), levels=[1,2,3])
with AssertExc(): # can't mix 3-channel levels and LUT
pg.makeARGB(np.zeros((2,2)), lut=np.zeros((10,3), dtype='ubyte'), levels=[(0,1)]*3)
with AssertExc(): # multichannel levels must have same number of channels as image
pg.makeARGB(np.zeros((2,2,3), dtype='float'), levels=[(1,2)]*4)
with AssertExc(): # 3d levels not allowed
pg.makeARGB(np.zeros((2,2,3), dtype='float'), levels=np.zeros([3, 2, 2]))
def test_eq():
eq = pg.functions.eq
zeros = [0, 0.0, np.float(0), np.int(0)]
if sys.version[0] < '3':
zeros.append(long(0))
for i,x in enumerate(zeros):
for y in zeros[i:]:
assert eq(x, y)
assert eq(y, x)
assert eq(np.nan, np.nan)
# test
class NotEq(object):
def __eq__(self, x):
return False
noteq = NotEq()
assert eq(noteq, noteq) # passes because they are the same object
assert not eq(noteq, NotEq())
# Should be able to test for equivalence even if the test raises certain
# exceptions
class NoEq(object):
def __init__(self, err):
self.err = err
def __eq__(self, x):
raise self.err
noeq1 = NoEq(AttributeError())
noeq2 = NoEq(ValueError())
noeq3 = NoEq(Exception())
assert eq(noeq1, noeq1)
assert not eq(noeq1, noeq2)
assert not eq(noeq2, noeq1)
with pytest.raises(Exception):
eq(noeq3, noeq2)
# test array equivalence
# note that numpy has a weird behavior here--np.all() always returns True
# if one of the arrays has size=0; eq() will only return True if both arrays
# have the same shape.
a1 = np.zeros((10, 20)).astype('float')
a2 = a1 + 1
a3 = a2.astype('int')
a4 = np.empty((0, 20))
assert not eq(a1, a2) # same shape/dtype, different values
assert not eq(a1, a3) # same shape, different dtype and values
assert not eq(a1, a4) # different shape (note: np.all gives True if one array has size 0)
assert not eq(a2, a3) # same values, but different dtype
assert not eq(a2, a4) # different shape
assert not eq(a3, a4) # different shape and dtype
assert eq(a4, a4.copy())
assert not eq(a4, a4.T)
# test containers
assert not eq({'a': 1}, {'a': 1, 'b': 2})
assert not eq({'a': 1}, {'a': 2})
d1 = {'x': 1, 'y': np.nan, 3: ['a', np.nan, a3, 7, 2.3], 4: a4}
d2 = deepcopy(d1)
assert eq(d1, d2)
d1_ordered = OrderedDict(d1)
d2_ordered = deepcopy(d1_ordered)
assert eq(d1_ordered, d2_ordered)
assert not eq(d1_ordered, d2)
items = list(d1.items())
assert not eq(OrderedDict(items), OrderedDict(reversed(items)))
assert not eq([1,2,3], [1,2,3,4])
l1 = [d1, np.inf, -np.inf, np.nan]
l2 = deepcopy(l1)
t1 = tuple(l1)
t2 = tuple(l2)
assert eq(l1, l2)
assert eq(t1, t2)
assert eq(set(range(10)), set(range(10)))
assert not eq(set(range(10)), set(range(9)))
if __name__ == '__main__':
test_interpolateArray()
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/tests/test_stability.py | .py | 3,567 | 161 | """
PyQt/PySide stress test:
Create lots of random widgets and graphics items, connect them together randomly,
the tear them down repeatedly.
The purpose of this is to attempt to generate segmentation faults.
"""
from pyqtgraph.Qt import QtTest
import pyqtgraph as pg
from random import seed, randint
import sys, gc, weakref
app = pg.mkQApp()
seed(12345)
widgetTypes = [
pg.PlotWidget,
pg.ImageView,
pg.GraphicsView,
pg.QtGui.QWidget,
pg.QtGui.QTreeWidget,
pg.QtGui.QPushButton,
]
itemTypes = [
pg.PlotCurveItem,
pg.ImageItem,
pg.PlotDataItem,
pg.ViewBox,
pg.QtGui.QGraphicsRectItem
]
widgets = []
items = []
allWidgets = weakref.WeakKeyDictionary()
def crashtest():
global allWidgets
try:
gc.disable()
actions = [
createWidget,
#setParent,
forgetWidget,
showWidget,
processEvents,
#raiseException,
#addReference,
]
thread = WorkThread()
thread.start()
while True:
try:
action = randItem(actions)
action()
print('[%d widgets alive, %d zombie]' % (len(allWidgets), len(allWidgets) - len(widgets)))
except KeyboardInterrupt:
print("Caught interrupt; send another to exit.")
try:
for i in range(100):
QtTest.QTest.qWait(100)
except KeyboardInterrupt:
thread.terminate()
break
except:
sys.excepthook(*sys.exc_info())
finally:
gc.enable()
class WorkThread(pg.QtCore.QThread):
'''Intended to give the gc an opportunity to run from a non-gui thread.'''
def run(self):
i = 0
while True:
i += 1
if (i % 1000000) == 0:
print('--worker--')
def randItem(items):
return items[randint(0, len(items)-1)]
def p(msg):
print(msg)
sys.stdout.flush()
def createWidget():
p('create widget')
global widgets, allWidgets
if len(widgets) > 50:
return
widget = randItem(widgetTypes)()
widget.setWindowTitle(widget.__class__.__name__)
widgets.append(widget)
allWidgets[widget] = 1
p(" %s" % widget)
return widget
def setParent():
p('set parent')
global widgets
if len(widgets) < 2:
return
child = parent = None
while child is parent:
child = randItem(widgets)
parent = randItem(widgets)
p(" %s parent of %s" % (parent, child))
child.setParent(parent)
def forgetWidget():
p('forget widget')
global widgets
if len(widgets) < 1:
return
widget = randItem(widgets)
p(' %s' % widget)
widgets.remove(widget)
def showWidget():
p('show widget')
global widgets
if len(widgets) < 1:
return
widget = randItem(widgets)
p(' %s' % widget)
widget.show()
def processEvents():
p('process events')
QtTest.QTest.qWait(25)
class TstException(Exception):
pass
def raiseException():
p('raise exception')
raise TstException("A test exception")
def addReference():
p('add reference')
global widgets
if len(widgets) < 1:
return
obj1 = randItem(widgets)
obj2 = randItem(widgets)
p(' %s -> %s' % (obj1, obj2))
obj1._testref = obj2
if __name__ == '__main__':
test_stability()
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/tests/__init__.py | .py | 165 | 3 | from .image_testing import assertImageApproved, TransposedImageItem
from .ui_testing import resizeWindow, mousePress, mouseMove, mouseRelease, mouseDrag, mouseClick
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/tests/image_testing.py | .py | 23,728 | 653 | # Image-based testing borrowed from vispy
"""
Procedure for unit-testing with images:
1. Run unit tests at least once; this initializes a git clone of
pyqtgraph/test-data in ~/.pyqtgraph.
2. Run individual test scripts with the PYQTGRAPH_AUDIT environment variable set:
$ PYQTGRAPH_AUDIT=1 python pyqtgraph/graphicsItems/tests/test_PlotCurveItem.py
Any failing tests will display the test results, standard image, and the
differences between the two. If the test result is bad, then press (f)ail.
If the test result is good, then press (p)ass and the new image will be
saved to the test-data directory.
To check all test results regardless of whether the test failed, set the
environment variable PYQTGRAPH_AUDIT_ALL=1.
3. After adding or changing test images, create a new commit:
$ cd ~/.pyqtgraph/test-data
$ git add ...
$ git commit -a
4. Look up the most recent tag name from the `testDataTag` global variable
below. Increment the tag name by 1 and create a new tag in the test-data
repository:
$ git tag test-data-NNN
$ git push --tags origin master
This tag is used to ensure that each pyqtgraph commit is linked to a specific
commit in the test-data repository. This makes it possible to push new
commits to the test-data repository without interfering with existing
tests, and also allows unit tests to continue working on older pyqtgraph
versions.
"""
# This is the name of a tag in the test-data repository that this version of
# pyqtgraph should be tested against. When adding or changing test images,
# create and push a new tag and update this variable. To test locally, begin
# by creating the tag in your ~/.pyqtgraph/test-data repository.
testDataTag = 'test-data-7'
import time
import os
import sys
import inspect
import base64
import subprocess as sp
import numpy as np
if sys.version[0] >= '3':
import http.client as httplib
import urllib.parse as urllib
else:
import httplib
import urllib
from ..Qt import QtGui, QtCore, QtTest, QT_LIB
from .. import functions as fn
from .. import GraphicsLayoutWidget
from .. import ImageItem, TextItem
tester = None
# Convenient stamp used for ensuring image orientation is correct
axisImg = [
" 1 1 1 ",
" 1 1 1 1 1 1 ",
" 1 1 1 1 1 1 1 1 1 1",
" 1 1 1 1 1 ",
" 1 1 1 1 1 1 ",
" 1 1 ",
" 1 1 ",
" 1 ",
" ",
" 1 ",
" 1 ",
" 1 ",
"1 1 1 1 1 ",
"1 1 1 1 1 ",
" 1 1 1 ",
" 1 1 1 ",
" 1 ",
" 1 ",
]
axisImg = np.array([map(int, row[::2].replace(' ', '0')) for row in axisImg])
def getTester():
global tester
if tester is None:
tester = ImageTester()
return tester
def assertImageApproved(image, standardFile, message=None, **kwargs):
"""Check that an image test result matches a pre-approved standard.
If the result does not match, then the user can optionally invoke a GUI
to compare the images and decide whether to fail the test or save the new
image as the standard.
This function will automatically clone the test-data repository into
~/.pyqtgraph/test-data. However, it is up to the user to ensure this repository
is kept up to date and to commit/push new images after they are saved.
Run the test with the environment variable PYQTGRAPH_AUDIT=1 to bring up
the auditing GUI.
Parameters
----------
image : (h, w, 4) ndarray
standardFile : str
The name of the approved test image to check against. This file name
is relative to the root of the pyqtgraph test-data repository and will
be automatically fetched.
message : str
A string description of the image. It is recommended to describe
specific features that an auditor should look for when deciding whether
to fail a test.
Extra keyword arguments are used to set the thresholds for automatic image
comparison (see ``assertImageMatch()``).
"""
if isinstance(image, QtGui.QWidget):
w = image
# just to be sure the widget size is correct (new window may be resized):
QtGui.QApplication.processEvents()
graphstate = scenegraphState(w, standardFile)
image = np.zeros((w.height(), w.width(), 4), dtype=np.ubyte)
qimg = fn.makeQImage(image, alpha=True, copy=False, transpose=False)
painter = QtGui.QPainter(qimg)
w.render(painter)
painter.end()
# transpose BGRA to RGBA
image = image[..., [2, 1, 0, 3]]
if message is None:
code = inspect.currentframe().f_back.f_code
message = "%s::%s" % (code.co_filename, code.co_name)
# Make sure we have a test data repo available, possibly invoking git
dataPath = getTestDataRepo()
# Read the standard image if it exists
stdFileName = os.path.join(dataPath, standardFile + '.png')
if not os.path.isfile(stdFileName):
stdImage = None
else:
pxm = QtGui.QPixmap()
pxm.load(stdFileName)
stdImage = fn.imageToArray(pxm.toImage(), copy=True, transpose=False)
# If the test image does not match, then we go to audit if requested.
try:
if stdImage is None:
raise Exception("No reference image saved for this test.")
if image.shape[2] != stdImage.shape[2]:
raise Exception("Test result has different channel count than standard image"
"(%d vs %d)" % (image.shape[2], stdImage.shape[2]))
if image.shape != stdImage.shape:
# Allow im1 to be an integer multiple larger than im2 to account
# for high-resolution displays
ims1 = np.array(image.shape).astype(float)
ims2 = np.array(stdImage.shape).astype(float)
sr = ims1 / ims2 if ims1[0] > ims2[0] else ims2 / ims1
if (sr[0] != sr[1] or not np.allclose(sr, np.round(sr)) or
sr[0] < 1):
raise TypeError("Test result shape %s is not an integer factor"
" different than standard image shape %s." %
(ims1, ims2))
sr = np.round(sr).astype(int)
image = fn.downsample(image, sr[0], axis=(0, 1)).astype(image.dtype)
assertImageMatch(image, stdImage, **kwargs)
if bool(os.getenv('PYQTGRAPH_PRINT_TEST_STATE', False)):
print(graphstate)
if os.getenv('PYQTGRAPH_AUDIT_ALL') == '1':
raise Exception("Image test passed, but auditing due to PYQTGRAPH_AUDIT_ALL evnironment variable.")
except Exception:
if stdFileName in gitStatus(dataPath):
print("\n\nWARNING: unit test failed against modified standard "
"image %s.\nTo revert this file, run `cd %s; git checkout "
"%s`\n" % (stdFileName, dataPath, standardFile))
if os.getenv('PYQTGRAPH_AUDIT') == '1' or os.getenv('PYQTGRAPH_AUDIT_ALL') == '1':
sys.excepthook(*sys.exc_info())
getTester().test(image, stdImage, message)
stdPath = os.path.dirname(stdFileName)
print('Saving new standard image to "%s"' % stdFileName)
if not os.path.isdir(stdPath):
os.makedirs(stdPath)
img = fn.makeQImage(image, alpha=True, transpose=False)
img.save(stdFileName)
else:
if stdImage is None:
raise Exception("Test standard %s does not exist. Set "
"PYQTGRAPH_AUDIT=1 to add this image." % stdFileName)
else:
if os.getenv('TRAVIS') is not None:
saveFailedTest(image, stdImage, standardFile, upload=True)
elif os.getenv('AZURE') is not None:
standardFile = os.path.join(os.getenv("SCREENSHOT_DIR", "screenshots"), standardFile)
saveFailedTest(image, stdImage, standardFile)
print(graphstate)
raise
def assertImageMatch(im1, im2, minCorr=None, pxThreshold=50.,
pxCount=-1, maxPxDiff=None, avgPxDiff=None,
imgDiff=None):
"""Check that two images match.
Images that differ in shape or dtype will fail unconditionally.
Further tests for similarity depend on the arguments supplied.
By default, images may have no pixels that gave a value difference greater
than 50.
Parameters
----------
im1 : (h, w, 4) ndarray
Test output image
im2 : (h, w, 4) ndarray
Test standard image
minCorr : float or None
Minimum allowed correlation coefficient between corresponding image
values (see numpy.corrcoef)
pxThreshold : float
Minimum value difference at which two pixels are considered different
pxCount : int or None
Maximum number of pixels that may differ. Default is 0 for Qt4 and
1% of image size for Qt5.
maxPxDiff : float or None
Maximum allowed difference between pixels
avgPxDiff : float or None
Average allowed difference between pixels
imgDiff : float or None
Maximum allowed summed difference between images
"""
assert im1.ndim == 3
assert im1.shape[2] == 4
assert im1.dtype == im2.dtype
if pxCount == -1:
if QT_LIB in {'PyQt5', 'PySide2'}:
# Qt5 generates slightly different results; relax the tolerance
# until test images are updated.
pxCount = int(im1.shape[0] * im1.shape[1] * 0.01)
else:
pxCount = 0
diff = im1.astype(float) - im2.astype(float)
if imgDiff is not None:
assert np.abs(diff).sum() <= imgDiff
pxdiff = diff.max(axis=2) # largest value difference per pixel
mask = np.abs(pxdiff) >= pxThreshold
if pxCount is not None:
assert mask.sum() <= pxCount
maskedDiff = diff[mask]
if maxPxDiff is not None and maskedDiff.size > 0:
assert maskedDiff.max() <= maxPxDiff
if avgPxDiff is not None and maskedDiff.size > 0:
assert maskedDiff.mean() <= avgPxDiff
if minCorr is not None:
with np.errstate(invalid='ignore'):
corr = np.corrcoef(im1.ravel(), im2.ravel())[0, 1]
assert corr >= minCorr
def saveFailedTest(data, expect, filename, upload=False):
"""Upload failed test images to web server to allow CI test debugging.
"""
# concatenate data, expect, and diff into a single image
ds = data.shape
es = expect.shape
shape = (max(ds[0], es[0]) + 4, ds[1] + es[1] + 8 + max(ds[1], es[1]), 4)
img = np.empty(shape, dtype=np.ubyte)
img[..., :3] = 100
img[..., 3] = 255
img[2:2+ds[0], 2:2+ds[1], :ds[2]] = data
img[2:2+es[0], ds[1]+4:ds[1]+4+es[1], :es[2]] = expect
diff = makeDiffImage(data, expect)
img[2:2+diff.shape[0], -diff.shape[1]-2:-2] = diff
png = makePng(img)
directory = os.path.dirname(filename)
if not os.path.isdir(directory):
os.makedirs(directory)
with open(filename + ".png", "wb") as png_file:
png_file.write(png)
print("\nImage comparison failed. Test result: %s %s Expected result: "
"%s %s" % (data.shape, data.dtype, expect.shape, expect.dtype))
if upload:
uploadFailedTest(filename, png)
def uploadFailedTest(filename, png):
commit = runSubprocess(['git', 'rev-parse', 'HEAD'])
name = filename.split(os.path.sep)
name.insert(-1, commit.strip())
filename = os.path.sep.join(name)
host = 'data.pyqtgraph.org'
conn = httplib.HTTPConnection(host)
req = urllib.urlencode({'name': filename,
'data': base64.b64encode(png)})
conn.request('POST', '/upload.py', req)
response = conn.getresponse().read()
conn.close()
print("Uploaded to: \nhttp://%s/data/%s" % (host, filename))
if not response.startswith(b'OK'):
print("WARNING: Error uploading data to %s" % host)
print(response)
def makePng(img):
"""Given an array like (H, W, 4), return a PNG-encoded byte string.
"""
io = QtCore.QBuffer()
qim = fn.makeQImage(img.transpose(1, 0, 2), alpha=False)
qim.save(io, 'PNG')
png = bytes(io.data().data())
return png
def makeDiffImage(im1, im2):
"""Return image array showing the differences between im1 and im2.
Handles images of different shape. Alpha channels are not compared.
"""
ds = im1.shape
es = im2.shape
diff = np.empty((max(ds[0], es[0]), max(ds[1], es[1]), 4), dtype=int)
diff[..., :3] = 128
diff[..., 3] = 255
diff[:ds[0], :ds[1], :min(ds[2], 3)] += im1[..., :3]
diff[:es[0], :es[1], :min(es[2], 3)] -= im2[..., :3]
diff = np.clip(diff, 0, 255).astype(np.ubyte)
return diff
class ImageTester(QtGui.QWidget):
"""Graphical interface for auditing image comparison tests.
"""
def __init__(self):
self.lastKey = None
QtGui.QWidget.__init__(self)
self.resize(1200, 800)
#self.showFullScreen()
self.layout = QtGui.QGridLayout()
self.setLayout(self.layout)
self.view = GraphicsLayoutWidget()
self.layout.addWidget(self.view, 0, 0, 1, 2)
self.label = QtGui.QLabel()
self.layout.addWidget(self.label, 1, 0, 1, 2)
self.label.setWordWrap(True)
font = QtGui.QFont("monospace", 14, QtGui.QFont.Bold)
self.label.setFont(font)
self.passBtn = QtGui.QPushButton('Pass')
self.failBtn = QtGui.QPushButton('Fail')
self.layout.addWidget(self.passBtn, 2, 0)
self.layout.addWidget(self.failBtn, 2, 1)
self.passBtn.clicked.connect(self.passTest)
self.failBtn.clicked.connect(self.failTest)
self.views = (self.view.addViewBox(row=0, col=0),
self.view.addViewBox(row=0, col=1),
self.view.addViewBox(row=0, col=2))
labelText = ['test output', 'standard', 'diff']
for i, v in enumerate(self.views):
v.setAspectLocked(1)
v.invertY()
v.image = ImageItem(axisOrder='row-major')
v.image.setAutoDownsample(True)
v.addItem(v.image)
v.label = TextItem(labelText[i])
v.setBackgroundColor(0.5)
self.views[1].setXLink(self.views[0])
self.views[1].setYLink(self.views[0])
self.views[2].setXLink(self.views[0])
self.views[2].setYLink(self.views[0])
def test(self, im1, im2, message):
"""Ask the user to decide whether an image test passes or fails.
This method displays the test image, reference image, and the difference
between the two. It then blocks until the user selects the test output
by clicking a pass/fail button or typing p/f. If the user fails the test,
then an exception is raised.
"""
self.show()
if im2 is None:
message += '\nImage1: %s %s Image2: [no standard]' % (im1.shape, im1.dtype)
im2 = np.zeros((1, 1, 3), dtype=np.ubyte)
else:
message += '\nImage1: %s %s Image2: %s %s' % (im1.shape, im1.dtype, im2.shape, im2.dtype)
self.label.setText(message)
self.views[0].image.setImage(im1)
self.views[1].image.setImage(im2)
diff = makeDiffImage(im1, im2)
self.views[2].image.setImage(diff)
self.views[0].autoRange()
while True:
QtGui.QApplication.processEvents()
lastKey = self.lastKey
self.lastKey = None
if lastKey in ('f', 'esc') or not self.isVisible():
raise Exception("User rejected test result.")
elif lastKey == 'p':
break
time.sleep(0.03)
for v in self.views:
v.image.setImage(np.zeros((1, 1, 3), dtype=np.ubyte))
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Escape:
self.lastKey = 'esc'
else:
self.lastKey = str(event.text()).lower()
def passTest(self):
self.lastKey = 'p'
def failTest(self):
self.lastKey = 'f'
def getTestDataRepo():
"""Return the path to a git repository with the required commit checked
out.
If the repository does not exist, then it is cloned from
https://github.com/pyqtgraph/test-data. If the repository already exists
then the required commit is checked out.
"""
global testDataTag
dataPath = os.path.join(os.path.expanduser('~'), '.pyqtgraph', 'test-data')
gitPath = 'https://github.com/pyqtgraph/test-data'
gitbase = gitCmdBase(dataPath)
if os.path.isdir(dataPath):
# Already have a test-data repository to work with.
# Get the commit ID of testDataTag. Do a fetch if necessary.
try:
tagCommit = gitCommitId(dataPath, testDataTag)
except NameError:
cmd = gitbase + ['fetch', '--tags', 'origin']
print(' '.join(cmd))
sp.check_call(cmd)
try:
tagCommit = gitCommitId(dataPath, testDataTag)
except NameError:
raise Exception("Could not find tag '%s' in test-data repo at"
" %s" % (testDataTag, dataPath))
except Exception:
if not os.path.exists(os.path.join(dataPath, '.git')):
raise Exception("Directory '%s' does not appear to be a git "
"repository. Please remove this directory." %
dataPath)
else:
raise
# If HEAD is not the correct commit, then do a checkout
if gitCommitId(dataPath, 'HEAD') != tagCommit:
print("Checking out test-data tag '%s'" % testDataTag)
sp.check_call(gitbase + ['checkout', testDataTag])
else:
print("Attempting to create git clone of test data repo in %s.." %
dataPath)
parentPath = os.path.split(dataPath)[0]
if not os.path.isdir(parentPath):
os.makedirs(parentPath)
if os.getenv('TRAVIS') is not None or os.getenv('AZURE') is not None:
# Create a shallow clone of the test-data repository (to avoid
# downloading more data than is necessary)
os.makedirs(dataPath)
cmds = [
gitbase + ['init'],
gitbase + ['remote', 'add', 'origin', gitPath],
gitbase + ['fetch', '--tags', 'origin', testDataTag,
'--depth=1'],
gitbase + ['checkout', '-b', 'master', 'FETCH_HEAD'],
]
else:
# Create a full clone
cmds = [['git', 'clone', gitPath, dataPath]]
for cmd in cmds:
print(' '.join(cmd))
rval = sp.check_call(cmd)
if rval == 0:
continue
raise RuntimeError("Test data path '%s' does not exist and could "
"not be created with git. Please create a git "
"clone of %s at this path." %
(dataPath, gitPath))
return dataPath
def gitCmdBase(path):
return ['git', '--git-dir=%s/.git' % path, '--work-tree=%s' % path]
def gitStatus(path):
"""Return a string listing all changes to the working tree in a git
repository.
"""
cmd = gitCmdBase(path) + ['status', '--porcelain']
return runSubprocess(cmd, stderr=None, universal_newlines=True)
def gitCommitId(path, ref):
"""Return the commit id of *ref* in the git repository at *path*.
"""
cmd = gitCmdBase(path) + ['show', ref]
try:
output = runSubprocess(cmd, stderr=None, universal_newlines=True)
except sp.CalledProcessError:
print(cmd)
raise NameError("Unknown git reference '%s'" % ref)
commit = output.split('\n')[0]
assert commit[:7] == 'commit '
return commit[7:]
def runSubprocess(command, return_code=False, **kwargs):
"""Run command using subprocess.Popen
Similar to subprocess.check_output(), which is not available in 2.6.
Run command and wait for command to complete. If the return code was zero
then return, otherwise raise CalledProcessError.
By default, this will also add stdout= and stderr=subproces.PIPE
to the call to Popen to suppress printing to the terminal.
Parameters
----------
command : list of str
Command to run as subprocess (see subprocess.Popen documentation).
**kwargs : dict
Additional kwargs to pass to ``subprocess.Popen``.
Returns
-------
stdout : str
Stdout returned by the process.
"""
# code adapted with permission from mne-python
use_kwargs = dict(stderr=None, stdout=sp.PIPE)
use_kwargs.update(kwargs)
p = sp.Popen(command, **use_kwargs)
output = p.communicate()[0]
# communicate() may return bytes, str, or None depending on the kwargs
# passed to Popen(). Convert all to unicode str:
output = '' if output is None else output
output = output.decode('utf-8') if isinstance(output, bytes) else output
if p.returncode != 0:
print(output)
err_fun = sp.CalledProcessError.__init__
if 'output' in inspect.getargspec(err_fun).args:
raise sp.CalledProcessError(p.returncode, command, output)
else:
raise sp.CalledProcessError(p.returncode, command)
return output
def scenegraphState(view, name):
"""Return information about the scenegraph for debugging test failures.
"""
state = "====== Scenegraph state for %s ======\n" % name
state += "view size: %dx%d\n" % (view.width(), view.height())
state += "view transform:\n" + indent(transformStr(view.transform()), " ")
for item in view.scene().items():
if item.parentItem() is None:
state += itemState(item) + '\n'
return state
def itemState(root):
state = str(root) + '\n'
from .. import ViewBox
state += 'bounding rect: ' + str(root.boundingRect()) + '\n'
if isinstance(root, ViewBox):
state += "view range: " + str(root.viewRange()) + '\n'
state += "transform:\n" + indent(transformStr(root.transform()).strip(), " ") + '\n'
for item in root.childItems():
state += indent(itemState(item).strip(), " ") + '\n'
return state
def transformStr(t):
return ("[%0.2f %0.2f %0.2f]\n"*3) % (t.m11(), t.m12(), t.m13(), t.m21(), t.m22(), t.m23(), t.m31(), t.m32(), t.m33())
def indent(s, pfx):
return '\n'.join([pfx+line for line in s.split('\n')])
class TransposedImageItem(ImageItem):
# used for testing image axis order; we can test row-major and col-major using
# the same test images
def __init__(self, *args, **kwds):
self.__transpose = kwds.pop('transpose', False)
ImageItem.__init__(self, *args, **kwds)
def setImage(self, image=None, **kwds):
if image is not None and self.__transpose is True:
image = np.swapaxes(image, 0, 1)
return ImageItem.setImage(self, image, **kwds)
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/tests/test_qt.py | .py | 796 | 27 | # -*- coding: utf-8 -*-
import pyqtgraph as pg
import gc, os
import pytest
app = pg.mkQApp()
def test_isQObjectAlive():
o1 = pg.QtCore.QObject()
o2 = pg.QtCore.QObject()
o2.setParent(o1)
del o1
assert not pg.Qt.isQObjectAlive(o2)
@pytest.mark.skipif(pg.Qt.QT_LIB == 'PySide', reason='pysideuic does not appear to be '
'packaged with conda')
@pytest.mark.skipif(pg.Qt.QT_LIB == "PySide2" and "pg.Qt.QtVersion.startswith('5.14')", reason="new PySide2 doesn't have loadUi functionality")
def test_loadUiType():
path = os.path.dirname(__file__)
formClass, baseClass = pg.Qt.loadUiType(os.path.join(path, 'uictest.ui'))
w = baseClass()
ui = formClass()
ui.setupUi(w)
w.show()
app.processEvents()
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/tests/test_srttransform3d.py | .py | 1,339 | 40 | import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_almost_equal
testPoints = np.array([
[0, 0, 0],
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
[-1, -1, 0],
[0, -1, -1]])
def testMatrix():
"""
SRTTransform3D => Transform3D => SRTTransform3D
"""
tr = pg.SRTTransform3D()
tr.setRotate(45, (0, 0, 1))
tr.setScale(0.2, 0.4, 1)
tr.setTranslate(10, 20, 40)
assert tr.getRotation() == (45, QtGui.QVector3D(0, 0, 1))
assert tr.getScale() == QtGui.QVector3D(0.2, 0.4, 1)
assert tr.getTranslation() == QtGui.QVector3D(10, 20, 40)
tr2 = pg.Transform3D(tr)
assert np.all(tr.matrix() == tr2.matrix())
# This is the most important test:
# The transition from Transform3D to SRTTransform3D is a tricky one.
tr3 = pg.SRTTransform3D(tr2)
assert_array_almost_equal(tr.matrix(), tr3.matrix())
assert_almost_equal(tr3.getRotation()[0], tr.getRotation()[0])
assert_array_almost_equal(tr3.getRotation()[1], tr.getRotation()[1])
assert_array_almost_equal(tr3.getScale(), tr.getScale())
assert_array_almost_equal(tr3.getTranslation(), tr.getTranslation())
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_plot/pyqtgraph/tests/test_ref_cycles.py | .py | 2,433 | 87 | # -*- coding: utf-8 -*-
"""
Test for unwanted reference cycles
"""
import pyqtgraph as pg
import numpy as np
import gc, weakref
import six
import pytest
app = pg.mkQApp()
skipreason = ('This test is failing on pyside and pyside2 for an unknown reason.')
def assert_alldead(refs):
for ref in refs:
assert ref() is None
def qObjectTree(root):
"""Return root and its entire tree of qobject children"""
childs = [root]
for ch in pg.QtCore.QObject.children(root):
childs += qObjectTree(ch)
return childs
def mkrefs(*objs):
"""Return a list of weakrefs to each object in *objs.
QObject instances are expanded to include all child objects.
"""
allObjs = {}
for obj in objs:
if isinstance(obj, pg.QtCore.QObject):
obj = qObjectTree(obj)
else:
obj = [obj]
for o in obj:
allObjs[id(o)] = o
return [weakref.ref(obj) for obj in allObjs.values()]
@pytest.mark.skipif(pg.Qt.QT_LIB in {'PySide', 'PySide2'}, reason=skipreason)
def test_PlotWidget():
def mkobjs(*args, **kwds):
w = pg.PlotWidget(*args, **kwds)
data = pg.np.array([1,5,2,4,3])
c = w.plot(data, name='stuff')
w.addLegend()
# test that connections do not keep objects alive
w.plotItem.vb.sigRangeChanged.connect(mkrefs)
app.focusChanged.connect(w.plotItem.vb.invertY)
# return weakrefs to a bunch of objects that should die when the scope exits.
return mkrefs(w, c, data, w.plotItem, w.plotItem.vb, w.plotItem.getMenu(), w.plotItem.getAxis('left'))
for i in range(5):
assert_alldead(mkobjs())
@pytest.mark.skipif(pg.Qt.QT_LIB in {'PySide', 'PySide2'}, reason=skipreason)
def test_ImageView():
def mkobjs():
iv = pg.ImageView()
data = np.zeros((10,10,5))
iv.setImage(data)
return mkrefs(iv, iv.imageItem, iv.view, iv.ui.histogram, data)
for i in range(5):
gc.collect()
assert_alldead(mkobjs())
@pytest.mark.skipif(pg.Qt.QT_LIB in {'PySide', 'PySide2'}, reason=skipreason)
def test_GraphicsWindow():
def mkobjs():
w = pg.GraphicsWindow()
p1 = w.addPlot()
v1 = w.addViewBox()
return mkrefs(w, p1, v1)
for i in range(5):
assert_alldead(mkobjs())
if __name__ == '__main__':
ot = test_PlotItem()
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_protocols/__init__.py | .py | 0 | 0 | null | Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_protocols/base_protocols.py | .py | 11,553 | 280 | # Copyright 2020 by Giacomo Janson. All rights reserved.
# This code is part of the PyMod package and governed by its license. Please
# see the LICENSE file that should have been included as part of this package
# or the main __init__.py file in the pymod3 folder.
"""
Module implementing a base class for "PyMod protocols". A "PyMod protocol" can be many kind of
actions performed in PyMod (for example, running a BLAST search, performing a multiple sequence
alignment or using MODELLER). Each protocol will be represented by a class derived from this base
class.
"""
import os
import sys
import math
import time # For development.
import numpy as np
# This will give a message if MODELLER is installed, but the licence key is not inserted.
try:
import modeller
except:
pass
from io import StringIO
from pymol import cmd
from pymod_lib.pymod_gui.shared_gui_components_qt import askyesno_qt
class PyMod_protocol:
"""
A base class for PyMod protocols.
"""
def __init__(self, pymod, output_directory=os.path.curdir):
# 'PyMod' class object, used to access all the information of the plugin.
self.pymod = pymod
# self.protocol_name = protocol_name
# Original stdout.
self.sys_stdout = sys.stdout
# Temporary stdout used by some protocols.
self.my_stdout = None
# Directory where the output files of the protocol will be built.
self.output_directory = output_directory
# Perform an additional initialization, which is protocol specific.
self.additional_initialization()
def additional_initialization(self):
"""
Overridden in child classes.
"""
pass
def get_pymod_elements(self, pymod_elements=None):
if pymod_elements == None:
pymod_elements = self.pymod.get_selected_sequences()
return pymod_elements
def get_seq_text(self, sequences, elements_string="sequence"):
n_seqs = len(sequences)
if n_seqs == 1:
seq_text = "1 %s" % (elements_string)
else:
seq_text = "%s %ss" % (n_seqs, elements_string)
return seq_text
def launch_from_gui(self):
"""
Override in children classes. This should contain a list fof methods
organized like this (but of course variations are possible and actually
used in PyMod):
self.check_parameters_from_gui()
self.show_options_window()
self.execute_protocol()
self.remove_temp_files()
self.import_results_in_pymod()
"""
pass
def quit_protocol(self):
"""
Quit the protocol. Each protocol may extend this method.
"""
os.chdir(self.pymod.current_project_dirpath)
###############################################################################################
# Build selection of PyMod elements for the protocols. #
###############################################################################################
def extend_selection_to_hidden_children(self):
selected_elements = self.pymod.get_selected_sequences()
extend_selection = None
# Checks if in the selection there are some cluster leads of which mothers are not selected.
if False in [e.mother.selected for e in selected_elements if self.pymod.main_window.is_lead_of_collapsed_cluster(e)]:
# Ask to include the hidden children of the collapsed clusters.
title = "Selection Message"
message = "Would you like to include in the alignment the hidden sequences of the collapsed clusters?"
extend_selection = askyesno_qt(title, message, parent=self.pymod.get_qt_parent())
else:
extend_selection = False
if not extend_selection:
return None
# Actually selects the hidden children.
for e in selected_elements:
if self.pymod.main_window.is_lead_of_collapsed_cluster(e) and not e.mother.selected:
e.mother.widget_group.select_collapsed_cluster_descendants()
def build_cluster_lists(self):
"""
This will build the self.involved_clusters_list, which will contain the elements
belonging to cluster that were either selected entirely or with at least one selected child.
"""
# A list that will contain all the clusters that have at least one selected element.
self.involved_clusters_list = []
for e in self.pymod.get_selected_elements():
if not e.mother in self.involved_clusters_list:
self.involved_clusters_list.append(e.mother)
if self.pymod.root_element in self.involved_clusters_list:
self.involved_clusters_list.remove(self.pymod.root_element)
# A list that will contain all the clusters that have all of their sequences selected.
self.selected_clusters_list = self.pymod.get_selected_clusters()
# A list that will contain all the selected sequences in the root level of PyMod.
self.selected_root_sequences_list = set([s for s in self.pymod.get_selected_sequences() if s.mother == self.pymod.root_element])
###############################################################################################
# PyMOL related methods. #
###############################################################################################
def superpose_in_pymol(self, mobile_selection, fixed_selection, save_superposed_structure=True, output_directory=None):
"""
Superpose 'mobile' to 'fixed' in PyMOL.
"""
if not output_directory:
output_directory = self.pymod.structures_dirpath
if hasattr(cmd, "super"): # 'super' is sequence-independent.
cmd.super(mobile_selection, fixed_selection)
else: # PyMOL 0.99 does not have 'cmd.super'.
cmd.align(mobile_selection, fixed_selection)
if save_superposed_structure:
cmd.save(os.path.join(output_directory, mobile_selection+".pdb"), mobile_selection)
def get_coords_array(self, pymod_element, interaction_center, get_selectors=True):
"""
Takes a 'pymod_element' as input and returns a list of its PyMod residues and the corresponding
atomic coordinates of the interaction center (specified 'interaction_center') and selectors.
Only residues for which atomic coordinates are defined in PyMOL are retrieved.
"""
objsel = pymod_element.get_pymol_selector()
residues = pymod_element.get_polymer_residues()
if interaction_center == "ca":
atm_types = ("CA", )
elif interaction_center == "cb":
atm_types = ("CB", "CA", )
else:
raise KeyError("Invalid 'interaction_center': %s" % interaction_center)
# Gets the coordinates from PyMOL.
from pymol import stored
# Builds a dictionary in which the keys are tuples with (residue_id, atom_name) and the values
# are coordinates.
stored.pymod_element_coords = {}
# The 'cmd.iterate_state' function is particularly fast in PyMOL, much faster than iterating to
# every residue and calling 'cmd.get_coords' for them.
cmd.iterate_state(1, objsel, "stored.pymod_element_coords[(int(resv), name)] = [x, y, z]")
# Store the coordinates of residues having an interaction center atom (CA or CB).
coords = [] # Coordinates list.
_residues = [] # New residues list, which will substitute the 'residues' one.
selectors = []
for res in residues:
# Attempts to get various atoms.
for atm_type in atm_types:
if (res.db_index, atm_type) in stored.pymod_element_coords:
coords_i = stored.pymod_element_coords[(res.db_index, atm_type)]
coords.append(coords_i)
_residues.append(res)
if get_selectors:
sel = "object %s and n. %s and i. %s" % (objsel, atm_type, res.db_index)
selectors.append(sel)
break
coords = np.array(coords)
if get_selectors:
return _residues, coords, selectors
else:
return _residues, coords
def get_rmsd(self, element_1, element_2, coords_dict_1=None, coords_dict_2=None,
threshold_dist=100.0):
"""
Takes two 'PyMod_elements' objects and computes a RMSD deviation between their structures
loaded in PyMOL. The RMSD is computed between a list of residues pairs defined by the
alignment currently existing in PyMod between the two sequences. Remove aligned pairs with
a distance above 'threshold_dist'.
"""
t1 = time.time()
# Get the list of the ids of the aligned residues for both sequences.
ali_id = 0
coords_1 = []
coords_2 = []
for id_1, id_2 in zip(element_1.my_sequence, element_2.my_sequence):
if id_1 != "-" and id_2 != "-":
db_index_1 = element_1.get_residue_by_index(ali_id, aligned_sequence_index=True).db_index
db_index_2 = element_2.get_residue_by_index(ali_id, aligned_sequence_index=True).db_index
# Get their coordinates from the coordinate dictionaries and stores them in form of matrices.
if db_index_1 in coords_dict_1 and db_index_2 in coords_dict_2:
coords_1.append(coords_dict_1[db_index_1])
coords_2.append(coords_dict_2[db_index_2])
ali_id += 1
coords_1 = np.array(coords_1)
coords_2 = np.array(coords_2)
# Perform substraction between the two matrices.
coords_diff = coords_2 - coords_1
# Take the square of every element in the matrix and sum along rows.
square_dist_list = (coords_diff**2).sum(axis=1)
# Filters the distances > 'threshold_dist' Angstrom.
square_dist_list = square_dist_list[square_dist_list < threshold_dist**2]
# Computes the RMSD.
square_dist_sum = square_dist_list.sum()
n_aligned = float(square_dist_list.shape[0])
if n_aligned == 0:
rmsd = None
else:
if square_dist_sum == 0:
rmsd = 0.0
else:
rmsd = math.sqrt(square_dist_sum/n_aligned)
return rmsd
###################################################################################################
# MODELLER protocol. #
###################################################################################################
class MODELLER_common:
"""
A base class for running MODELLER based scripts. To be used as a parent class along
'PyMod_protocol' class.
"""
def __init__(self):
self.run_modeller_internally = self.pymod.modeller.run_internally()
def _initialize_env(self, use_hetatm=True, use_water=True):
env = modeller.environ()
env.io.atom_files_directory = []
env.io.atom_files_directory.append(".")
env.io.hetatm = use_hetatm
env.io.water = use_water
env.libs.topology.read(file='$(LIB)/top_heav.lib')
env.libs.parameters.read(file='$(LIB)/par.lib')
return env
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_protocols/modeling_protocols/loop_refinement.py | .py | 23,179 | 560 | # Copyright 2020 by Giacomo Janson. All rights reserved.
# This code is part of the PyMod package and governed by its license. Please
# see the LICENSE file that should have been included as part of this package
# or the main __init__.py file in the pymod3 folder.
"""
Module implementing a loop modeling protocol using MODELLER in PyMod.
"""
import os
import shutil
import pymod_lib.pymod_structure as pmstr
from .homology_modeling import MODELLER_homology_modeling, Modeling_cluster
###################################################################################################
# Classes for the loop modeling protocol. #
###################################################################################################
###############################################################################
# Main class. #
###############################################################################
class MODELLER_loop_refinement(MODELLER_homology_modeling):
"""
Class for performing loop refinement of a protein PDB structure.
Implements the following protocol: https://salilab.org/modeller/manual/node36.html.
"""
protocol_name = "modeller_loop_refinement"
def modeling_protocol_initialization(self):
self.modeling_mode = "loop_refinement"
self.modeling_window_class_qt = Loop_refinement_window_qt
def initialize_modeling_protocol_from_gui(self):
#---------------------------------------------------------------------
# Get the selected sequences to see if there is a correct selection. -
#---------------------------------------------------------------------
selected_sequences = self.pymod.get_selected_sequences()
# First check if at least one sequence is selected.
if not len(selected_sequences) > 0:
self.pymod.main_window.show_error_message("Selection Error", "Please select at least one target sequence to use MODELLER.")
return None
# Checks if all the selected sequences can be used to build a model.
if False in [s.has_structure() for s in selected_sequences]:
self.pymod.main_window.show_error_message("Selection Error", "Please select only sequences that have a structure loaded in PyMOL.")
return None
# Checks that no nucleic acids have been selected.
if True in [e.polymer_type == "nucleic_acid" for e in selected_sequences]:
self.pymod.main_window.show_error_message("Selection Error", "Can not perform loop refinement with structures with nucleic acids.")
return None
# Checks that all target chains come from the same PDB file.
original_pdbs_set = set([t.get_structure_file(full_file=True) for t in selected_sequences])
if len(original_pdbs_set) > 1:
self.pymod.main_window.show_error_message("Selection Error", "In order to perform multiple chain loop modeling, please select only chains coming from the same original PDB file.")
return None
# This will contain a list of 'Modeling_cluster' objects.
self.loop_modeling_targets = selected_sequences
self.modeling_clusters_list = [Loop_modeling_cluster(self, t) for t in self.loop_modeling_targets]
# Fixes the 'block_index' attribute so that each block index will correspond to the
# numeric ID of the chain in the 3D model.
for mc_idx, mc in enumerate(self.get_modeling_clusters_list(sorted_by_id=True)):
mc.block_index = mc_idx
# Define the modeling mode.
self.multiple_chain_mode = len(self.loop_modeling_targets) > 1
# Single chain homology modeling mode.
if not self.multiple_chain_mode:
self.build_modeling_window()
# Multiple chains modeling requires additional controls.
else:
# This will be used to build the symmetry restraints options for loop modeling.
self.initialize_multichain_modeling()
self.build_modeling_window()
def _get_multichain_options_from_gui(self):
self.template_complex_name = "starting_complex.pdb"
self.template_complex_modeller_name = self.template_complex_name[:-4]
def check_modeling_cluster_parameters(self, modeling_cluster):
"""
Checks the if there are any problems with the user-supplied parameters of a "modeling cluster"
before starting the modeling process.
"""
# Checks if there are some templates that have been selected.
if modeling_cluster.loops_list == []:
raise ValueError("You have to select at least one loop for target '%s' in order to perform refinement." % (modeling_cluster.target_name))
def prepare_modeling_protocol_session_files(self):
# Copies the target chains files in the modeling directory.
for mc_i, mc in enumerate(self.modeling_clusters_list):
"""
# Copy the templates structure files in the modeling directory.
tar_file = mc.target.get_structure_file(basename_only=False)
copied_tar_file = os.path.basename(tar_file)
shutil.copy(tar_file, os.path.join(self.modeling_protocol.modeling_dirpath, copied_tar_file))
mc.structure_file = copied_tar_file
"""
tar_file = mc.target.get_structure_file(basename_only=False)
copied_tar_file = os.path.basename(tar_file)
shutil.copy(tar_file, os.path.join(self.modeling_dirpath, copied_tar_file))
if not self.multiple_chain_mode and mc_i == 0:
self.loop_refinement_starting_model = copied_tar_file
# Prepares the starting complex file for multiple chain loop refinement.
if self.multiple_chain_mode:
list_of_starting_chains_files = []
for t in self.get_targets_list(sorted_by_id=True):
list_of_starting_chains_files.append(os.path.join(self.modeling_dirpath, t.get_structure_file()))
pmstr.join_pdb_files(list_of_starting_chains_files, os.path.join(self.modeling_dirpath, self.template_complex_name))
self.loop_refinement_starting_model = self.template_complex_name
###############################################################################
# Modeling clusters. #
###############################################################################
class Loop_modeling_cluster(Modeling_cluster):
"""
Class to represent a single target chain for loop modeling. It is a simpler version of the
'Modeling_cluster' class used for the homology modeling protocol.
"""
def __init__(self, modeling_protocol, target):
self.modeling_protocol = modeling_protocol
self.target = target
self.target_name = self.get_target_name()
self.model_elements_list = []
self.block_index = target.get_chain_numeric_id()
self.model_chain_id = target.get_chain_id()
self.restraints_options_dict = {}
def set_options_from_gui(self):
self.loops_list = []
# Gets a list of elements like: ('GLN 2', 'LYS 6')
# defining the starting and ending residues of loop.
_loops_list = self.user_loop_selector_frame.user_defined_loops
for l in _loops_list:
# For each loop, builds a tuple like: ("2", "6", "A")
# where the third element if the chain of the target chain.
res_1_pdb_id = l[0].split()[1]
res_2_pdb_id = l[1].split()[1]
self.loops_list.append((res_1_pdb_id, res_2_pdb_id, self.target.structure.chain_id))
def use_water_in_cluster(self):
return False
def get_symmetry_chain_id(self):
return self.target.get_chain_id()
###################################################################################################
# GUI. #
###################################################################################################
from pymol.Qt import QtWidgets, QtCore
from pymod_lib.pymod_gui.shared_gui_components_qt import small_font_style
from .homology_modeling._gui_qt import (Modeling_window_qt, Optimization_level_frame_qt, Custom_obj_func_frame_qt,
modeling_window_title_style, modeling_options_sections_style,
modeling_options_subsections_style)
################################################################################
# Main window. #
################################################################################
class Loop_refinement_window_qt(Modeling_window_qt):
"""
Loop modeling window.
"""
optimization_level_choices = ("Approximate", "Low", "Mid", "Default", "High", "Custom")
def build_modeling_protocol_main_page(self):
"""
Starts to insert content in the "Main" page.
"""
# Builds a frame for each modeling_cluster.
for (i, modeling_cluster) in enumerate(self.protocol.modeling_clusters_list):
# Add a spacer to separate the sections for each modeling cluster.
if i != 0 and self.protocol.multiple_chain_mode:
spacer_frame = QtWidgets.QFrame()
spacer_frame.setFrameShape(QtWidgets.QFrame.HLine)
spacer_frame.setFrameShadow(QtWidgets.QFrame.Sunken)
self.main_page_interior_layout.addRow(spacer_frame)
show_symmetry_restraints_option = False
# Widgets necessary to choose the templates for a single target sequence.
modeling_option_label = QtWidgets.QLabel("Modeling options for target: %s" % (modeling_cluster.target_name))
modeling_option_label.setStyleSheet(modeling_window_title_style)
self.main_page_interior_layout.addRow(modeling_option_label)
if self.protocol.multiple_chain_mode:
# Use symmetry restraints option.
if modeling_cluster.symmetry_restraints_id != None:
show_symmetry_restraints_option = True
symmetry_checkbox, symmetry_info = self.build_symmetry_restraints_option(modeling_cluster)
if any((show_symmetry_restraints_option, )): # This might include other flags in future releases.
additional_options_label = QtWidgets.QLabel("Restraints options")
additional_options_label.setStyleSheet(modeling_options_sections_style)
self.main_page_interior_layout.addRow(additional_options_label)
if show_symmetry_restraints_option:
self.main_page_interior_layout.addRow(symmetry_checkbox, symmetry_info)
# Build a series of widgets for loop ranges selection.
modeling_option_label = QtWidgets.QLabel("Loop selection")
modeling_option_label.setStyleSheet(modeling_options_sections_style)
self.main_page_interior_layout.addRow(modeling_option_label)
# Build a 'User_loop_selector_frame' object, which will contain information about
# user-defined loops for this target.
uls = User_loop_selector_frame_qt(parent=None, parent_window=self,
modeling_cluster=modeling_cluster)
modeling_cluster.user_loop_selector_frame = uls
self.main_page_interior_layout.addRow(uls)
def get_optimization_level_class(self):
return Optimization_level_frame_loop_qt
def get_custom_obj_func_frame_class(self):
return Custom_obj_func_frame_loop_qt
################################################################################
# Selectors for loop ranges. #
################################################################################
class User_loop_selector_frame_qt(QtWidgets.QFrame):
"""
Each modeling cluster will be used to build an object of this class. It will be used to let
users define loop ranges in the model chains.
"""
def __init__(self, parent, parent_window, modeling_cluster, *args, **configs):
self.parent_window = parent_window
self.protocol = self.parent_window.protocol
self.modeling_cluster = modeling_cluster
super(User_loop_selector_frame_qt, self).__init__(parent, *args, **configs)
self.initUI()
self.initialize_list()
self.loop_selector_frame_layout.setAlignment(QtCore.Qt.AlignLeft)
self.setFrameShape(QtWidgets.QFrame.StyledPanel)
def initUI(self):
self.loop_selector_frame_layout = QtWidgets.QGridLayout()
self.setLayout(self.loop_selector_frame_layout)
label_text = "Select two residues for a loop"
self.modeling_cluster_loop_selection_label = QtWidgets.QLabel(label_text)
self.modeling_cluster_loop_selection_label.setStyleSheet(modeling_options_subsections_style)
self.loop_selector_frame_layout.addWidget(self.modeling_cluster_loop_selection_label, 0, 0, 1, 3)
def initialize_list(self):
"""
Build the initial row in the user-defined loops frame.
"""
# The target chain sequence.
self.target_seq = self.modeling_cluster.target.my_sequence
# This is going to contain User_loop_combo objects.
self.list_of_loop_combos = []
# This list is going to contain info about loop ranges defined by the user through the
# GUI.
self.user_defined_loops = []
# Creates the comboboxes.
first = User_loop_combo_qt(self, self.modeling_cluster.target.get_polymer_residues())
self.list_of_loop_combos.append(first)
def add_new_user_loop(self):
"""
This is called when the "Add" button to add a user-defined loop is pressed.
"""
res_1 = self.list_of_loop_combos[-1].get_res1_combobox_val()
res_2 = self.list_of_loop_combos[-1].get_res2_combobox_val()
# Checks that both the comboboxes have been used to select a residue.
if res_1 == "" or res_2 == "":
txt = "You have to select two residues to define a loop."
self.protocol.pymod.main_window.show_warning_message("Warning", txt)
return None
# Checks that the same residue has not been selected in both comboboxes.
elif res_1 == res_2:
txt = "You cannot select the same starting and ending residue to define a loop."
self.protocol.pymod.main_window.show_warning_message("Warning", txt)
return None
res_1_pdb_id = int(res_1.split()[1])
res_2_pdb_id = int(res_2.split()[1])
if res_1_pdb_id >= res_2_pdb_id:
txt = "The index of the starting residue of a loop (you selected %s) can not be higher than the ending residue index (you selected %s)." % (res_1_pdb_id, res_2_pdb_id)
self.protocol.pymod.main_window.show_warning_message("Warning", txt)
return None
# If the two residues can be used to define a loop, then adds the new loop and updates
# the frame with a new combobox row.
new_ls_combo = User_loop_combo_qt(self, self.modeling_cluster.target.get_polymer_residues())
# Activates the previous row and returns the name of the 2 selected residues.
residues = self.list_of_loop_combos[-1].activate()
# Finishes and adds the new row.
self.list_of_loop_combos.append(new_ls_combo)
# Adds the pair to the self.user_defined_loops, which is going to be
# used in the launch_modelization() method.
self.user_defined_loops.append(residues)
def remove_user_loop(self, uls_to_remove):
"""
This is called when the "Remove" button is pressed.
"""
# Deactivate and get the right loop to remove.
ls_to_remove = uls_to_remove.deactivate()
# Finishes to adds the new row.
self.list_of_loop_combos.remove(uls_to_remove)
# Also removes the loop from the self.user_defined_loops.
self.user_defined_loops.remove(ls_to_remove)
class User_loop_combo_qt:
"""
Class for building in the Loop selection page in the modeling window a "row"
with two comboboxes and a button to add or remove a new loops. This is very
similar to the system used in the custom disulfide GUI.
"""
# This is used in the constructor when a new combobox row is created.
id_counter = 0
def __init__(self, parent, polymer_residues):
self.parent = parent
# Selected have the "Add" button, unselected have the "Remove" button.
self.selected = False
User_loop_combo_qt.id_counter += 1
self.row = User_loop_combo_qt.id_counter
# The list of residues of the target sequence.
self.polymer_residues = polymer_residues
# The list of strings that is going to appear on the scrollable menus of the comboboxes.
self.scrollable_res_list = []
self.scrollable_res_dict = {}
for res_i, res in enumerate(self.polymer_residues):
res_label = "%s %s" % (res.three_letter_code, res.db_index)
self.scrollable_res_list.append(res_label)
self.scrollable_res_dict[res_label] = self.polymer_residues
# Creates the first row with two comboboxes.
self.create_combobox_row()
combobox_padding = 30
button_padding = 40
def create_combobox_row(self):
"""
Builds a row with two comboboxes an "Add" button for defining a loop.
"""
# First residue combobox.
self.res1_combobox = QtWidgets.QComboBox() # Select the starting residue:
for item in self.scrollable_res_list:
self.res1_combobox.addItem(item)
self.res1_combobox.setEditable(False)
self.res1_combobox.setStyleSheet(small_font_style)
self.res1_combobox.setFixedWidth(self.res1_combobox.sizeHint().width() + self.combobox_padding)
# Second residue combobox.
self.res2_combobox = QtWidgets.QComboBox() # Select the ending residue:
for item in self.scrollable_res_list:
self.res2_combobox.addItem(item)
self.res2_combobox.setEditable(False)
self.res2_combobox.setStyleSheet(small_font_style)
self.res2_combobox.setFixedWidth(self.res2_combobox.sizeHint().width() + self.combobox_padding)
# "Add" button.
self.new_loop_button = QtWidgets.QPushButton("Add")
self.new_loop_button.setStyleSheet(small_font_style)
self.new_loop_button.clicked.connect(self.press_add_button)
self.new_loop_button.setFixedWidth(self.new_loop_button.sizeHint().width() + self.button_padding)
self.parent.loop_selector_frame_layout.addWidget(self.res1_combobox, self.row, 0)
self.parent.loop_selector_frame_layout.addWidget(self.res2_combobox, self.row, 1)
self.parent.loop_selector_frame_layout.addWidget(self.new_loop_button, self.row, 2)
User_loop_combo_qt.id_counter += 1
def select_res(self, i):
"""
This is launched by the combobox when some residue is selected.
"""
pass
def press_add_button(self):
self.parent.add_new_user_loop()
def activate(self):
"""
This is going to return the information about which residue have been selected when the "Add"
button is pressed.
"""
self.selected = True
# Removes the "Add" button.
self.remove_widget(self.new_loop_button)
self.new_loop_button = None
# Removes both comboboxes, but before get their values.
self.text1 = self.get_res1_combobox_val()
self.remove_widget(self.res1_combobox)
self.res1_combobox = None
self.text2 = self.get_res2_combobox_val()
self.remove_widget(self.res2_combobox)
self.res2_combobox = None
self.create_label_row()
return self.text1, self.text2
def remove_widget(self, widget):
self.parent.loop_selector_frame_layout.removeWidget(widget)
widget.deleteLater()
def create_label_row(self):
"""
Row with two labels and a "Remove" button.
"""
# Create a first residue label that tells which residue has been selected.
self.res1_label = QtWidgets.QLabel(self.text1)
self.res1_label.setStyleSheet(small_font_style)
self.res1_label.setAlignment(QtCore.Qt.AlignCenter)
self.parent.loop_selector_frame_layout.addWidget(self.res1_label, self.row, 0)
# Second residue label.
self.res2_label = QtWidgets.QLabel(self.text2)
self.res2_label.setStyleSheet(small_font_style)
self.res2_label.setAlignment(QtCore.Qt.AlignCenter)
self.parent.loop_selector_frame_layout.addWidget(self.res2_label, self.row, 1)
# Adds the "Remove" button.
self.remove_loop_button = QtWidgets.QPushButton("Remove")
self.remove_loop_button.setStyleSheet(small_font_style)
self.remove_loop_button.clicked.connect(self.press_remove_button)
self.parent.loop_selector_frame_layout.addWidget(self.remove_loop_button, self.row, 2)
def press_remove_button(self):
self.parent.remove_user_loop(self)
def deactivate(self):
"""
This is going to return the information about which loop has been removed when "Remove"
button is pressed.
"""
self.selected = False
self.remove_widget(self.res1_label)
self.res1_label = None
self.remove_widget(self.res2_label)
self.res2_label = None
self.remove_widget(self.remove_loop_button)
self.remove_loop_button = None
return self.text1, self.text2
def get_res1_combobox_val(self):
return self.res1_combobox.currentText()
def get_res2_combobox_val(self):
return self.res2_combobox.currentText()
################################################################################
# Options widgets. #
################################################################################
class Optimization_level_frame_loop_qt(Optimization_level_frame_qt):
use_max_cg_iterations_enf = True
use_vtfm_schedule_rds = False
use_md_schedule_rds = True
md_schedule_rds_default_val = "slow"
use_repeat_optimization_enf = False
use_max_obj_func_value_enf = False
class Custom_obj_func_frame_loop_qt(Custom_obj_func_frame_qt):
use_loop_stat_pot_rds = True
use_hddr_frame = False
use_hdar_frame = True
hdar_frame_text = "Dihedral angle restraints. Weight: "
use_charmm22_frame = True
use_soft_sphere_frame = True
use_dope_frame = False
use_stat_pot_frame = True
use_lj_frame = True
use_gbsa_frame = True
initial_nb_cutoff_val = 7.0
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_protocols/modeling_protocols/__init__.py | .py | 0 | 0 | null | Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_protocols/modeling_protocols/homology_modeling/__init__.py | .py | 144,446 | 2,679 | # Copyright 2020 by Giacomo Janson. All rights reserved.
# This code is part of the PyMod package and governed by its license. Please
# see the LICENSE file that should have been included as part of this package
# or the main __init__.py file in the pymod3 folder.
"""
Module for performing homology modeling with MODELLER in PyMod.
"""
import os
import sys
import shutil
import importlib
import pickle
from pymol import cmd
try:
import modeller
import modeller.automodel
from modeller.scripts import complete_pdb
from modeller import soap_pp
from modeller import parallel
except:
pass
from pymod_lib.pymod_protocols.base_protocols import PyMod_protocol, MODELLER_common
from pymod_lib.pymod_protocols.structural_analysis_protocols.dope_assessment import DOPE_assessment, show_dope_plot, compute_dope_of_structure_file
from pymod_lib.pymod_element_feature import Element_feature
from pymod_lib.pymod_threading import Protocol_exec_dialog
import pymod_lib.pymod_vars as pmdt
import pymod_lib.pymod_os_specific as pmos
import pymod_lib.pymod_seq.seq_manipulation as pmsm
import pymod_lib.pymod_structure as pmstr
from pymod_lib.pymod_protocols.modeling_protocols.homology_modeling._gui_qt import Modeling_window_qt
from pymod_lib.pymod_gui.shared_gui_components_qt import askyesno_qt
###################################################################################################
# HOMOLOGY MODELING. #
###################################################################################################
class MODELLER_homology_modeling(PyMod_protocol, MODELLER_common):
"""
Class to represent an homology model building session with MODELLER.
"""
# The maximum number of models that Modeler can produce at the same time.
max_models_per_session = 1000
default_modeller_random_seed = -8123
min_modeller_random_seed = -50000
max_modeller_random_seed = -2
# If set to True, creates a file "my_model.py" that can be used by command line MODELLER to
# perform the modellization. It is necessary when using MODELLER as an external coomand line
# tool, that is, when using MODELLER on PyMOL version which can't import the systemwide
# 'modeller' library. Users may also take the script and modify it according to their needs.
write_modeller_script_option = True
modeling_dirpath = ""
modeling_files_name = "my_model"
modeling_script_name = "%s.py" % modeling_files_name
modeling_script_lib_name = "%s_lib.py" % modeling_files_name
modeling_lib_name = modeling_script_lib_name.split(".")[0]
modeling_log_name = "%s.log" % modeling_files_name
pir_file_name = "align-multiple.ali"
modeller_temp_output_name = "modeller_saved_outputs.txt"
modeller_vars_filename = "modeller_vars.pkl"
# single_chain_models_formatted_string = "m%s_%s" # (decoy_number, model_name)
single_chain_models_name = "model"
single_chain_loop_models_name = "loop"
multiple_chains_models_name = "multi_model" # "MyMultiModel"
multiple_chains_loop_models_name = "multi_loop"
tc_temp_pymol_name = "template_complex_temp"
mc_temp_pymol_name = "model_complex_temp"
single_chain_model_color = "white"
list_of_model_chains_colors = pmdt.pymol_light_colors_list
loop_default_color = "orange" # "red"
protocol_name = "modeller_homology_modeling"
def __init__(self, pymod, **configs):
PyMod_protocol.__init__(self, pymod, **configs)
MODELLER_common.__init__(self)
self.use_hetatm_in_session = False
self.use_water_in_session = False
self.models_count = 0
self.modeling_protocol_initialization()
def modeling_protocol_initialization(self):
self.modeling_mode = "homology_modeling"
self.modeling_window_class_qt = Modeling_window_qt
def round_assessment_value(self, assessment_value, digits_after_point=3):
return round(assessment_value, digits_after_point)
def launch_from_gui(self):
"""
This method is called when the "MODELLER" option is clicked in the "Tools" menu.
"""
# Try to find if Modeller is installed on the user's computer.
modeller_error = self.pymod.modeller.check_exception()
if modeller_error is not None:
message = "In order to perform 3D modeling in PyMod, MODELLER must be installed and configured correctly. %s" % modeller_error
self.pymod.main_window.show_error_message("MODELLER Error", message)
return None
self.initialize_modeling_protocol_from_gui()
###########################################################################
# Checks the input selection. #
###########################################################################
def initialize_modeling_protocol_from_gui(self):
#---------------------------------------------------------------------
# Get the selected sequences to see if there is a correct selection. -
#---------------------------------------------------------------------
selected_sequences = self.pymod.get_selected_sequences()
# First check if at least one sequence is selected.
if not len(selected_sequences) > 0:
self.pymod.main_window.show_error_message("Selection Error", "Please select at least one target sequence to use MODELLER.")
return None
# Checks if all the selected sequences can be used to build a model.
if False in [s.can_be_modeled() for s in selected_sequences]:
self.pymod.main_window.show_error_message("Selection Error", "Please select only sequences that do not have a structure loaded in PyMOL.")
return None
# Checks that all the selected sequences are currently aligned to some other sequence
# (aligned sequences are always 'children'). Only sequences aligned to some template can be
# modeled.
if False in [e.is_child() for e in selected_sequences]:
self.pymod.main_window.show_error_message("Selection Error", "Please select only target sequences that are currently aligned to some structure.")
return None
#----------------------------------------------------------------------------------------
# Builds the modeling clusters which will store the information needed to run MODELLER. -
#----------------------------------------------------------------------------------------
# Using the 'build_cluster_list()' method build the 'self.involved_cluster_elements_list'
# just like when performing an alignment.
self.build_cluster_lists()
# This will contain a list of 'Modeling_cluster' objects.
self.modeling_clusters_list = []
# Checks other conditions in each cluster (that is, checks if there is only one target
# sequence selected per cluster and if it is aligned to some suitable template).
for cluster_element in self.involved_clusters_list:
# Checks that only one sequence per cluster is selected.
if not self.pymod.check_only_one_selected_child_per_cluster(cluster_element):
self.pymod.main_window.show_error_message("Selection Error", "Please select only one target sequence in the following cluster: %s" % (cluster_element.my_header))
return False
# Look if there is at least one suitable template aligned to the target sequence.
templates_temp_list = []
target_name = None
found_nucleic_acid_template = False
for e in cluster_element.get_children():
if not e.selected and e.is_suitable_template():
if e.polymer_type == "nucleic_acid":
found_nucleic_acid_template = True
templates_temp_list.append(e)
if e.selected:
target_name = e.my_header
# Checks if some templates have been found.
if not len(templates_temp_list) > 0:
self.pymod.main_window.show_error_message("Selection Error", "The target sequence '%s' is currently not aligned to any suitable template." % (target_name))
return False
# Checks for the absence of nucleic acid templates.
if found_nucleic_acid_template:
self.pymod.main_window.show_error_message("Selection Error", "The target sequence '%s' is currently aligned to a nucleic acid structure, which can not be used as a template." % (target_name))
return False
#-------------------------------------------------
# Actually builds the modeling clusters objects. -
#-------------------------------------------------
self.modeling_clusters_list.append(Modeling_cluster(self, cluster_element))
#--------------------------------------
# Build the homology modeling window. -
#--------------------------------------
# Define the modeling mode.
self.multiple_chain_mode = len(self.modeling_clusters_list) > 1
# Single chain homology modeling mode.
if not self.multiple_chain_mode:
self.build_modeling_window()
# Multiple chains modeling requires the identification of "template complexes" and
# additional controls.
else:
# This will build the 'self.available_template_complex_list'.
self.initialize_multichain_modeling()
# Proceeds only if there is at least one suitable "template complex".
if len(self.available_template_complex_list) > 0:
self.build_modeling_window()
else:
self.pymod.main_window.show_error_message("Selection Error", "There aren't any suitable 'Template Complexes' to perform multiple chain homology modeling.")
def initialize_multichain_modeling(self):
"""
This method will prepare data needed to perform multichain modeling. It will:
- identify suitable template complexes
- check if there are target sequences with the same sequence, so that symmetry restraints
can be applied to them when using Modeller.
"""
if self.modeling_mode == "homology_modeling":
#--------------------------------------------
# Generates modeling clusters dictionaries. -
#--------------------------------------------
for mc in self.modeling_clusters_list:
mc.build_template_complex_chains_dict()
#--------------------------------------------------
# Builds a list of suitable "template complexes". -
#--------------------------------------------------
# A "teplate complex" is available only if in each selected cluster there is at least ONE
# chain coming from the same original PDB file. For example, with these two cluster:
# - cluster 1: <1HHO_Chain:A>, 2DN2_Chain:A
# - cluster 2: <1HHO_Chain:B>, 3EOK_Chain:A
# the "template complex" is 1HHO.
# self.available_template_complex_list = []
# self.available_template_complex_dict = {}
codes_per_cluster = [set(mc.full_structure_files_dict.keys()) for mc in self.modeling_clusters_list]
self.available_template_complex_list = list(set.intersection(*codes_per_cluster))
self.available_template_complex_list.sort() # Sorts the list alphabetically.
self.all_full_structure_fn_dict = {}
for mc in self.modeling_clusters_list:
self.all_full_structure_fn_dict.update(mc.full_structure_fn_dict)
#--------------------------------------------------------------------------------------
# Checks if there are some target chains with the same sequence, so that the user may -
# apply symmetry restraints to them. -
#--------------------------------------------------------------------------------------
# Builds a 'Symmetry_restraints_groups' object that is going to be used to keep track of
# modeling clusters that have a target sequence with the same sequence.
self.symmetry_restraints_groups = Symmetry_restraints_groups_list()
for mc in self.modeling_clusters_list:
seq = str(mc.target.my_sequence).replace("-","")
# Adds a "symmetry restraints group" for each group of target sequences that share the
# exact same sequence.
if not seq in [g.id for g in self.symmetry_restraints_groups.get_groups()]:
self.symmetry_restraints_groups.add_group(seq)
self.symmetry_restraints_groups.get_group_by_id(seq).add_cluster(mc)
# Also assigns "symmetry ids" to each modeling cluster.
for mc in self.modeling_clusters_list:
seq = str(mc.target.my_sequence).replace("-","")
if seq in [g.id for g in self.symmetry_restraints_groups.get_groups(min_number_of_sequences=2)]:
mc.symmetry_restraints_id = seq
else:
mc.symmetry_restraints_id = None
def build_modeling_window(self):
"""
Builds the modeling window with all the options for MODELLER.
"""
# self.modeling_window = self.modeling_window_class(self.pymod.get_pymod_app(), self)
self.modeling_window = self.modeling_window_class_qt(parent=self.pymod.main_window,
protocol=self)
self.modeling_window.show()
# self.modeling_window.resize(700, 800)
def launch_modelization(self):
"""
This method is called when the 'SUBMIT' button in the modelization window is pressed. It
contains the code to instruct Modeller on how to perform the modelization.
"""
if not self.prepare_modelization():
return None
self.perform_modelization()
###########################################################################
# Checks the modeling window parameters. #
###########################################################################
def get_modeling_options_from_gui(self):
"""
Add to the 'Modeling_clusters' objects information about which templates to use according to
the parameters supplied by users.
"""
#--------------------------------------
# Get options from the 'Options' tab. -
#--------------------------------------
self.starting_model_number = 1
# Checks if a correct value in the max models entry has been supplied.
self.ending_model_number = self.modeling_window.max_models_enf.getvalue(validate=True)
# Get heteroatoms options.
if self.modeling_mode == "homology_modeling":
self.exclude_hetatms = pmdt.yesno_dict[self.modeling_window.exclude_heteroatoms_rds.getvalue()]
elif self.modeling_mode == "loop_refinement":
self.include_hetatms = self.modeling_window.exclude_heteroatoms_rds.getvalue()
# Check if a correct random seed value has been supplied.
self.modeller_random_seed = self.modeling_window.random_seed_enf.getvalue(validate=True)
# Check that a correct number of parallel jobs has been supplied.
self.modeller_n_jobs = self.modeling_window.n_jobs_enf.getvalue(validate=True)
if self.modeller_n_jobs != 1 and self.modeller_n_jobs > self.ending_model_number:
message = ("You can not use more MODELLER parallel jobs (%s) than the"
" number of models you want to build (%s). Please decrease"
" the number of parallel jobs." % (self.modeller_n_jobs, self.ending_model_number))
raise ValueError(message)
# Checks the optimization level parameters.
self.optimization_level = self.modeling_window.optimization_level_rds.getvalue()
if self.optimization_level == "Custom":
self.check_custom_optimization_level_parameters()
# Checks if the custom objective function parameters are correct.
self.use_custom_obj_func = self.modeling_window.get_custom_obj_func_option()
if self.use_custom_obj_func == "customize":
self.check_custom_obj_func_parameters()
elif self.use_custom_obj_func == "altmod":
self.set_altmod_obj_func_parameters()
else:
if self.modeling_mode == "loop_refinement":
# By default use the 'loopmodel' class.
self.loop_refinement_class_name = "loopmodel"
if self.modeling_mode == "homology_modeling":
self.superpose_to_templates = pmdt.yesno_dict[self.modeling_window.superpose_models_to_templates_rds.getvalue()]
if self.modeling_mode == "loop_refinement":
self.loop_initial_conformation = self.modeling_window.loop_initial_conformation_rds.getvalue()
self.color_models_by_choice = self.modeling_window.color_models_rds.getvalue()
#------------------------------------------
# Gets options for each modeling cluster. -
#------------------------------------------
for modeling_cluster in self.modeling_clusters_list:
# Begins a for cycle that is going to get the structures to be used as templates.
# When using loop refinement, it will get the loop intervals.
modeling_cluster.set_options_from_gui()
#------------------------------------
# Set the template complex options. -
#------------------------------------
if self.multiple_chain_mode:
self._get_multichain_options_from_gui()
#------------------------------------
# Check if hetatms have to be used. -
#------------------------------------
# Homology modeling.
if self.modeling_mode == "homology_modeling":
if self.exclude_hetatms:
# The 'hetatm' flag of MODELLER will be set to 'True', but each template heteroatom
# will be aligned to a gap character in the target sequence (that is, the heteroatom
# will not be included in the model).
self.use_hetatm_in_session = False
self.use_water_in_session = False
else:
self.use_hetatm_in_session = True
# Check if water molecules have to be included in the modeling session.
self.use_water_in_session = True in [mc.use_water_in_cluster() for mc in self.modeling_clusters_list]
# Loop refinement.
else:
if self.include_hetatms == "Het + Water":
self.use_hetatm_in_session = True
self.use_water_in_session = True
elif self.include_hetatms == "Het":
self.use_hetatm_in_session = True
self.use_water_in_session = False
elif self.include_hetatms == "No":
self.use_hetatm_in_session = False
self.use_water_in_session = False
#------------------------------------------------------------------------------------------
# Builds a list with the "knowns" for MODELLER and sets the name of the target sequences. -
#------------------------------------------------------------------------------------------
# Homology modeling.
if self.modeling_mode == "homology_modeling":
self.all_templates_namelist = []
self.modeller_target_name = ""
self.pir_sequences_dict = {}
if not self.multiple_chain_mode:
self.all_templates_namelist = self.modeling_clusters_list[0].get_template_nameslist()
self.modeller_target_name = self.single_chain_models_name # self.modeling_clusters_list[0].target_name
elif self.multiple_chain_mode:
for mc in self.modeling_clusters_list:
for t in mc.templates_list:
# Includes the "template complex" name only once.
if mc.is_template_complex_chain(t):
if not self.template_complex_modeller_name in self.all_templates_namelist:
self.all_templates_namelist.append(self.template_complex_modeller_name)
else:
self.all_templates_namelist.append(mc.template_options_dict[t]["modeller_name"])
self.modeller_target_name = self.multiple_chains_models_name
# Loop modeling.
else:
if not self.multiple_chain_mode:
self.modeller_target_name = self.single_chain_loop_models_name # self.modeling_clusters_list[0].target_name
elif self.multiple_chain_mode:
self.modeller_target_name = self.multiple_chains_loop_models_name
#-------------------------------------
# Get options for disulfide bridges. -
#-------------------------------------
if self.modeling_mode == "homology_modeling":
self.use_template_dsb = self.modeling_window.get_use_template_dsb_var()
self.use_auto_dsb = self.modeling_window.get_auto_dsb_var()
elif self.modeling_mode == "loop_refinement":
self.use_template_dsb = 0
self.use_auto_dsb = 0
self.use_user_defined_dsb = self.modeling_window.get_use_user_defined_dsb_var()
if self.use_user_defined_dsb:
self.all_user_defined_dsb = self.modeling_window.get_user_dsb_list()
#---------------------------------------
# Get options for symmetry restraints. -
#---------------------------------------
if self.multiple_chain_mode:
self.symmetry_restraints_groups.get_symmetry_restraints_from_gui()
def _get_multichain_options_from_gui(self):
"""
Finds the PDB_file object of the "template complex" selected by the user.
"""
# Name of the original full structure file of the template complex.
self.template_complex_filename = self.available_template_complex_list[self.modeling_window.get_template_complex_var()]
# Name of the template complex.
self.template_complex_name = self.all_full_structure_fn_dict[self.template_complex_filename]
self.template_complex_modeller_name = self.template_complex_name[:-4]
for mc in self.modeling_clusters_list:
for t in mc.templates_list:
if self.chain_is_from_template_complex(t):
mc.set_template_complex_chain(t)
def set_modeling_options(self):
"""
Set additional modeling options after some initial paramaters from the GUI have been
checked.
"""
if self.multiple_chain_mode:
self.list_of_symmetry_restraints = self.symmetry_restraints_groups.get_symmetry_restraints_list()
def chain_is_from_template_complex(self, pymod_element):
return pymod_element.get_structure_file(full_file=True) == self.template_complex_filename
def check_all_modeling_parameters(self):
"""
This will be used before launching Modeller to check:
- if the parameters of each modeling clusters are correct
- when performing multichain modeling
- if there is exactly 1 template complex chain selected in each cluster
- if symmetry restraints buttons are selected properly
if some parameters are not correct, an exception will be raised.
"""
# Checks if the parameters of all the "modeling clusters" are correct.
for mc in self.modeling_clusters_list:
self.check_modeling_cluster_parameters(mc)
# Check if there are only correct sequences.
for mc in self.modeling_clusters_list:
if not pmsm.check_correct_sequence(mc.target.my_sequence):
raise ValueError("The target sequence '%s' contains an invalid character in its sequence (%s) and MODELLER can't modelize it." % (mc.target.my_header, pmsm.get_invalid_characters_list(mc.target.my_sequence)[0]))
if self.modeling_mode == "homology_modeling":
for t in mc.templates_list:
if not pmsm.check_correct_sequence(t.my_sequence):
raise ValueError("The template '%s' contains an invalid character in its sequence (%s) and MODELLER can't use it as a template." % (t.my_header, pmsm.get_invalid_characters_list(t.my_sequence)[0]))
# If each "modeling cluster" has correct parameters, when performing multiple chain modeling,
# there are other conditions that must be satisfied.
if self.multiple_chain_mode:
if self.modeling_mode == "homology_modeling":
# Then perform additional controls for each modeling cluster and also get the list of
# the "target complex" chains selected by the user.
for mc in self.modeling_clusters_list:
# Gets the "template complex" chains selected in the current modeling cluster.
template_complex_selected_chains_in_cluster = [t for t in mc.templates_list if mc.is_template_complex_chain(t)]
# Check if the current cluster has a selected chain from the "target complex".
if len(template_complex_selected_chains_in_cluster) == 0:
raise ValueError("Please select AT LEAST one chain from the 'Template Complex' (%s) as a template for %s!" % (self.template_complex_name, mc.target_name))
# Checks if in some cluster there is more than one selected template belonging to the
# "template complex". This is needed for because ONLY one chain belonging to the
# "template complex" can be selected by ther user in each cluster.
if len(template_complex_selected_chains_in_cluster) > 1:
raise ValueError("Please select ONLY one chain from the 'Template Complex' (%s) as template for %s!" % (self.template_complex_name, mc.target_name))
# Sets the template complex in the modeling cluster. This will first set the
# 'block_index' attribute.
mc.set_template_complex_chain_to_use(template_complex_selected_chains_in_cluster[0])
# Fixes the 'block_index' attribute so that each block index will correspond to the
# numeric ID of the chain in the 3D model.
for mc_idx, mc in enumerate(self.get_modeling_clusters_list(sorted_by_id=True)):
mc.block_index = mc_idx
# Finally checks if the symmetries checkbuttons are selected properly.
self.check_symmetry_restraints_vars()
# Check if the alignments can be given as correct input to MODELLER.
if self.modeling_mode == "homology_modeling":
self.check_alignments()
# Warns the user if parallel MODELLER jobs can not be used.
if self.modeller_n_jobs > 1 and not self.pymod.parallel_modeller:
self.modeller_n_jobs = 1
fix_pythonpath_modeller_ref = "the PyMod user's guide"
message = ("Can not use multiple MODELLER jobs. MODELLER will be launched"
" serially, using only one job. If you want to use MODELLER in"
" a parallel way, re-install MODELLER in a way that it can be"
" fully compatible with PyMod/PyMOL (see %s for more"
" information)." % fix_pythonpath_modeller_ref)
self.pymod.main_window.show_warning_message("MODELLER warning", message)
# If on Windows, warns before using parallel MODELLER jobs.
if self.modeller_n_jobs > 1 and sys.platform == "win32":
message = ("You decided to use multiple parallel MODELLER jobs on a"
" Windows machine. The use of parallel MODELLER jobs does"
" not work on certain Windows machines (the modeling task"
" could crash or freeze unexpectedly). Are you sure you"
" want to use parallel jobs? You may try to do it, and if"
" the task fails, you can attempt to run it again with"
" only one job."
" Note that even if your Windows machine can use parallel"
" MODELLER jobs, this will trigger a message from Windows"
" Defender (this is because PyMOL will spawn a separate"
" child process for each parallel MODELLER job)."
" However, you can safely suppress this Windows Defender"
" message, in this way you will be able to use all the"
" cores you want also on Windows.")
choice = askyesno_qt("Use parallel MODELLER jobs?", message,
parent=self.pymod.get_qt_parent())
if not choice:
raise ValueError("Please set in the 'Options' tab of the MODELLER"
" window the 'N. of Parallel Jobs' option to 1"
" in order to use only one MODELLER job.")
def check_custom_optimization_level_parameters(self):
"""
Checks if the custom optimization level parameters are correct.
"""
# Max CG iterations.
if self.modeling_window.optimization_level_frame.use_max_cg_iterations_enf:
self.custom_max_cg_iterations = self.modeling_window.optimization_level_frame.max_cg_iterations_enf.getvalue(validate=True)
# VTFM schedule.
if self.modeling_window.optimization_level_frame.use_vtfm_schedule_rds:
self.custom_vtfm_schedule = self.modeling_window.optimization_level_frame.vtfm_schedule_rds.getvalue()
# MDSA protocol.
if self.modeling_window.optimization_level_frame.use_md_schedule_rds:
self.custom_md_schedule = self.modeling_window.optimization_level_frame.md_schedule_rds.getvalue()
# Repeat optimization.
if self.modeling_window.optimization_level_frame.use_repeat_optimization_enf:
self.custom_repeat_optimization = self.modeling_window.optimization_level_frame.repeat_optimization_enf.getvalue(validate=True)
# Max objective function value.
if self.modeling_window.optimization_level_frame.use_max_obj_func_value_enf:
self.custom_max_obj_func_value = self.modeling_window.optimization_level_frame.max_obj_func_value_enf.getvalue(validate=True)
return True
def check_custom_obj_func_parameters(self):
"""
Check the paramaters for customizing the objective function.
"""
# Automodel class for loop refinement.
if self.modeling_window.custom_obj_func_frame.use_loop_stat_pot_rds:
self.loop_refinement_class_name = self.modeling_window.custom_obj_func_frame.loop_stat_pot_rds.getvalue()
# Homology-derived distance restraints terms.
if self.modeling_window.custom_obj_func_frame.use_hddr_frame:
self.custom_w_hddr = self.modeling_window.custom_obj_func_frame.hddr_frame.getvalue(validate=True)
# Dihedral angle restraints terms.
if self.modeling_window.custom_obj_func_frame.use_hdar_frame:
self.custom_w_hdar = self.modeling_window.custom_obj_func_frame.hdar_frame.getvalue(validate=True)
# CHARM22 terms.
if self.modeling_window.custom_obj_func_frame.use_charmm22_frame:
self.custom_w_charmm22 = self.modeling_window.custom_obj_func_frame.charmm22_frame.getvalue(validate=True)
# Soft sphere overlap terms.
if self.modeling_window.custom_obj_func_frame.use_soft_sphere_frame:
# DOPE loopmodel does not use soft sphere terms.
get_custom_w_soft_sphere = True if self.modeling_mode == "homology_modeling" else self.loop_refinement_class_name != "DOPE loopmodel"
if get_custom_w_soft_sphere:
self.custom_w_soft_sphere = self.modeling_window.custom_obj_func_frame.soft_sphere_frame.getvalue(validate=True)
else:
self.custom_w_soft_sphere = 1.0
# Use DOPE in homology modeling.
if self.modeling_window.custom_obj_func_frame.use_dope_frame:
self.use_dope_in_obj_func = self.modeling_window.custom_obj_func_frame.get_use_dope_var()
if self.use_dope_in_obj_func:
self.custom_w_dope = self.modeling_window.custom_obj_func_frame.dope_frame.getvalue(validate=True)
else:
self.custom_w_dope = 0.0
# Statistical potentials terms in loop modeling.
if self.modeling_window.custom_obj_func_frame.use_stat_pot_frame:
self.custom_w_stat_pot_loop = self.modeling_window.custom_obj_func_frame.stat_pot_frame.getvalue(validate=True)
# Lennard-Jones terms.
if self.modeling_window.custom_obj_func_frame.use_lj_frame:
get_custom_w_lj = False if self.modeling_mode == "homology_modeling" else self.loop_refinement_class_name == "DOPE loopmodel"
if get_custom_w_lj:
self.custom_w_lj = self.modeling_window.custom_obj_func_frame.lj_frame.getvalue(validate=True)
else:
self.custom_w_lj = 1.0
# GBSA terms.
if self.modeling_window.custom_obj_func_frame.use_gbsa_frame:
get_custom_w_gbsa = False if self.modeling_mode == "homology_modeling" else self.loop_refinement_class_name == "DOPE loopmodel"
if get_custom_w_gbsa:
self.custom_w_gbsa = self.modeling_window.custom_obj_func_frame.gbsa_frame.getvalue(validate=True)
else:
self.custom_w_gbsa = 1.0
# Non-bonded interactions cutoff.
self.custom_nb_cutoff = self.modeling_window.custom_obj_func_frame.nb_cutoff_frame.getvalue(validate=True)
return True
def set_altmod_obj_func_parameters(self):
self.custom_w_hddr = 1.0
self.custom_w_hdar = 1.0
self.custom_w_charmm22 = 1.0
self.custom_w_soft_sphere = 1.0
self.use_dope_in_obj_func = True
self.custom_w_dope = 0.5
self.custom_nb_cutoff = 8.0
def check_modeling_cluster_parameters(self, modeling_cluster):
"""
Checks the if there are any problems with the user-supplied parameters of a "modeling cluster"
before starting the modeling process.
"""
# Checks if there are some templates that have been selected.
if modeling_cluster.templates_list == []:
raise ValueError("You have to select at least one template for target '%s' in order to build a model!" % (modeling_cluster.target_name))
def check_symmetry_restraints_vars(self):
"""
Check if symmetry restraints for multiple chain modeling can be applied.
"""
for srg in self.symmetry_restraints_groups.get_groups(min_number_of_sequences=2):
if srg.use == 1:
raise ValueError("In order to impose symmetry restraints you need select the 'Apply symmetry restraints' option for at least two targets with the same sequence (you selected this option only for target '%s')." % (srg.list_of_clusters[0].target_name))
def check_targets_with_cys(self):
"""
Check if there is at least one modeling cluster with a target sequence with at least two CYS
residues.
"""
return True in [mc.has_target_with_multiple_cys() for mc in self.modeling_clusters_list]
def check_structures_with_disulfides(self):
"""
Checks in all modeling clusters if there is at least one structure with a disulfide bridge.
"""
return True in [mc.has_structures_with_disulfides() for mc in self.modeling_clusters_list]
def get_template_complex_chains(self, sorted_by_id=False):
return [mc.get_template_complex_chain() for mc in self.get_modeling_clusters_list(sorted_by_id=sorted_by_id)]
def get_targets_list(self, sorted_by_id=False):
return [mc.target for mc in self.get_modeling_clusters_list(sorted_by_id=sorted_by_id)]
def get_modeling_clusters_list(self, sorted_by_id=False):
if sorted_by_id:
return sorted(self.modeling_clusters_list, key = lambda mc: mc.block_index)
else:
return self.modeling_clusters_list
def check_alignments(self):
"""
Checks if correct alignments are being provided.
"""
for modeling_cluster in self.modeling_clusters_list:
for char_id, target_char in enumerate(modeling_cluster.target.my_sequence):
if target_char == "X":
template_gaps = [template.my_sequence[char_id] == "-" for template in modeling_cluster.templates_list]
# The alignment is not correct if there are any 'X' character of the target not
# aligned to at least one residue of the templates.
if not False in template_gaps:
message = ("An X residue of the '%s' target sequence is currently"
" not aligned to a template residue. Make sure that"
" each X residue in your target sequences is aligned"
" with some residue of your templates." % (modeling_cluster.target_name))
raise ValueError(message)
def get_modeller_schedule_obj(self, phase, modeller_exec, name):
# MODELLER 3D Model building parameters.
modeller_3d_building_params_dict = {"cg": {"internal": {"fastest": modeller.automodel.autosched.fastest,
"very fast": modeller.automodel.autosched.very_fast,
"fast": modeller.automodel.autosched.fast,
"normal": modeller.automodel.autosched.normal,
"slow": modeller.automodel.autosched.slow},
"external": {"fastest": "modeller.automodel.autosched.fastest",
"very fast": "modeller.automodel.autosched.very_fast",
"fast": "modeller.automodel.autosched.fast",
"normal": "modeller.automodel.autosched.normal",
"slow": "modeller.automodel.autosched.slow"}},
"md": {"internal": {"none": None,
"very fast": modeller.automodel.refine.very_fast,
"fast": modeller.automodel.refine.fast,
"slow": modeller.automodel.refine.slow,
"very slow": modeller.automodel.refine.very_slow},
"external": {"none": "None",
"very fast": "modeller.automodel.refine.very_fast",
"fast": "modeller.automodel.refine.fast",
"slow": "modeller.automodel.refine.slow",
"very slow": "modeller.automodel.refine.very_slow"}}}
return modeller_3d_building_params_dict[phase][modeller_exec][name]
###########################################################################
# Prepares input files for MODELLER. #
###########################################################################
def prepare_modeling_session_files(self):
"""
Prepares the directory where MODELLER's output will be generated and moves into it.
"""
#--------------------------------------------------------------------------
# Build a directory where all the modeling session files will be located. -
#--------------------------------------------------------------------------
# The absolute path of the models directory.
models_dir = os.path.join(self.pymod.current_project_dirpath, self.pymod.models_dirname)
# Name of the model subdirectory where Modeller output files are going to be placed.
model_subdir_name = "%s_%s_%s" % (self.pymod.models_subdirectory, self.pymod.performed_modeling_count + 1, self.modeller_target_name)
# The absolute path of the model subdirectory.
modeller_output_dir_path = os.path.join(models_dir, model_subdir_name)
# Stores the path of the modeling directory.
self.modeling_dirpath = modeller_output_dir_path
if not os.path.isdir(self.modeling_dirpath):
os.mkdir(self.modeling_dirpath)
self.prepare_modeling_protocol_session_files()
#-------------------------------------------------------------------
# Changes the current working directory to the modeling directory. -
#-------------------------------------------------------------------
# The current directory has to be changed beacause in Modeller the user can't change the
# output directory, it has to be the current directory.
os.chdir(self.modeling_dirpath)
def prepare_modeling_protocol_session_files(self):
#-------------------------------------------------------------------------
# Prepares the structure files of the templates in the output directory. -
#-------------------------------------------------------------------------
# Prepares the single chain templates files.
for mc in self.modeling_clusters_list:
mc.prepare_single_chains_template_files()
# Prepares the template complex file.
if self.multiple_chain_mode:
list_of_template_complex_files = []
for t in self.get_template_complex_chains(sorted_by_id=True):
list_of_template_complex_files.append(os.path.join(self.modeling_dirpath, t.get_structure_file()))
pmstr.join_pdb_files(list_of_template_complex_files, os.path.join(self.modeling_dirpath, self.template_complex_name))
#---------------------------------------
# Prepares input and ouput file paths. -
#---------------------------------------
self.pir_file_path = os.path.join(self.modeling_dirpath, self.pir_file_name)
#--------------------------------------------------------------------------
# Creates a file with the target-template(s )alignment in the PIR format. -
#--------------------------------------------------------------------------
def build_pir_align_file(self):
"""
This function creates alignments in a PIR format: this is entirely rewritten from the
original PyMod version. This method should write the sequences as seen by MODELLER.
"""
# Starts to write the PIR sequence file needed by MODELLER for input.
pir_align_file_handle = open(self.pir_file_path, "w")
for modeling_cluster in self.modeling_clusters_list:
#--------------------------------------------------------------------------------------
# Prepares the full sequences (with both standard residues and heteroresidues) of the -
# target and templates. -
#--------------------------------------------------------------------------------------
het_to_use_list = []
np_hetatm_portions = {}
for template in modeling_cluster.templates_list:
# Builds the polymer sequence of the template. It comprises standard amino acid
# residues and modified residues making part of the polypeptide chain.
res_count = 0
res_list = template.get_polymer_residues()
polymer_seq = ""
for ali_id, ali_pos in enumerate(template.my_sequence):
if ali_pos != "-":
res = res_list[res_count]
if not res.is_standard_residue():
if modeling_cluster.template_options_dict[template]["hetres_dict"][res]:
het_to_use_list.append(ali_id)
polymer_seq += "."
else:
polymer_seq += ali_pos
res_count += 1
else:
polymer_seq += ali_pos
# Adds non-polymer heteroatoms (ligands and water molecules).
np_hetres_list = template.get_residues(standard=False, ligands=True,
modified_residues=False,
water=self.use_water_in_session)
np_hetatm_portions[template] = np_hetres_list
self.pir_sequences_dict[template] = {"pir_seq": polymer_seq,
"modeling_cluster": modeling_cluster}
# Builds the PIR string for the target sequence.
polymer_seq = ""
for ali_id, ali_pos in enumerate(modeling_cluster.target.my_sequence):
if ali_pos != "-":
if ali_id in het_to_use_list and self.use_hetatm_in_session:
polymer_seq += "."
else:
if ali_pos != "X":
polymer_seq += ali_pos
else:
polymer_seq += "A" # Adds an alanine for an undefined residue.
else:
polymer_seq += ali_pos
self.pir_sequences_dict[modeling_cluster.target] = {"pir_seq": polymer_seq, "modeling_cluster": modeling_cluster}
#-------------------------------------------------------------------------------
# Update the sequences by inserting in them ligands and water molecules in the -
# sequences aligned in PyMod (which miss ligands and water molecules). -
#-------------------------------------------------------------------------------
# Add the non-polymer heteratomic portions (containing ligands and water molecules)
# for the templates.
for template_i in modeling_cluster.templates_list:
for template_j in modeling_cluster.templates_list:
np_hetres_list = np_hetatm_portions[template_j]
# Add to each template its ligand portions.
if template_i is template_j:
self.pir_sequences_dict[template_i]["pir_seq"] += self._get_hetres_seq(np_hetres_list)
else:
self.pir_sequences_dict[template_i]["pir_seq"] += len(self._get_hetres_seq(np_hetres_list))*"-"
# Add the non-polymer heteratomic portion for the target.
for template_i in modeling_cluster.templates_list:
np_hetres_list = np_hetatm_portions[template_i]
for hetres in np_hetres_list:
if modeling_cluster.template_options_dict[template_i]["hetres_dict"][hetres] and self.use_hetatm_in_session:
if not hetres.is_water():
self.pir_sequences_dict[modeling_cluster.target]["pir_seq"] += "."
else:
self.pir_sequences_dict[modeling_cluster.target]["pir_seq"] += "w"
else:
self.pir_sequences_dict[modeling_cluster.target]["pir_seq"] += "-"
#--------------------------------
# Write the template sequences. -
#--------------------------------
# First write the template complex block (only for multiple chain mode).
if self.multiple_chain_mode:
print(">P1;%s" % self.template_complex_modeller_name, file=pir_align_file_handle)
print("structure:%s:.:.:.:.::::" % self.template_complex_modeller_name, file=pir_align_file_handle) # TODO: (template_code,template_chain,template_chain)
tc_pir_string = ""
for template_complex_chain in self.get_template_complex_chains(sorted_by_id=True): # TODO: order them.
tc_pir_string += self.pir_sequences_dict[template_complex_chain]["pir_seq"] + self.get_chain_separator()
print(self.get_pir_formatted_sequence(tc_pir_string), file=pir_align_file_handle)
# Then write the single chain template blocks.
for modeling_cluster in self.get_modeling_clusters_list(sorted_by_id=True):
for template in modeling_cluster.get_single_chain_templates():
# Writes the first line of the template.
template_code = modeling_cluster.template_options_dict[template]["modeller_name"]
template_chain = template.get_chain_id()
print(">P1;%s" % template_code, file=pir_align_file_handle)
print("structure:%s:.:%s:.:%s::::" % (template_code, template_chain, template_chain), file=pir_align_file_handle)
sct_pir_string = ""
for target_chain in self.get_targets_list(sorted_by_id=True):
if target_chain != modeling_cluster.target:
sct_pir_string += len(self.pir_sequences_dict[target_chain]["pir_seq"])*"-" + self.get_chain_separator() # TODO: adjust separator for single chain modeling.
else:
sct_pir_string += self.pir_sequences_dict[template]["pir_seq"] + self.get_chain_separator()
print(self.get_pir_formatted_sequence(sct_pir_string), file=pir_align_file_handle)
# Finally write the target block.
print(">P1;%s" % self.modeller_target_name, file=pir_align_file_handle)
print("sequence:%s:.:.:.:.::::" % self.modeller_target_name, file=pir_align_file_handle)
targets_pir_string = ""
for target in self.get_targets_list(sorted_by_id=True):
targets_pir_string += self.pir_sequences_dict[target]["pir_seq"] + self.get_chain_separator()
print(self.get_pir_formatted_sequence(targets_pir_string), file=pir_align_file_handle)
pir_align_file_handle.close()
def _get_hetres_seq(self, hetres_list):
hetres_seq = ""
for hetres in hetres_list:
if not hetres.is_water():
hetres_seq += "."
else:
hetres_seq += "w"
return hetres_seq
def get_pir_formatted_sequence(self,sequence,multi=False):
"""
Print one block of the PIR alignment file using 60 characters-long lines.
"""
formatted_sequence = ""
for s in range(0,len(sequence),60):
# For all the lines except the last one.
if (len(sequence) - s) > 60:
formatted_sequence += sequence[s:s+60] + "\n"
# For the last line.
else:
if not multi:
formatted_sequence += sequence[s:]+"*"+"\n"
else:
formatted_sequence += sequence[s:]+"/*"+"\n"
return formatted_sequence
def get_chain_separator(self):
if self.multiple_chain_mode:
return "/"
else:
return ""
###########################################################################
# Actually launches the full 3D modeling protocol. #
###########################################################################
def prepare_modelization(self):
#-----------------------------------------------------------------------------------
# Takes input supplied by users though the GUI and sets the names of sequences and -
# template which will be used by MODELLER. -
#-----------------------------------------------------------------------------------
try:
self.get_modeling_options_from_gui()
except Exception as e:
title = "Input Error"
self.pymod.main_window.show_error_message(title, str(e))
return False
# Starts the modeling process only if the user has supplied correct parameters.
try:
self.check_all_modeling_parameters()
except Exception as e:
title = "Input Error"
self.pymod.main_window.show_error_message(title, str(e))
return False
self.set_modeling_options()
# The modeling window can be destroyed.
self.modeling_window.destroy()
# Prepares the directory where MODELLER's output will be generated and moves into it.
self.prepare_modeling_session_files()
return True
def perform_modelization(self):
try:
self._perform_modelization()
except Exception as e:
self.finish_modeling_session(successful=False, error_message=str(e))
def launch_modeller(self, in_thread=False):
"""
Sets the MODELLER environment and script, then launches 3D model building.
"""
#************************
# Sets the environment. *
#************************
# Internal --------------------------------------------------
if self.run_modeller_internally:
# Use multiple CPUs, each one will be used to build a model copy.
if self.modeller_n_jobs > 1:
j = parallel.job()
for _job_idx in range(0, self.modeller_n_jobs):
j.append(parallel.local_slave())
modeller.log.verbose()
if self.modeller_random_seed == self.default_modeller_random_seed:
env = modeller.environ()
else:
env = modeller.environ(rand_seed=self.modeller_random_seed)
env.io.atom_files_directory = []
env.io.atom_files_directory.append(".")
#------------------------------------------------------------
# External --------------------------------------------------
if self.write_modeller_script_option:
# This dictionary will store string which will be used to write the modeling script
# files.
self.mod_script_dict = {"environment": "",
"hetres": "",
"automodel": {"definition": "",
"default_patches": "",
"special_patches": {"definition": "",
"multichain": "",
"disulfides": ""},
"special_restraints": "",
"loop_selection": "",},
"automodel_init": "",
"refinement": "",
"models_indices": "",
"make": "",
"external_post_make": ""}
self.mod_script_dict["environment"] += "import modeller\n"
self.mod_script_dict["environment"] += "import modeller.automodel\n"
if self.modeller_n_jobs > 1:
self.mod_script_dict["environment"] += "from modeller import parallel\n\n"
self.mod_script_dict["environment"] += "j = parallel.job()\n"
self.mod_script_dict["environment"] += "for _job_idx in range(0, %s):\n" % self.modeller_n_jobs
self.mod_script_dict["environment"] += " j.append(parallel.local_slave())\n\n"
else:
self.mod_script_dict["environment"] += "\n"
self.mod_script_dict["environment"] += "modeller.log.verbose()\n"
if self.modeller_random_seed == self.default_modeller_random_seed:
self.mod_script_dict["environment"] += "env = modeller.environ()\n"
else:
self.mod_script_dict["environment"] += "env = modeller.environ(rand_seed=%s)\n" % self.modeller_random_seed
if not self.run_modeller_internally:
env = None
self.mod_script_dict["environment"] += "env.io.atom_files_directory = []\n"
self.mod_script_dict["environment"] += "env.io.atom_files_directory.append('.')\n"
#------------------------------------------------------------
#**************************************
# Sets heteroatoms and water options. *
#**************************************
# If the user wants to include hetero-atoms and water molecules. The 'hetatm' flag is always
# set to 'True' in homology modeling.
if self.modeling_mode == "homology_modeling" or self.use_hetatm_in_session:
# Internal ----------------------------------------------
if self.run_modeller_internally:
env.io.hetatm = True
#--------------------------------------------------------
# External ----------------------------------------------
if self.write_modeller_script_option:
self.mod_script_dict["hetres"] += "env.io.hetatm = True\n"
#--------------------------------------------------------
# Use water only if the user chose to include water molecules from some template.
if self.use_water_in_session:
# Internal ------------------------------------------
if self.run_modeller_internally:
env.io.water = True
#----------------------------------------------------
# External ------------------------------------------
if self.write_modeller_script_option:
self.mod_script_dict["hetres"] += "env.io.water = True\n"
#----------------------------------------------------
#**********************************************************
# Define the name of the base automodel class to be used. *
#**********************************************************
if self.modeling_mode == "homology_modeling":
session_automodel_class = modeller.automodel.automodel
session_automodel_class_name = "automodel"
elif self.modeling_mode == "loop_refinement":
if self.loop_refinement_class_name == "loopmodel":
session_automodel_class = modeller.automodel.loopmodel
session_automodel_class_name = "loopmodel"
elif self.loop_refinement_class_name == "DOPE loopmodel":
session_automodel_class = modeller.automodel.dope_loopmodel
session_automodel_class_name = "dope_loopmodel"
#*******************************************************
# Creates a file with the alignment in the PIR format. *
#*******************************************************
if self.modeling_mode == "homology_modeling":
self.build_pir_align_file()
#*******************************************************************
# Defines a custom class to use some additional MODELLER features. *
#*******************************************************************
# This class is going to be used to build the "a" object used to perform the actual
# homology modelization. It is going to inherit everything from the automodel class
# but is going to have dynamically redifined routines to make it possible to:
# - include user defined disulfide bridges in the model
# - exclude template disulfide bridges in the model
# - build multichain models with symmetries restraints
# - rename the chains in multichain models
# External --------------------------------------------------
if self.write_modeller_script_option:
self.mod_script_dict["automodel"]["definition"] += "class MyModel(modeller.automodel.%s):\n" % session_automodel_class_name
#------------------------------------------------------------
#*******************************
# Template-derived disulfides. *
#*******************************
if self.modeling_mode == "homology_modeling":
# If there are some targets with at least two CYS residues and also some templates with
# disulfides, it decides whether to use template disulfides or to let the CYS residues
# in a "reduced" state.
if self.check_targets_with_cys() and self.check_structures_with_disulfides():
# If the user chose to use templates disulfides bridges MODELLER will automatically use
# the patch_ss_templates() method of the automodel class.
if self.use_template_dsb:
pass
# Don't use template dsbs: this will not create any dsbs in the model by not disulfide
# patching and leave the model CYS residues that in the template are engaged in a dsb in
# a "reduced" state.
else:
# External ------------------------------------------
if self.write_modeller_script_option:
self.mod_script_dict["automodel"]["default_patches"] += " def default_patches(self, aln):\n"
self.mod_script_dict["automodel"]["default_patches"] += " pass\n"
#----------------------------------------------------
#***********************************************************************************
# Part for multichain models and user defined disulfide bridges, which requires to *
# override the special_patches() method. *
#***********************************************************************************
# External --------------------------------------------------
if self.write_modeller_script_option:
self.mod_script_dict["automodel"]["special_patches"]["definition"] += " def special_patches(self, aln):\n"
#--------------------------------------------------------------------------------
# Renumber the residues in the new chains starting from 1. When Modeller builds -
# a multichain model it doesn't restart to count residues from 1 when changing -
# chain. The following code renumbers the residues in the correct way. -
#--------------------------------------------------------------------------------
if self.multiple_chain_mode:
if self.modeling_mode == "homology_modeling":
self.mod_script_dict["automodel"]["special_patches"]["multichain"] += " # Renumber the residues of the chains of multichain models starting from 1.\n"
self.mod_script_dict["automodel"]["special_patches"]["multichain"] += " count_dictionary = dict((chain.name, 1) for chain in self.chains)\n"
self.mod_script_dict["automodel"]["special_patches"]["multichain"] += " for chain in self.chains:\n"
self.mod_script_dict["automodel"]["special_patches"]["multichain"] += " for residue in chain.residues:\n"
self.mod_script_dict["automodel"]["special_patches"]["multichain"] += " residue.num = '%d' % (count_dictionary[chain.name])\n"
self.mod_script_dict["automodel"]["special_patches"]["multichain"] += " count_dictionary[chain.name] += 1\n"
#-------------------------------------------------------------
# Informs Modeller on how to build custom disulfide bridges. -
#-------------------------------------------------------------
if self.check_targets_with_cys():
# If the user wants to use some custom dsb.
if self.use_user_defined_dsb:
# Gets the list of user defined dsb for each modeling cluster (if the
# target of the modeling cluster doesn't have at least two cys residues
# it will have an [] empty list).
for (mci, mc) in enumerate(self.modeling_clusters_list):
for dsb in self.all_user_defined_dsb[mci]:
# For example "CYS 321".
cys1 = dsb[0][4:] # dsb[0][3:]
cys2 = dsb[1][4:] # dsb[1][3:]
# Redefine the routine to include user defined dsb.
# NOTE. If a bridge has the same cys the following error will ensue:
# <class '_modeller.ModellerError'>: unqang__247E> Internal error
if self.modeling_mode == "homology_modeling":
if self.multiple_chain_mode:
chain = mc.block_index
self.mod_script_dict["automodel"]["special_patches"]["disulfides"] += " self.patch(residue_type='DISU', residues=(self.chains[%s].residues['%s'], self.chains[%s].residues['%s']))\n" % (chain, cys1, chain, cys2)
else:
self.mod_script_dict["automodel"]["special_patches"]["disulfides"] += " self.patch(residue_type='DISU', residues=(self.residues['%s'], self.residues['%s']))\n" % (cys1, cys2)
elif self.modeling_mode == "loop_refinement":
chain = mc.target.get_chain_id()
self.mod_script_dict["automodel"]["special_patches"]["disulfides"] += " self.patch(residue_type='DISU', residues=(self.chains['%s'].residues['%s'], self.chains['%s'].residues['%s']))\n" % (chain, cys1, chain, cys2)
# If the user wants MODELLER to build automatically the dsb.
if self.use_auto_dsb:
# Adds disulfides bridges for cys that are sufficently close.
self.mod_script_dict["automodel"]["special_patches"]["disulfides"] += " self.patch_ss()\n"
#------------------------------------------------------------
#**************************************************************************
# Apply symmetry restraints to target chains that have the same sequence. *
#**************************************************************************
if self.multiple_chain_mode and len(self.list_of_symmetry_restraints) > 0:
# External ----------------------------------------------
if self.write_modeller_script_option:
# Constrain chains to be identical (but only restrain the C-alpha atoms, to reduce
# the number of interatomic distances that need to be calculated).
self.mod_script_dict["automodel"]["special_restraints"] += " def special_restraints(self, aln):\n"
for si, symmetry_restraints_group in enumerate(self.list_of_symmetry_restraints):
# MODELLER's API only allows to apply symmetry restraints to couple of chains.
# Therefore if we want to apply symmetry restraints to chains ("A", "B", "C"),
# we will first apply symmetry restraints to ("A", "B") and then to ("B", "C").
self.mod_script_dict["automodel"]["special_restraints"] += " # Symmetry restraints group n. %d.\n" % (si+1)
for s in symmetry_restraints_group:
# In homology modeling, the chain ids for symmetry restraints are integers
# starting from 0.
if self.modeling_mode == "homology_modeling":
self.mod_script_dict["automodel"]["special_restraints"] += " s1 = modeller.selection(self.chains[%s]).only_atom_types('CA')\n" % (s[0])
self.mod_script_dict["automodel"]["special_restraints"] += " s2 = modeller.selection(self.chains[%s]).only_atom_types('CA')\n" % (s[1])
# In loop refinement, the chain ids for symmetry restraints are the chain ID
# letters.
elif self.modeling_mode == "loop_refinement":
self.mod_script_dict["automodel"]["special_restraints"] += " s1 = modeller.selection(self.chains['%s']).only_atom_types('CA')\n" % (s[0])
self.mod_script_dict["automodel"]["special_restraints"] += " s2 = modeller.selection(self.chains['%s']).only_atom_types('CA')\n" % (s[1])
self.mod_script_dict["automodel"]["special_restraints"] += " self.restraints.symmetry.append(modeller.symmetry(s1, s2, 1.0))\n"
self.mod_script_dict["automodel"]["special_restraints"] += "\n"
# Report on symmetry violations greater than 1A after building each model.
self.mod_script_dict["automodel"]["special_restraints"] += " def user_after_single_model(self):\n"
self.mod_script_dict["automodel"]["special_restraints"] += " self.restraints.symmetry.report(1.0)\n\n"
#--------------------------------------------------------
#******************
# Loop selection. *
#******************
if self.modeling_mode == "loop_refinement":
# Definition of loop residues.
loop_intervals = []
for mcl in self.modeling_clusters_list:
loop_intervals.extend(mcl.loops_list)
# External ----------------------------------------------
if self.write_modeller_script_option:
self.mod_script_dict["automodel"]["special_restraints"] += " def select_loop_atoms(self):\n"
self.mod_script_dict["automodel"]["special_restraints"] += " return modeller.selection(\n"
for lt in loop_intervals:
self.mod_script_dict["automodel"]["special_restraints"] += " self.residue_range('%s:%s', '%s:%s'),\n" % (lt[0], lt[2], lt[1], lt[2])
self.mod_script_dict["automodel"]["special_restraints"] += " )\n\n"
#--------------------------------------------------------
# Loop starting conformation.
if self.loop_initial_conformation == "Linearized":
pass
elif self.loop_initial_conformation == "Original":
# External ----------------------------------------------
if self.write_modeller_script_option:
self.mod_script_dict["automodel"]["special_restraints"] += " def build_ini_loop(self, atmsel):\n"
self.mod_script_dict["automodel"]["special_restraints"] += " pass\n"
#--------------------------------------------------------
#**************************************************************
# Creates the "automodel" object to perform the modelization. *
#**************************************************************
# Internal --------------------------------------------------
if self.run_modeller_internally:
# Writes a module in the current modeling directory.
self.write_modeller_script(write_script=False, write_lib=True)
# Imports the module.
sys.path.append(self.modeling_dirpath)
_session_mod_lib = importlib.import_module(self.modeling_lib_name)
# Reloads it, so that the module from previous modeling sessions (if present) is
# refreshed with the new one.
_session_mod_lib = importlib.reload(_session_mod_lib)
MyModel = _session_mod_lib.MyModel
sys.path.remove(self.modeling_dirpath)
# Standard homology modeling.
if self.modeling_mode == "homology_modeling":
if not self.multiple_chain_mode:
assess_methods = (modeller.automodel.assess.GA341, modeller.automodel.assess.DOPE)
else:
assess_methods = (modeller.automodel.assess.DOPE, )
a = MyModel(env,
alnfile=self.pir_file_name, # alignment filename
knowns=tuple([str(tmpn) for tmpn in self.all_templates_namelist]), # tuple(self.all_templates_namelist), # codes of the templates
sequence=str(self.modeller_target_name), # code of the target
assess_methods=assess_methods)
# Loop modeling.
elif self.modeling_mode == "loop_refinement":
loop_assess_methods = (modeller.automodel.assess.DOPE, ) # soap_loop.Scorer()
a = MyModel(env,
sequence=str(self.modeller_target_name),
inimodel=self.loop_refinement_starting_model, # initial model of the target
loop_assess_methods=loop_assess_methods) # assess loops with statistical potentials
#------------------------------------------------------------
# External --------------------------------------------------
if self.write_modeller_script_option:
if self.modeling_mode == "homology_modeling":
self.mod_script_dict["automodel_init"] += "a = MyModel(\n"
self.mod_script_dict["automodel_init"] += " env,\n"
self.mod_script_dict["automodel_init"] += " alnfile='%s',\n" % self.pir_file_name
self.mod_script_dict["automodel_init"] += " knowns=%s,\n" % repr(tuple([str(tmpn) for tmpn in self.all_templates_namelist]))
self.mod_script_dict["automodel_init"] += " sequence='%s',\n" % (str(self.modeller_target_name))
if not self.multiple_chain_mode:
self.mod_script_dict["automodel_init"] += " assess_methods=(modeller.automodel.assess.GA341, modeller.automodel.assess.DOPE))\n"
else:
self.mod_script_dict["automodel_init"] += " assess_methods=(modeller.automodel.assess.DOPE, ))\n"
elif self.modeling_mode == "loop_refinement":
self.mod_script_dict["automodel_init"] += "a = MyModel(\n"
self.mod_script_dict["automodel_init"] += " env,\n"
self.mod_script_dict["automodel_init"] += " sequence='%s',\n" % self.modeller_target_name
self.mod_script_dict["automodel_init"] += " inimodel='%s',\n" % self.loop_refinement_starting_model
self.mod_script_dict["automodel_init"] += " loop_assess_methods=(modeller.automodel.assess.DOPE,))\n"
#------------------------------------------------------------
#************************************************
# Sets the level of refinment and optimization. *
#************************************************
#---------------------
# Homology modeling. -
#---------------------
if self.modeling_mode == "homology_modeling":
if self.optimization_level == "Low":
# Internal ----------------------------------------------
if self.run_modeller_internally:
# Low VTFM optimization:
a.library_schedule = modeller.automodel.autosched.very_fast
# Low MD optimization:
a.md_level = modeller.automodel.refine.very_fast
#--------------------------------------------------------
# External ----------------------------------------------
if self.write_modeller_script_option:
self.mod_script_dict["refinement"] += "a.library_schedule = modeller.automodel.autosched.very_fast\n"
self.mod_script_dict["refinement"] += "a.md_level = modeller.automodel.refine.very_fast\n"
#--------------------------------------------------------
elif self.optimization_level == "Default":
# a.library_schedule = modeller.automodel.autosched.normal
# a.max_var_iterations = 200
# a.md_level = modeller.automodel.refine.very_fast
# a.repeat_optimization = 1
# a.max_molpdf = 1e7
pass
elif self.optimization_level == "Mid":
# Internal ----------------------------------------------
if self.run_modeller_internally:
# Thorough VTFM optimization:
a.library_schedule = modeller.automodel.autosched.normal
a.max_var_iterations = 300
# Mid MD optimization:
a.md_level = modeller.automodel.refine.slow
#--------------------------------------------------------
# External ----------------------------------------------
if self.write_modeller_script_option:
self.mod_script_dict["refinement"] += "a.library_schedule = modeller.automodel.autosched.fast\n"
self.mod_script_dict["refinement"] += "a.max_var_iterations = 300\n"
self.mod_script_dict["refinement"] += "a.md_level = modeller.automodel.refine.slow\n"
#--------------------------------------------------------
elif self.optimization_level == "High":
# Internal ----------------------------------------------
if self.run_modeller_internally:
# Very thorough VTFM optimization:
a.library_schedule = modeller.automodel.autosched.slow
a.max_var_iterations = 300
# Thorough MD optimization:
a.md_level = modeller.automodel.refine.slow
# Repeat the whole cycle 2 times and do not stop unless obj.func. > 1E6
a.repeat_optimization = 2
a.max_molpdf = 1e8 # 1e6
#--------------------------------------------------------
# External ----------------------------------------------
if self.write_modeller_script_option:
self.mod_script_dict["refinement"] += "a.library_schedule = modeller.automodel.autosched.slow\n"
self.mod_script_dict["refinement"] += "a.max_var_iterations = 300\n"
self.mod_script_dict["refinement"] += "a.md_level = modeller.automodel.refine.slow\n"
self.mod_script_dict["refinement"] += "a.repeat_optimization = 2\n"
self.mod_script_dict["refinement"] += "a.max_molpdf = 1e8\n"
#--------------------------------------------------------
elif self.optimization_level == "Approximate":
# Internal ----------------------------------------------
if self.run_modeller_internally:
# Reduces the amount of homology-derived distance restraints to speed up the
# optimization.
a.max_ca_ca_distance = 10.0
a.max_n_o_distance = 6.0
a.max_sc_mc_distance = 5.0
a.max_sc_sc_distance = 4.5
# Few CG iterations.
a.max_var_iterations = 50
a.library_schedule = modeller.automodel.autosched.fastest
# No MD phase.
a.md_level = None
#--------------------------------------------------------
# External ----------------------------------------------
if self.write_modeller_script_option:
self.mod_script_dict["refinement"] += "a.max_ca_ca_distance = 10.0\n"
self.mod_script_dict["refinement"] += "a.max_n_o_distance = 6.0\n"
self.mod_script_dict["refinement"] += "a.max_sc_mc_distance = 5.0\n"
self.mod_script_dict["refinement"] += "a.max_sc_sc_distance = 4.5\n"
self.mod_script_dict["refinement"] += "a.max_var_iterations = 50\n"
self.mod_script_dict["refinement"] += "a.library_schedule = modeller.automodel.autosched.fastest\n"
self.mod_script_dict["refinement"] += "a.md_level = None\n"
#--------------------------------------------------------
elif self.optimization_level == "Custom":
# Internal ----------------------------------------------
if self.run_modeller_internally:
a.max_var_iterations = self.custom_max_cg_iterations
a.library_schedule = self.get_modeller_schedule_obj("cg", "internal", self.custom_vtfm_schedule)
a.md_level = self.get_modeller_schedule_obj("md", "internal", self.custom_md_schedule)
a.repeat_optimization = self.custom_repeat_optimization
a.max_molpdf = 10**self.custom_max_obj_func_value
#--------------------------------------------------------
# External ----------------------------------------------
if self.write_modeller_script_option:
self.mod_script_dict["refinement"] += "a.max_var_iterations = %s\n" % self.custom_max_cg_iterations
self.mod_script_dict["refinement"] += "a.library_schedule = %s\n" % self.get_modeller_schedule_obj("cg", "external", self.custom_vtfm_schedule)
self.mod_script_dict["refinement"] += "a.md_level = %s\n" % self.get_modeller_schedule_obj("md", "external", self.custom_md_schedule)
self.mod_script_dict["refinement"] += "a.repeat_optimization = %s\n" % self.custom_repeat_optimization
self.mod_script_dict["refinement"] += "a.max_molpdf = 10**%s\n" % self.custom_max_obj_func_value
#--------------------------------------------------------
#-------------------
# Loop refinement. -
#-------------------
elif self.modeling_mode == "loop_refinement":
if self.optimization_level == "Low":
# Internal ----------------------------------------------
if self.run_modeller_internally:
a.loop.md_level = modeller.automodel.refine.very_fast
#--------------------------------------------------------
# External ----------------------------------------------
if self.write_modeller_script_option:
self.mod_script_dict["refinement"] += "a.loop.md_level = modeller.automodel.refine.very_fast\n"
#--------------------------------------------------------
elif self.optimization_level == "Mid":
# Internal ----------------------------------------------
if self.run_modeller_internally:
a.loop.md_level = modeller.automodel.refine.fast
#--------------------------------------------------------
# External ----------------------------------------------
if self.write_modeller_script_option:
self.mod_script_dict["refinement"] += "a.loop.md_level = modeller.automodel.refine.fast\n"
#--------------------------------------------------------
elif self.optimization_level == "Default":
# a.loop.md_level = modeller.automodel.refine.slow
pass
elif self.optimization_level == "High":
# Internal ----------------------------------------------
if self.run_modeller_internally:
a.loop.md_level = modeller.automodel.refine.very_slow
#--------------------------------------------------------
# External ----------------------------------------------
if self.write_modeller_script_option:
self.mod_script_dict["refinement"] += "a.loop.md_level = modeller.automodel.refine.very_slow\n"
#--------------------------------------------------------
elif self.optimization_level == "Approximate":
# Internal ----------------------------------------------
if self.run_modeller_internally:
a.loop.md_level = None
#--------------------------------------------------------
# External ----------------------------------------------
if self.write_modeller_script_option:
self.mod_script_dict["refinement"] += "a.loop.md_level = None\n"
#--------------------------------------------------------
elif self.optimization_level == "Custom":
# Internal ----------------------------------------------
if self.run_modeller_internally:
a.loop.max_var_iterations = self.custom_max_cg_iterations
a.loop.md_level = self.get_modeller_schedule_obj("md", "internal", self.custom_md_schedule)
#--------------------------------------------------------
# External ----------------------------------------------
if self.write_modeller_script_option:
self.mod_script_dict["refinement"] += "a.loop.max_var_iterations = %s\n" % self.custom_max_cg_iterations
self.mod_script_dict["refinement"] += "a.loop.md_level = %s\n" % self.get_modeller_schedule_obj("md", "external", self.custom_md_schedule)
#--------------------------------------------------------
#************************************
# Customize the objective function. *
#************************************
if self.use_custom_obj_func in ("customize", "altmod"):
#---------------------
# Homology modeling. -
#---------------------
if self.modeling_mode == "homology_modeling":
w_dope = self.custom_w_dope if self.use_dope_in_obj_func else 0
# Internal ----------------------------------------------
if self.run_modeller_internally:
# Sets the weights of the objective function.
a.env.schedule_scale = modeller.physical.values(default=1.0,
# Statistical potential terms.
nonbond_spline=w_dope,
# Distance restraints terms.
ca_distance=self.custom_w_hddr,
n_o_distance=self.custom_w_hddr,
sd_mn_distance=self.custom_w_hddr,
sd_sd_distance=self.custom_w_hddr,
# Dihedral restraints terms.
phi_dihedral=self.custom_w_hdar,
psi_dihedral=self.custom_w_hdar,
chi1_dihedral=self.custom_w_hdar,
chi2_dihedral=self.custom_w_hdar,
chi3_dihedral=self.custom_w_hdar,
chi4_dihedral=self.custom_w_hdar,
phi_psi_dihedral=self.custom_w_hdar,
# CHARM22 terms.
bond=self.custom_w_charmm22,
angle=self.custom_w_charmm22,
dihedral=self.custom_w_charmm22,
improper=self.custom_w_charmm22,
# Soft-sphere terms.
soft_sphere=self.custom_w_soft_sphere)
edat = a.env.edat
edat.contact_shell = self.custom_nb_cutoff
# Allow calculation of statistical (dynamic_modeller) potential.
if self.use_dope_in_obj_func:
edat.dynamic_modeller = True
# Group restraints.
gprsr = modeller.group_restraints(a.env, classes='$(LIB)/atmcls-mf.lib', parameters='$(LIB)/dist-mf.lib')
a.group_restraints = gprsr
#--------------------------------------------------------
# External ----------------------------------------------
if self.write_modeller_script_option:
self.mod_script_dict["refinement"] += """
# Sets the weights of the objective function.
a.env.schedule_scale = modeller.physical.values(default=1.0,
# Statistical potential terms.
nonbond_spline=%s,
# Distance restraints terms.
ca_distance=%s,
n_o_distance=%s,
sd_mn_distance=%s,
sd_sd_distance=%s,
# Dihedral restraints terms.
phi_dihedral=%s,
psi_dihedral=%s,
chi1_dihedral=%s,
chi2_dihedral=%s,
chi3_dihedral=%s,
chi4_dihedral=%s,
phi_psi_dihedral=%s,
# CHARM22 terms.
bond=%s,
angle=%s,
dihedral=%s,
improper=%s,
# Soft-sphere terms.
soft_sphere=%s)
# Non-bonded interactions cutoff.
edat = a.env.edat
edat.contact_shell = %s
""" % (w_dope, self.custom_w_hddr, self.custom_w_hddr, self.custom_w_hddr, self.custom_w_hddr, self.custom_w_hdar, self.custom_w_hdar, self.custom_w_hdar, self.custom_w_hdar, self.custom_w_hdar, self.custom_w_hdar, self.custom_w_hdar, self.custom_w_charmm22, self.custom_w_charmm22, self.custom_w_charmm22, self.custom_w_charmm22, self.custom_w_soft_sphere, self.custom_nb_cutoff)
if self.use_dope_in_obj_func:
self.mod_script_dict["refinement"] += "# Adds DOPE terms to the objective function.\n"
self.mod_script_dict["refinement"] += "edat.dynamic_modeller = True\n"
self.mod_script_dict["refinement"] += "gprsr = modeller.group_restraints(a.env, classes='$(LIB)/atmcls-mf.lib', parameters='$(LIB)/dist-mf.lib')\n"
self.mod_script_dict["refinement"] += "a.group_restraints = gprsr\n"
#--------------------------------------------------------
#-------------------
# Loop refinement. -
#-------------------
elif self.modeling_mode == "loop_refinement":
# Internal ----------------------------------------------
if self.run_modeller_internally:
# Sets the weights of the objective function.
a.loop.env.schedule_scale = modeller.physical.values(default=1.0,
# Statistical potential terms.
nonbond_spline=self.custom_w_stat_pot_loop,
# Dihedral restraints terms.
phi_dihedral=self.custom_w_hdar,
psi_dihedral=self.custom_w_hdar,
chi1_dihedral=self.custom_w_hdar,
chi2_dihedral=self.custom_w_hdar,
chi3_dihedral=self.custom_w_hdar,
chi4_dihedral=self.custom_w_hdar,
phi_psi_dihedral=self.custom_w_hdar,
# CHARM22 terms.
bond=self.custom_w_charmm22,
angle=self.custom_w_charmm22,
dihedral=self.custom_w_charmm22,
improper=self.custom_w_charmm22,
# Soft-sphere terms.
soft_sphere=self.custom_w_soft_sphere,
# Lennard-Jones terms.
lennard_jones=self.custom_w_lj,
# GBSA terms.
gbsa=self.custom_w_gbsa,
)
edat = a.loop.env.edat
edat.contact_shell = self.custom_nb_cutoff
#--------------------------------------------------------
# External ----------------------------------------------
if self.write_modeller_script_option:
self.mod_script_dict["refinement"] += """
# Sets the weights of the objective function.
a.loop.env.schedule_scale = modeller.physical.values(default=1.0,
# Statistical potential terms.
nonbond_spline=%s,
# Dihedral restraints terms.
phi_dihedral=%s,
psi_dihedral=%s,
chi1_dihedral=%s,
chi2_dihedral=%s,
chi3_dihedral=%s,
chi4_dihedral=%s,
phi_psi_dihedral=%s,
# CHARM22 terms.
bond=%s,
angle=%s,
dihedral=%s,
improper=%s,
# Soft-sphere terms.
soft_sphere=%s,
# Lennard-Jones terms.
lennard_jones=%s,
# GBSA terms.
gbsa=%s,
)
# Non-bonded interactions cutoff.
edat = a.loop.env.edat
edat.contact_shell = %s
""" % (self.custom_w_stat_pot_loop, self.custom_w_hdar, self.custom_w_hdar, self.custom_w_hdar, self.custom_w_hdar, self.custom_w_hdar, self.custom_w_hdar, self.custom_w_hdar, self.custom_w_charmm22, self.custom_w_charmm22, self.custom_w_charmm22, self.custom_w_charmm22, self.custom_w_soft_sphere, self.custom_w_lj, self.custom_w_gbsa, self.custom_nb_cutoff)
#--------------------------------------------------------
#*********************************************************************
# Determines how many models to build and actually build the models. *
#*********************************************************************
# External --------------------------------------------------
if self.write_modeller_script_option:
if self.modeling_mode == "homology_modeling":
self.mod_script_dict["models_indices"] += "a.starting_model = %s\n" % self.starting_model_number
self.mod_script_dict["models_indices"] += "a.ending_model = %s\n" % self.ending_model_number
elif self.modeling_mode == "loop_refinement":
self.mod_script_dict["models_indices"] += "a.loop.starting_model = %s\n" % self.starting_model_number
self.mod_script_dict["models_indices"] += "a.loop.ending_model = %s\n" % self.ending_model_number
if self.modeller_n_jobs > 1:
self.mod_script_dict["make"] += "a.use_parallel_job(j)\n"
self.mod_script_dict["make"] += "a.make()\n"
# Saves an output file that will be read by PyMod when MODELLER is executed externally.
self.write_modeller_script(write_script=True, write_lib=False)
if not self.run_modeller_internally:
raise Exception("Not implemented anymore.")
#------------------------------------------------------------
# Internal --------------------------------------------------
if self.run_modeller_internally:
if self.modeling_mode == "homology_modeling":
a.starting_model = self.starting_model_number # index of the first model
a.ending_model = self.ending_model_number # index of the last model
elif self.modeling_mode == "loop_refinement":
a.loop.starting_model = self.starting_model_number
a.loop.ending_model = self.ending_model_number
if self.modeller_n_jobs > 1:
# Use a parallel job for model building.
a.use_parallel_job(j)
# This is the method that launches the model building phase.
a.make()
#------------------------------------------------------------
# Saves the 'automodel' object in a pickle file that can be loaded in the main thread.
if in_thread:
with open(self.modeller_vars_filename, "wb") as v_fh:
pickle.dump(a, v_fh)
# Directly returns the 'automodel' object.
else:
return env, a
def load_modeller_vars(self):
with open(self.modeller_vars_filename, "rb") as v_fh:
a = pickle.load(v_fh)
return None, a
def _perform_modelization(self):
###########################################################################################
# Sets the MODELLER run and build 3D models. #
###########################################################################################
# Launches in the main thread the method in which the 3D models are actually built.
if not self.pymod.use_protocol_threads:
env, a = self.launch_modeller(in_thread=False)
# Launches in a separate thread the method.
else:
label_text = "Running 3D model building. Please wait for the process to complete..."
p_dialog = Protocol_exec_dialog(app=self.pymod.main_window, pymod=self.pymod,
function=self.launch_modeller,
args=(True, ),
title="Building 3D models with MODELLER.",
label_text=label_text,
# A thread with MODELLER can not exit safely.
lock=True,
wait_start=1.0, wait_end=1.0, wait_close=1.0,
lock_title=self.pymod.modeller_lock_title,
lock_message=self.pymod.modeller_lock_message,
stdout_filepath=os.path.join(self.modeling_dirpath, "modeller_log.txt"))
p_dialog.exec_()
# Loads the MODELLER 'automodel' object saved on a pickle file.
with open(os.devnull, "w") as n_fh: # Silence some MODELLER output.
original_stdout = sys.stdout
sys.stdout = n_fh
env, a = self.load_modeller_vars()
sys.stdout = original_stdout
###########################################################################################
# Finishes to set options for MODELLER and returns back to the PyMod projects directory. #
###########################################################################################
os.chdir(self.pymod.current_project_dirpath)
#-----------------------------------------------------------------------------------
# Cycles through all models built by MODELLER to import them into PyMod and PyMOL. -
#-----------------------------------------------------------------------------------
# Gets the ouput of MODELLER in a list of dictionaries.
automodel_output = self._get_modeller_outputs(a)
# Filters the output by removing models that were not built (when using the standard
# MODELLER algorithm, a modeling failure is very rare).
automodel_output = [m for m in automodel_output if m["failure"] is None]
# Insert here code to perform additional actions on the models.
# ...
# If the list of correctly built models is empty, terminates the modeling session.
if not automodel_output:
error_message = ("No models could be correctly built by MODELLER."
" Terminating the modeling session.")
self.finish_modeling_session(successful=False, error_message=error_message)
return None
for model_file_number, model in enumerate(automodel_output):
#--------------------------------------------------------
# Builds PyMod elements for each of the model's chains. -
#--------------------------------------------------------
# Gets the file name generated by MODELLER (stored in model['name']).
model_file_full_path = os.path.join(self.modeling_dirpath, model['name'])
# Builds a new file name for the model.
pymod_model_name = self._get_model_filename()
# Parses the PDB file of the model.
parsed_model_file = pmstr.Parsed_model_pdb_file(self.pymod, model_file_full_path,
output_directory=self.pymod.structures_dirpath,
new_file_name=pymod_model_name,
model_root_name=self.modeller_target_name)
current_model_chains_elements = []
# Multiple chain models will yield multiple PyMod elements (one for each chain, thus one
# for each modeling cluster).
for chain_number, (model_element, modeling_cluster) in enumerate(zip(parsed_model_file.get_pymod_elements(), self.get_modeling_clusters_list(sorted_by_id=True))):
# Add the new element to PyMod.
self.pymod.add_element_to_pymod(model_element, color=self.get_model_color(chain_number, self.multiple_chain_mode))
modeling_cluster.model_elements_list.append(model_element)
current_model_chains_elements.append(model_element)
# Gets the aligned sequence of the original target element.
original_target_aligned_sequence = modeling_cluster.target.my_sequence
'''
# Substitute the first model with the target element.
if model_file_number == 0 and modeling_cluster.target.models_count == 0 and not modeling_cluster.target.has_structure():
# self.original_target_aligned_sequence = modeling_cluster.target.my_sequence
self.pymod.replace_element(old_element=modeling_cluster.target, new_element=model_element)
modeling_cluster.target = model_element
'''
# Adds gaps to the various copies of the target sequencs.
model_element.trackback_sequence(original_target_aligned_sequence)
#------------------------------------------
# Superpose models to templates in PyMOL. -
#------------------------------------------
if self.modeling_mode == "homology_modeling":
# Just superpose the model's chain to the first template.
if self.superpose_to_templates and not self.multiple_chain_mode:
super_template_selector = self.modeling_clusters_list[0].templates_list[0].get_pymol_selector()
# Builds only a selector for the first and only chain models.
for mod_e in current_model_chains_elements:
self.superpose_in_pymol(mod_e.get_pymol_selector(), super_template_selector)
# Superposing for multichain modeling is more complex, and follows a different strategy.
elif self.superpose_to_templates and self.multiple_chain_mode:
# Loads the full template complex file in PyMOL when the first model is loaded.
if model_file_number == 0:
cmd.load(os.path.join(self.modeling_dirpath, self.template_complex_name), self.tc_temp_pymol_name)
# Superpose each separated chain of the template complex to the corresponding
# chains of the full template complex.
for mc in self.get_modeling_clusters_list(sorted_by_id=True):
self.superpose_in_pymol(mc.get_template_complex_chain().get_pymol_selector(), # Single template complex chain selector.
"%s and chain %s" % (self.tc_temp_pymol_name, mc.tc_chain_id), # Same chain of the full template complex structure.
save_superposed_structure=False)
# Loads the full model complex file.
cmd.load(model_file_full_path, self.mc_temp_pymol_name)
# Superpose the full model complex file on the template complex using PyMOL.
self.superpose_in_pymol(self.mc_temp_pymol_name, self.tc_temp_pymol_name, save_superposed_structure=False)
# Saves the new superposed file in the structures directory.
# cmd.save(os.path.join(self.pymod.structures_dirpath, model['name']), self.mc_temp_pymol_name)
# Superpose single model chains to the correspondig one of the full model complex.
for mod_e in current_model_chains_elements:
self.superpose_in_pymol(mod_e.get_pymol_selector(),
"%s and chain %s" % (self.mc_temp_pymol_name, mod_e.get_chain_id()),
save_superposed_structure=False)
# Cleans up after having superposed the last multiple chain model.
if model_file_number == len(a.outputs) - 1:
cmd.delete(self.mc_temp_pymol_name)
cmd.delete(self.tc_temp_pymol_name)
# Increases the models count.
self.increase_model_number()
#------------------------------------------------------------
# Quality assessment of the models. -
#------------------------------------------------------------
# Launches in the main thread the quality assessment.
if not self.pymod.use_protocol_threads:
self.perform_quality_assessment(env, automodel_output)
# Launches in a separate thread the assessement.
else:
label_text = "Running 3D model quality assessment. Please wait for the process to complete..."
p_dialog = Protocol_exec_dialog(app=self.pymod.main_window, pymod=self.pymod,
function=self.perform_quality_assessment,
args=(env, automodel_output),
wait_start=2, wait_end=1.0, wait_close=1.0,
title="Assessing the quality of 3D models.",
label_text=label_text,
lock=True,
lock_title=self.pymod.modeller_lock_title,
lock_message=self.pymod.modeller_lock_message,
stdout_filepath=os.path.join(self.modeling_dirpath, "modeller_assessment_log.txt"))
p_dialog.exec_()
#------------------------------------------------------------
# Finishes the modeling process. -
#------------------------------------------------------------
# Adds the information of this new modeling session to PyMod.
self.pymod.modeling_session_list.append(self.current_modeling_session)
# Finally shows the table and the previously built DOPE profile comprising DOPE curves of
# every model and templates.
self.pymod.show_table(**self.current_modeling_session.assessment_table_data)
show_dope_plot(dope_plot_data=self.current_modeling_session.dope_profile_data,
parent_window=self.pymod.get_qt_parent(),
pymod=self.pymod)
# Completes the process.
self.finish_modeling_session(successful=True)
def perform_quality_assessment(self, env, automodel_output):
# Starts to build the 'current_modeling_session' which will be used to build a new item on
# the 'Models' submenu on the main window.
self.current_modeling_session = Modeling_session_information(session_id=self.pymod.performed_modeling_count + 1,
automodel_output=automodel_output,
modeling_directory_path=self.modeling_dirpath)
#------------------------------------------------------------------------------------------
# Create a DOPE profile plot for all models built in this by computing their DOPE scores. -
#------------------------------------------------------------------------------------------
self.all_assessed_structures_list = []
session_dope_protocol = DOPE_assessment(self.pymod, output_directory=self.modeling_dirpath)
session_dope_protocol.remove_temp_files = False
# Actually computes the DOPE profiles the templates and of the models.
for mc in self.get_modeling_clusters_list(sorted_by_id=True):
# Templates.
if self.modeling_mode == "homology_modeling":
for template in mc.templates_list:
session_dope_protocol.add_element(template)
self.all_assessed_structures_list.append(template)
# Initial models for loop refinement.
elif self.modeling_mode == "loop_refinement":
session_dope_protocol.add_element(mc.target)
self.all_assessed_structures_list.append(mc.target)
# Models.
for model_element in mc.model_elements_list:
session_dope_protocol.add_element(model_element)
self.all_assessed_structures_list.append(model_element)
session_dope_protocol.compute_all_dopes(env=env)
session_dope_protocol.assign_dope_items()
# This for cycle is used to add extra 'None' values in multiple chains profiles. In this way
# if, for example, there is a model with chains 'A' and 'B', in the plot the profile of
# chain 'B' will be put just after the end of the profile of chain 'A'.
alignment_lenght = 0
for mc in self.get_modeling_clusters_list(sorted_by_id=True):
# Computes the DOPE profile of the templates.
if self.modeling_mode == "homology_modeling":
for template in mc.templates_list:
template_dope_data = session_dope_protocol.prepare_dope_plot_data([template], start_from=alignment_lenght, mode="multiple")
self.current_modeling_session.add_template_dope_data(template_dope_data[0])
elif self.modeling_mode == "loop_refinement":
target_dope_data = session_dope_protocol.prepare_dope_plot_data([mc.target], start_from=alignment_lenght, mode="multiple")
self.current_modeling_session.add_template_dope_data(target_dope_data[0])
# Computes the DOPE profile of the models.
for model_index, model_element in enumerate(mc.model_elements_list):
model_dope_data = session_dope_protocol.prepare_dope_plot_data([model_element], start_from=alignment_lenght, mode="multiple")
self.current_modeling_session.add_model_dope_data(model_dope_data[0], model_index)
alignment_lenght += len(mc.target.my_sequence)
#------------------------------------------------------------------------------------
# Gets the objective function and DOPE scores values for each full model (the model -
# comprising all the chains) built. -
#------------------------------------------------------------------------------------
# This will also save in the modeling directory the DOPE profile files of the models and
# templates.
session_assessment_data = []
# Initialize a new environment for SOAP scoring.
if self.multiple_chain_mode:
soap_env = modeller.environ()
soap_env.libs.topology.read(file='$(LIB)/top_heav.lib')
soap_env.libs.parameters.read(file='$(LIB)/par.lib')
# Score each model copy.
for decoy_index in range(0, len(automodel_output)):
model = automodel_output[decoy_index]
fmo = self.current_modeling_session.full_models[decoy_index]
obj_funct_value = self.get_model_objective_function_value(model)
dope_score = self.get_model_dope_score_value(model, env)
assessment_values = [model["name"], self.round_assessment_value(obj_funct_value), self.round_assessment_value(dope_score)]
# Score with SOAP-PP.
if self.multiple_chain_mode:
soap_pp_assessor = soap_pp.Assessor()
complete_mdl = complete_pdb(soap_env, os.path.join(self.modeling_dirpath, model['name']))
atmsel = modeller.selection(complete_mdl)
soap_pp_score = atmsel.assess(soap_pp_assessor)
assessment_values.append(self.round_assessment_value(soap_pp_score))
# Score with GA341 (only for single chain modeling).
if self.modeling_mode == "homology_modeling" and not self.multiple_chain_mode:
assessment_values.append(self.round_assessment_value(model["GA341 score"][0], digits_after_point=4))
session_assessment_data.append(assessment_values)
fmo.assessment_data = assessment_values
# Prepares data to show a table with assessment values for each model.
column_headers = ["Model Filename", "Objective Function", "DOPE score"]
if self.multiple_chain_mode:
column_headers.append("SOAP-PP")
if self.modeling_mode == "homology_modeling" and not self.multiple_chain_mode:
column_headers.append("GA341")
assessment_table_args = {"column_headers": column_headers,
"data_array": session_assessment_data,
"title": "Assessment of Models of Modeling Session %s" % self.current_modeling_session.session_id,
# "number_of_tabs": 4, "rowheader_width": 25,
"width": 850, "height": 420,
"sortable": True,
}
self.current_modeling_session.assessment_table_data = assessment_table_args
def finish_modeling_session(self, successful=False, error_message=""):
"""
Finishes the modeling session, both when models where sucessully built and when some error
was encountered.
"""
# Displays the models in PyMod main window, if some were built.
self.pymod.main_window.gridder(update_menus=True, clear_selection=True, update_elements=successful, update_clusters=successful)
if successful:
# Colors the models and templates according to their DOPE values.
if self.color_models_by_choice == "DOPE Score":
for element in self.all_assessed_structures_list:
self.pymod.main_window.color_element_by_dope(element)
else:
# Color loops when performing loop refinement.
if self.modeling_mode == "loop_refinement":
for mcl in self.modeling_clusters_list: # Cycle each target.
for model_element in mcl.model_elements_list: # Cycle each model.
for start_res, end_res, _chain in mcl.loops_list: # Cycle each loop.
# Builds a loop feature.
start_res = int(start_res)
end_res = int(end_res)
feature_name = "loop %s-%s" % (start_res, end_res)
# Convert the 'db_index' values into 'seq_index' values.
feature_start = model_element.get_residue_by_db_index(start_res).seq_index
feature_end = model_element.get_residue_by_db_index(end_res).seq_index
new_feature = Element_feature(id=None, name=feature_name,
start=feature_start, end=feature_end,
description=feature_name,
feature_type='sequence',
color=self.loop_default_color)
# Adds the loop feature to the model element.
model_element.add_feature(new_feature)
self.pymod.main_window.color_element_by_custom_scheme(model_element)
# Increases modeling count.
self.pymod.performed_modeling_count += 1
# Reverts the stdout to the system one, and removes the modeling files.
else:
try:
if os.path.isdir(self.modeling_dirpath):
shutil.rmtree(self.modeling_dirpath)
self.pymod.main_window.show_error_message("Modeling Session Error",
"PyMod has encountered the following error while running MODELLER: %s" % error_message)
except:
self.pymod.main_window.show_error_message("Modeling Session Error",
"PyMod has encountered an unknown error in the modeling session: %s" % error_message)
# Moves back to the current project directory.
os.chdir(self.pymod.current_project_dirpath)
def _get_modeller_outputs(self, a):
if self.modeling_mode == "homology_modeling":
return a.outputs
elif self.modeling_mode == "loop_refinement":
return a.loop.outputs
def _get_model_filename(self):
return "%s_%s_%s" % (self.modeller_target_name, self.get_model_number()+1, self.pymod.performed_modeling_count+1)
###############################################################################################
# Prepares the modeling script. #
###############################################################################################
def write_modeller_script(self, write_script=True, write_lib=True):
"""
This methods will write two files: a script file for running MODELLER externally from PyMod
(if the 'write_script' argument is set to 'True') and a module file storing the custom
'automodel' class (if the 'write_lib' argument 'True'). In order to work externally from
PyMod, both files must be present.
"""
if not write_script and not write_lib:
raise ValueError("Either one of 'write_script' or 'write_lib' must be set to 'True'.")
if write_script:
mod_script_fh = open(self.modeling_script_name, "w")
# Environment.
print("from %s import MyModel\n" % self.modeling_lib_name, file=mod_script_fh)
print(self.mod_script_dict["environment"], file=mod_script_fh)
print(self.mod_script_dict["hetres"], file=mod_script_fh)
if write_lib:
# Automodel derived class.
mod_script_lib_fh = open(self.modeling_script_lib_name, "w")
print("import modeller", file=mod_script_lib_fh)
print("import modeller.automodel\n", file=mod_script_lib_fh)
print(self.mod_script_dict["automodel"]["definition"], file=mod_script_lib_fh)
if self.check_non_empty_automodel_dict():
# Default patches.
if self.mod_script_dict["automodel"]["default_patches"] != "":
print(self.mod_script_dict["automodel"]["default_patches"], file=mod_script_lib_fh)
# Special patches.
if self.check_non_empty_special_patches_dict():
print(self.mod_script_dict["automodel"]["special_patches"]["definition"], file=mod_script_lib_fh)
if self.mod_script_dict["automodel"]["special_patches"]["multichain"] != "":
print(self.mod_script_dict["automodel"]["special_patches"]["multichain"], file=mod_script_lib_fh)
if self.mod_script_dict["automodel"]["special_patches"]["disulfides"] != "":
print(self.mod_script_dict["automodel"]["special_patches"]["disulfides"], file=mod_script_lib_fh)
# Special restraints.
if self.mod_script_dict["automodel"]["special_restraints"] != "":
print(self.mod_script_dict["automodel"]["special_restraints"], file=mod_script_lib_fh)
else:
print(" pass\n", file=mod_script_lib_fh)
mod_script_lib_fh.close()
if write_script:
# Model building options.
print(self.mod_script_dict["automodel_init"], file=mod_script_fh)
print(self.mod_script_dict["refinement"], file=mod_script_fh)
print(self.mod_script_dict["models_indices"], file=mod_script_fh)
print(self.mod_script_dict["make"], file=mod_script_fh)
if not self.run_modeller_internally:
print(self.mod_script_dict["external_post_make"], file=mod_script_fh)
mod_script_fh.close()
def check_non_empty_automodel_dict(self):
if self.mod_script_dict["automodel"]["default_patches"] != "":
return True
elif self.check_non_empty_special_patches_dict():
return True
elif self.mod_script_dict["automodel"]["special_restraints"] != "":
return True
else:
return False
def check_non_empty_special_patches_dict(self):
if self.mod_script_dict["automodel"]["special_patches"]["multichain"] != "":
return True
elif self.mod_script_dict["automodel"]["special_patches"]["disulfides"] != "":
return True
else:
return False
###########################################################################
# Prepares the output of the modeling session. #
###########################################################################
def get_model_number(self):
return self.models_count
def increase_model_number(self):
self.models_count += 1
def get_model_objective_function_value(self, model):
"""
Gets the Objective function values of model. The model argument must be an item of the
'outputs' list of the automodel class of MODELLER.
"""
model_file = open(os.path.join(self.modeling_dirpath, model['name']), "r")
obj_funct_value = float(model_file.readlines()[1][39:].replace(" ",""))
model_file.close()
return obj_funct_value
def get_model_dope_score_value(self, model, env=None, use_automodel_assessment=True):
"""
Gets the total DOPE score of a model.
"""
if use_automodel_assessment:
dope_score = model["DOPE score"]
else:
dope_score = compute_dope_of_structure_file(self.pymod,
os.path.join(self.modeling_dirpath, model['name']),
os.path.join(self.modeling_dirpath, "%s.profile" % model['name'][:-4]),
env=env)
return dope_score
def get_model_color(self, chain_number, multiple_chain_mode):
if not multiple_chain_mode:
return self.single_chain_model_color
else:
return self.list_of_model_chains_colors[chain_number % len(self.list_of_model_chains_colors)]
###################################################################################################
# Modeling clusters and additional classes for the modeling protocol. #
###################################################################################################
class Modeling_cluster:
"""
Class representing a "modeling cluster", that is a target-template(s) alignment
used in a homology modeling protocol. When performing multiple chain homology
modeling, there will be as many modeling clusters as the number of target
chains.
"""
def __init__(self, modeling_protocol, cluster):
self.modeling_protocol = modeling_protocol
self.cluster_element = cluster
# This is actually the target sequence that is selected by the user.
self.target = [c for c in self.cluster_element.get_children() if c.selected][0]
# This is used to load the model into PyMOL when Modeller has done its job.
self.target_name = self.get_target_name()
# self.model_color=target.my_color
self.aligned_elements_list = self.target.get_siblings(sequences_only=True)
# Another for cycle to look for templates aligned to the target sequence. These will be
# displayed in the modeling window.
self.suitable_templates_list = [e for e in self.aligned_elements_list if e.is_suitable_template()]
# This will contain a list objects from the Structure_frame class.
self.structure_frame_list = []
self.water_molecules_count = 0
# Dictionary for additional options widgets.
self.restraints_options_dict = {}
# Chain ID of the template complex chain for this cluster.
self.tc_chain_id = " "
# Names of the template complex files.
self.full_structure_files_dict = {}
self.full_structure_fn_dict = {}
# Index of the modeling cluster (corresponds to the numerical ID of the chain in a model,
# the first chain has ID = 1, the second ID = 2, etc...).
self.block_index = 0
self.symmetry_restraints_id = None
# List of the elements representing the models built in a session.
self.model_elements_list = []
def get_target_name(self):
if not self.target.is_model():
return pmos.clean_file_name(self.target.compact_header)
else:
return self.target.model_root_name # re.match("m\d+_(.*)_chain_[A-Za-z]","m1_test_chain_x").groups()
def build_template_complex_chains_dict(self):
"""
Generates modeling clusters dictionaries.
They will be needed to check if a suitable "template complex" can be used. A cluster with
the following templates:
- 1HHO_Chain:A, 2DN2_Chain:A, 2DN2_Chain:B
will generate a dictionary with the following structure:
- {"1HHO.pdb":1, "2DN2.pdb":2}
The keys are the original PDB files, and the values are the number of chains in the cluster
which belong to that PDB structure.
"""
for t in self.suitable_templates_list:
template_original_file = t.get_structure_file(full_file=True)
if template_original_file in list(self.full_structure_files_dict.keys()):
self.full_structure_files_dict[template_original_file] += 1
else:
self.full_structure_files_dict.update({template_original_file: 1})
self.full_structure_fn_dict[template_original_file] = t.structure.file_name_root + ".pdb"
def set_options_from_gui(self):
self.templates_list = []
# Important dictionary that is going to contain informations about the templates.
self.template_options_dict = {}
template_count = 0
for suitable_template, structure_frame in zip(self.suitable_templates_list, self.structure_frame_list):
# Gets the values of each template checkbutton (it will be 0 if the structure was
# not selected or 1 if it was selected): selects only structures that were selected
# by the user to be used as templates.
if structure_frame.is_selected():
# Adds some information about the modeling options to the elements.
template_options_dict = {
"id": template_count,
# For every selected structure takes the values of HETRES checkbutton.
"hetres_dict": structure_frame.get_template_hetres_dict(),
# Do the same with the water checkbutton.
"water_state": structure_frame.get_water_state_var(),
"structure_file": None, "sequence_file": None,
"modeller_name": None,
"template_complex": False,
"selected_template_complex":False}
# Populate each modeling_cluster "template_list" with the elements selected by
# the user from the "suitable_templates_list".
self.add_new_template(pymod_element= suitable_template, template_options = template_options_dict)
template_count += 1
def add_new_template(self, pymod_element, template_options):
self.templates_list.append(pymod_element)
# This list will be used to inform Modeller about which are the "known" sequences.
# It will contain the headers of the templates.
self.template_options_dict.update({pymod_element: template_options})
self.template_options_dict[pymod_element]["modeller_name"] = self.get_template_modeller_name(pymod_element)
def get_template_modeller_name(self, pymod_element):
return pymod_element.get_structure_file().replace(":","_")[:-4]
# IF THE ORIGINAL PDB FILES ARE TO BE USED:
# - self.struct_list[a].structure.original_chain_pdb_file_name.replace(":","_")
# In the original Pymod it was:
# - "1UBI_Chain_A" for non ce-aligned seqs
# - "1UBI_Chain_A_aligned.pdb" for aligned seqs
# These codes must be the same in the .ali file and when assigning the "knowns".
# If it the names don't contain the .pdb extension, Modeller will still find the
# right files.
def get_template_nameslist(self):
ordered_keys = sorted(list(self.template_options_dict.keys()), key=lambda k:self.template_options_dict[k]["id"])
return [self.template_options_dict[k]["modeller_name"] for k in ordered_keys]
def use_water_in_cluster(self):
return 1 in [self.template_options_dict[t]["water_state"] for t in self.templates_list]
def has_target_with_multiple_cys(self):
return self.target.my_sequence.count("C") >= 2
def set_template_complex_chain(self, template):
self.template_options_dict[template]["template_complex"] = True
def set_template_complex_chain_to_use(self, template):
self.template_options_dict[template]["selected_template_complex"] = True
self.tc_chain_id = template.get_chain_id()
# Temporarily sets the 'block_index' of a multiple chain model.
self.block_index = template.get_chain_numeric_id()
def is_template_complex_chain(self, template):
"""
Check if a template chain is part of the 'template complex'.
"""
return self.template_options_dict[template]["template_complex"]
def get_template_complex_chain(self):
for template in self.templates_list:
if self.is_template_complex_chain(template):
return template
return None
def get_single_chain_templates(self):
return [t for t in self.templates_list if not self.is_template_complex_chain(t)]
def get_modeling_elements(self):
"""
Returns a list with the 'PyMod_elements' objects of the target and the templates of the
modeling cluster.
"""
modeling_elements = self.templates_list[:]
modeling_elements.insert(0, self.target)
return modeling_elements
def prepare_single_chains_template_files(self):
for template in self.templates_list:
# if not self.is_template_complex_chain(template):
self.prepare_template_files(template)
def prepare_template_files(self, template):
# Copy the templates structure files in the modeling directory.
template_str_file = template.get_structure_file(basename_only=False)
copied_template_str_file = os.path.basename(template_str_file)
shutil.copy(template_str_file, os.path.join(self.modeling_protocol.modeling_dirpath, copied_template_str_file))
self.template_options_dict[template]["structure_file"] = copied_template_str_file
# Build a sequence file for the templates.
# self.build_modeller_sequence_file(template)
def build_modeller_sequence_file(self, template):
# From point 17 of https://salilab.org/modeller/manual/node38.html.
env = modeller.environ()
modeller.log.none()
env.io.hetatm = True
if self.modeling_protocol.use_water_in_session:
env.io.water = True
structure_file_name = self.template_options_dict[template]["structure_file"]
structure_file_code = os.path.splitext(structure_file_name)[0]
mdl = modeller.model(env, file=os.path.join(self.modeling_protocol.modeling_dirpath, structure_file_name))
aln = modeller.alignment(env)
aln.append_model(mdl, align_codes=structure_file_code)
output_sequence_file = structure_file_code+'_aln.chn'
aln.write(file=os.path.join(self.modeling_protocol.modeling_dirpath, output_sequence_file))
self.template_options_dict[template]["sequence_file"] = output_sequence_file
def has_structures_with_disulfides(self):
return True in [e.has_disulfides() for e in self.suitable_templates_list]
def get_symmetry_chain_id(self):
return self.block_index
def get_symmetry_restraints_var(self):
return int(self.restraints_options_dict["symmetry"].isChecked())
class Symmetry_restraints_groups_list:
"""
This class will be used to store a list of Symmetry_restraint_group objects.
"""
def __init__(self):
self.list_of_groups = []
def get_groups(self, min_number_of_sequences=0):
"""
Returns a list of Symmetry_restraints_group objects that contain at least the number of
sequences specified in the argument.
"""
return [g for g in self.list_of_groups if len(g.list_of_clusters) >= min_number_of_sequences]
def get_groups_to_use(self):
return [g for g in self.get_groups(min_number_of_sequences=2) if g.use > 1]
def add_group(self,symmetry_id):
srg = Symmetry_restraints_group(symmetry_id)
self.list_of_groups.append(srg)
def get_group_by_id(self,symmetry_id):
for g in self.list_of_groups:
if g.id == symmetry_id:
return g
def get_symmetry_restraints_from_gui(self):
for srg in self.get_groups(min_number_of_sequences=2):
si = len([mc for mc in srg.list_of_clusters if mc.get_symmetry_restraints_var() == 1])
srg.use = si
def get_symmetry_restraints_list(self):
"""
Builds a list of symmetry restraints to be used by MODELLER.
"""
list_of_symmetry_restraints = []
symmetry_restraints_groups_to_use = self.get_groups_to_use()
if len(symmetry_restraints_groups_to_use) > 0:
# Define group of chains on which symmetry restraints have to be applied.
list_of_groups = []
for srg in symmetry_restraints_groups_to_use:
list_of_chains = []
for mcl in srg.list_of_clusters:
if mcl.get_symmetry_restraints_var() == 1:
list_of_chains.append(mcl.get_symmetry_chain_id())
list_of_groups.append(list_of_chains)
for list_of_chains in list_of_groups:
s = []
for c in range(len(list_of_chains)):
i1 = list_of_chains[c]
i2 = None
if c < len(list_of_chains) - 1:
i2 = list_of_chains[c+1]
if i2 != None:
s.append([i1, i2])
list_of_symmetry_restraints.append(s)
return list_of_symmetry_restraints
class Symmetry_restraints_group:
"""
When performing multichain modeling, this will be used to identify a "symmetry restraints
group", a group of target sequences that share the exact same sequence. By keeping track of
these groups, PyMod can let the user apply symmetry restraints to those chains when using
MODELLER.
"""
def __init__(self, symmetry_id):
# The "id" is just the target sequence stripped of all indels.
self.id = symmetry_id
# This will contain a list of Modeling_cluster objects that contain a target sequence
# with the same sequence as the "id".
self.list_of_clusters = []
# This will be set to True if the user decides to apply symmetry restraints to this group
# of target sequences.
self.use = False
def add_cluster(self, modeling_cluster):
"""
Adds a Modeling_cluster object to the group list_of_clusters.
"""
self.list_of_clusters.append(modeling_cluster)
class Modeling_session_information:
"""
Class for containing information on modeling sessions.
"""
def __init__(self, session_id, automodel_output, modeling_directory_path):
self.session_id = session_id
self.modeling_directory_path = modeling_directory_path
self.assessment_table_data = None
self.dope_profile_data = []
self.full_models = []
for model in automodel_output:
self.full_models.append(Full_model(os.path.join(self.modeling_directory_path, model['name'])))
def add_template_dope_data(self, template_dope_data):
"""
Stores the templates also profiles to each 'Full_model' object, so that the profile of the
templates can be inspected by accessing the 'Models' menu.
"""
for fmo in self.full_models: # All templates' data will be available in each model plot.
fmo.dope_profile_data.append(template_dope_data)
self.dope_profile_data.append(template_dope_data)
def add_model_dope_data(self, model_dope_data, model_index):
"""
Adds the DOPE profiles of the models.
"""
self.full_models[model_index].dope_profile_data.append(model_dope_data)
self.dope_profile_data.append(model_dope_data)
class Full_model:
"""
Class for containing information on models built in a modeling session. Object of this class
will be contained in the '.full_models' attribute of 'Modeling_session_information' class
objects.
"""
def __init__(self, original_file_path):
self.original_file_path = original_file_path
self.model_name = os.path.basename(self.original_file_path)[:-4]
self.dope_profile_data = []
self.assessment_data = None
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_protocols/modeling_protocols/homology_modeling/_gui_qt.py | .py | 90,207 | 2,002 | # Copyright 2020 by Giacomo Janson. All rights reserved.
# This code is part of the PyMod package and governed by its license. Please
# see the LICENSE file that should have been included as part of this package
# or the main __init__.py file in the pymod3 folder.
"""
GUI for MODELLER in PyMod.
"""
import multiprocessing
from pymol.Qt import QtWidgets, QtCore
from pymod_lib.pymod_gui.shared_gui_components_qt import (PyMod_QFormLayout,
PyMod_entryfield_qt, PyMod_entry_qt,
PyMod_radioselect_qt, PyMod_spinbox_entry_qt,
active_entry_style, inactive_entry_style,
options_title_style,
large_font_style, small_font_style,
highlight_color)
import pymod_lib.pymod_seq.seq_manipulation as pmsm
###############################################################################################
# Class for MODELLER options window. #
###############################################################################################
modeling_window_title_style = options_title_style # "%s; font-weight: bold" % options_title_style
modeling_options_sections_style = "font-weight: bold; color: #BBBBBB" # "color: %s" % highlight_color # "font-weight: bold"
modeling_options_sections_style = "color: #efefef" # "color: #ededed"
modeling_options_subsections_style = small_font_style + "; color: %s" % highlight_color
modeling_options_subsections_style = small_font_style + "; font-weight: bold"
modeling_options_subsections_style = small_font_style + "; " + modeling_options_sections_style
modeling_options_inactive_label_color = "#8c8c8c"
# modeling_window_explanation
class Modeling_window_qt(QtWidgets.QMainWindow):
"""
A class to represent the 'Homology Modeling Window' of PyMod.
"""
is_pymod_window = True
# options_frame_grid_options = {"padx": 10, "pady": 10, "sticky": "w"}
optimization_level_choices = ("Approximate", "Low", "Default", "Mid", "High", "Custom")
def __init__(self, parent, protocol):
super(Modeling_window_qt, self).__init__(parent)
self.protocol = protocol
self.initUI()
def initUI(self):
#########################
# Configure the window. #
#########################
self.setWindowTitle("MODELLER Options")
# Sets the central widget.
self.central_widget = QtWidgets.QWidget()
self.setCentralWidget(self.central_widget)
# The window has a main vbox layout.
self.main_vbox = QtWidgets.QVBoxLayout()
################
# Upper frame. #
################
self.upper_frame_title = QtWidgets.QLabel("Here you can modify options for MODELLER")
self.main_vbox.addWidget(self.upper_frame_title)
#################
# Middle frame. #
#################
# Builds the middle widget, which will contain a Notebook and its tabs.
# This will contain most of the content of the modeling window.
self.middle_widget = QtWidgets.QWidget()
self.main_vbox.addWidget(self.middle_widget)
# Layout of the 'middle_widget'.
self.middle_gridlayout = QtWidgets.QGridLayout()
self.middle_widget.setLayout(self.middle_gridlayout)
# Configure the 'notebook' with its tabs.
self.notebook = QtWidgets.QTabWidget()
# Builds the different Notebook pages.
self.build_main_page()
self.build_disulfides_page()
self.build_options_page()
self.middle_gridlayout.addWidget(self.notebook)
#################
# Bottom frame. #
#################
# This is the "Submit" button on the modellization window.
self.main_button = QtWidgets.QPushButton("Submit")
self.main_button.clicked.connect(lambda a=None: self.protocol.launch_modelization())
self.main_vbox.addWidget(self.main_button)
self.main_button.setFixedWidth(self.main_button.sizeHint().width())
# Sets the main vertical layout.
self.central_widget.setLayout(self.main_vbox)
self.main_vbox.setAlignment(self.main_button, QtCore.Qt.AlignCenter)
###########################################################################
# Main tab (template or loop selection). #
###########################################################################
def build_main_page(self):
"""
Add and configure the 'Main' page and tab fo the modeling window. In the
homology modeling mode, it will contain options for choosing templates
and some restraints option. In the loop refinement mode, it will contain
options for choosing the loop ranges to refine.
"""
# Main page widget.
self.main_page = QtWidgets.QWidget()
self.notebook.addTab(self.main_page, "Main")
# Main page widget layout.
self.main_page_gridlayout = QtWidgets.QGridLayout()
self.main_page.setLayout(self.main_page_gridlayout)
# Scroll area for the main page.
self.main_page_scroll = QtWidgets.QScrollArea()
# Build the main page interior and set properties of the scrollbar.
self.main_page_interior = QtWidgets.QWidget()
self.main_page_scroll.setWidgetResizable(True)
self.main_page_scroll.setWidget(self.main_page_interior)
self.main_page_gridlayout.addWidget(self.main_page_scroll)
# self.main_page_interior_layout = QtWidgets.QVBoxLayout()
self.main_page_interior_layout = QtWidgets.QFormLayout()
self.main_page_interior.setLayout(self.main_page_interior_layout)
self.build_modeling_protocol_main_page()
def build_modeling_protocol_main_page(self):
"""
Starts to insert content in the "Main" page.
"""
# If the user choose to build a multiple chain model, it displays an additional option to
# let the user choose his/her "template complex".
if self.protocol.multiple_chain_mode:
# Add widgets for the "template complex" selection.
self.template_complex_selection_label = QtWidgets.QLabel("Template Complex selection")
self.template_complex_selection_label.setStyleSheet(modeling_window_title_style)
self.main_page_interior_layout.addRow(self.template_complex_selection_label)
# The user can choose the "template complex" with some Radiobuttons.
self.template_complex_rad_group = QtWidgets.QButtonGroup()
# Display some information to explain what is a "template complex".
information = (
"Select the PDB file containing the complex on which you would like to base the building\n"+
"of your multiple chain model. The relative orientation in space and the interfaces of\n"+
"your model's chains will be based on the architecture of the Template Complex.")
# self.template_complex_message = Label(self.template_complex_selection_frame, text=information, **shared_gui_components.modeling_window_explanation)
# self.template_complex_message.grid(row=1, column=0, sticky = "w")
for (tc_i, tc) in enumerate(self.protocol.available_template_complex_list):
tcb = QtWidgets.QRadioButton(self.protocol.all_full_structure_fn_dict[tc])
# tcb.setStyleSheet(shared_gui_components.modeling_window_rb_big)
self.main_page_interior_layout.addRow(tcb)
self.template_complex_rad_group.addButton(tcb)
# Initialize by default with the first PDB in the list.
if tc_i == 0:
tcb.setChecked(True)
# Builds a frame for each modeling_cluster.
for (mc_i, modeling_cluster) in enumerate(self.protocol.modeling_clusters_list):
# Add a spacer to separate the sections for each modeling cluster.
if self.protocol.multiple_chain_mode:
spacer_frame = QtWidgets.QFrame()
spacer_frame.setFrameShape(QtWidgets.QFrame.HLine)
spacer_frame.setFrameShadow(QtWidgets.QFrame.Sunken)
self.main_page_interior_layout.addRow(spacer_frame)
#----------------------------------------------------
# This part should contain also other options like: -
# - secondary structure assignment to the model -
# - others... -
#----------------------------------------------------
show_symmetry_restraints_option = False
modeling_option_label = QtWidgets.QLabel("Modeling options for target: %s" % (modeling_cluster.target_name))
modeling_option_label.setStyleSheet(modeling_window_title_style)
self.main_page_interior_layout.addRow(modeling_option_label)
# Multiple chain options.
if self.protocol.multiple_chain_mode:
# Use symmetry restraints option.
if modeling_cluster.symmetry_restraints_id != None:
show_symmetry_restraints_option = True
symmetry_checkbox, symmetry_info = self.build_symmetry_restraints_option(modeling_cluster)
if any((show_symmetry_restraints_option, )): # This might include other flags in future releases.
additional_options_label = QtWidgets.QLabel("Restraints options")
additional_options_label.setStyleSheet(modeling_options_sections_style)
self.main_page_interior_layout.addRow(additional_options_label)
if show_symmetry_restraints_option:
self.main_page_interior_layout.addRow(symmetry_checkbox, symmetry_info)
#-------------------------------------------------------------------
# Builds a frame for each structure aligned to the target sequence -
# of the current modeling cluster. -
#-------------------------------------------------------------------
modeling_option_label = QtWidgets.QLabel("Template selection")
modeling_option_label.setStyleSheet(modeling_options_sections_style)
self.main_page_interior_layout.addRow(modeling_option_label)
# Builds a frame for selecting all templates.
if len(modeling_cluster.suitable_templates_list) > 1:
control_all_templates_frame = QtWidgets.QFrame()
control_all_templates_frame_layout = QtWidgets.QFormLayout()
control_all_templates_frame.setLayout(control_all_templates_frame_layout)
control_all_templates_label = QtWidgets.QLabel("Quick template selection")
control_all_templates_label.setStyleSheet(modeling_options_subsections_style)
control_all_templates_frame_layout.addRow(control_all_templates_label)
select_all_templates_button = QtWidgets.QPushButton("Select all templates")
select_all_templates_button.setStyleSheet(small_font_style)
select_all_templates_button.setFixedWidth(select_all_templates_button.sizeHint().width()+20)
select_all_templates_button.clicked.connect(lambda a=None, i=mc_i: self.select_all_templates(i))
select_no_templates_button = QtWidgets.QPushButton("Deselect all templates")
select_no_templates_button.setStyleSheet(small_font_style)
select_no_templates_button.setFixedWidth(select_no_templates_button.sizeHint().width()+20)
select_no_templates_button.clicked.connect(lambda a=None, i=mc_i: self.deselect_all_templates(i))
control_all_templates_frame_layout.addRow(select_all_templates_button, select_no_templates_button)
self.main_page_interior_layout.addRow(control_all_templates_frame)
control_all_templates_frame_layout.setAlignment(QtCore.Qt.AlignLeft)
control_all_templates_frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
# Builds a frame for each template structure.
modeling_cluster.structure_frame_list = []
for (si, structure) in enumerate(modeling_cluster.suitable_templates_list):
# This object is a PyQt one, and contains many other PyQt widgets.
structure_frame = Structure_frame_qt(parent=None,
parent_window=self,
template_element=structure, # target_element=modeling_cluster.target
template_idx=si,
modeling_cluster=modeling_cluster,
modeling_cluster_idx=mc_i)
self.main_page_interior_layout.addRow(structure_frame)
# Append the current "structure_frame" to the list of the current modeling cluster.
# Storing this object will also store the value of each Checkbox, Radiobutton and
# entry found inside it.
modeling_cluster.structure_frame_list.append(structure_frame)
def build_symmetry_restraints_option(self, modeling_cluster):
symmetry_checkbox = QtWidgets.QCheckBox("Use symmetry restraints for this chain")
symmetry_checkbox.setStyleSheet(small_font_style)
symmetry_information = "Show Info"
symmetry_info = QtWidgets.QPushButton(symmetry_information)
symmetry_info.setStyleSheet(small_font_style)
symmetry_info.clicked.connect(lambda a=None, mc=modeling_cluster: self.show_symmetry_info(modeling_cluster))
symmetry_info.setFixedWidth(symmetry_info.sizeHint().width()+20)
# Store this widget for this modeling cluster, so that its value may be
# retrieved later.
modeling_cluster.restraints_options_dict["symmetry"] = symmetry_checkbox
return symmetry_checkbox, symmetry_info
def select_all_templates(self, mc_i):
modeling_cluster = self.protocol.modeling_clusters_list[mc_i]
for structure_frame in modeling_cluster.structure_frame_list:
structure_frame.template_checkbox.setChecked(True)
structure_frame.click_on_structure_checkbutton()
def deselect_all_templates(self, mc_i):
modeling_cluster = self.protocol.modeling_clusters_list[mc_i]
for structure_frame in modeling_cluster.structure_frame_list:
structure_frame.template_checkbox.setChecked(False)
structure_frame.click_on_structure_checkbutton()
def switch_all_hetres_checkbutton_states(self, het_radio_button_state):
"""
Launched when the user activates/inactivates the "Include HetAtoms" in the Options page in
the modeling window.
"""
for mc in self.protocol.modeling_clusters_list:
self.switch_hetres_checkbutton_states(mc, het_radio_button_state)
def switch_hetres_checkbutton_states(self, modeling_cluster, het_radio_button_state):
for sf in modeling_cluster.structure_frame_list:
# Activate.
if het_radio_button_state == 1:
sf.hetres_radiocluster_button_state = 1
sf.activate_water_checkbutton()
if sf.number_of_hetres > 0:
sf.activate_het_checkbuttons()
# Inactivate.
elif het_radio_button_state == 0:
sf.hetres_radiocluster_button_state = 0
sf.inactivate_water_checkbutton()
if sf.number_of_hetres > 0:
sf.inactivate_het_checkbuttons()
else:
raise KeyError("Unknown 'het_radio_button_state': %s" % het_radio_button_state)
def show_symmetry_info(self, modeling_cluster):
"""
Displays informations about which target sequence shares the same sequence of other targets.
"""
mc_list = self.protocol.symmetry_restraints_groups.get_group_by_id(modeling_cluster.symmetry_restraints_id).list_of_clusters
mc_list = [x for x in mc_list if not x is modeling_cluster]
message1 = "The target '%s' shares the same sequence with these other targets:" % (modeling_cluster.target_name)
seqs = "\n".join([mc.target_name for mc in mc_list])
message2 = "so you may apply symmetry restraints for them."
message = message1 + "\n\n" + seqs + "\n\n" + message2
self.protocol.pymod.main_window.show_warning_message("Symmetry restraints information",
message)
def get_template_complex_var(self):
sel_id = None
for rb_idx, rb in enumerate(self.template_complex_rad_group.buttons()):
if rb.isChecked():
sel_id = rb_idx
break
if sel_id is None:
raise ValueError("No template complex was selected.")
print(sel_id)
return sel_id
###########################################################################
# Disulfides tab. #
###########################################################################
def build_disulfides_page(self):
"""
Add the "Disulfides" page to the modeling window notebook.
"""
#----------------------------------
# Configures the the "Disulfides" page. -
#----------------------------------
# Disulfides page widget.
self.disulfides_page = QtWidgets.QWidget()
self.notebook.addTab(self.disulfides_page, "Disulfides")
# Disulfides page widget layout.
self.disulfides_page_gridlayout = QtWidgets.QGridLayout()
self.disulfides_page.setLayout(self.disulfides_page_gridlayout)
# Scroll area for the disulfides page.
self.disulfides_page_scroll = QtWidgets.QScrollArea()
# Build the main page interior and set properties of the scrollbar.
self.disulfides_page_interior = QtWidgets.QWidget()
self.disulfides_page_scroll.setWidgetResizable(True)
self.disulfides_page_scroll.setWidget(self.disulfides_page_interior)
self.disulfides_page_gridlayout.addWidget(self.disulfides_page_scroll)
# self.disulfides_page_interior_layout = QtWidgets.QVBoxLayout()
self.disulfides_page_interior_layout = QtWidgets.QFormLayout()
self.disulfides_page_interior.setLayout(self.disulfides_page_interior_layout)
#-------------------------------------------
# Build widgets for the "Disulfides" page. -
#-------------------------------------------
# If at least one cluster has a target with at least two CYS residues, then build the
# disulfide page with all its options.
if self.protocol.check_targets_with_cys():
# Use template disulfides.
if self.protocol.modeling_mode == "homology_modeling":
self.build_template_dsb_frame()
# User defined dsb. Each target is going to have a frame to define additional dsb.
self.build_user_defined_dsb_frame()
# Automatically build disulfides.
if self.protocol.modeling_mode == "homology_modeling":
self.build_auto_dsb_frame()
else:
self.build_no_dsb_frame()
def build_template_dsb_frame(self):
"""
Builds the top frame, for the templates disulfides.
"""
self.templates_dsb_label = QtWidgets.QLabel("Use template disulfides")
self.templates_dsb_label.setStyleSheet(modeling_options_sections_style)
self.disulfides_page_interior_layout.addRow(self.templates_dsb_label)
# If there are some templates with disulfide bridges.
if self.protocol.check_structures_with_disulfides():
# Label for the information about the use of this feature.
information = "Include disulfide bridges from the templates selected in the 'Main' page."
self.template_disulfides_information = QtWidgets.QLabel(information)
self.template_disulfides_information.setStyleSheet(small_font_style)
self.disulfides_page_interior_layout.addRow(self.template_disulfides_information)
# Initialize the radiobutton: if the are some structures with disulfides use this option
# by default.
self.use_template_dsb_rad_group = QtWidgets.QButtonGroup()
self.use_template_dsb_rad1 = QtWidgets.QRadioButton("Yes")
self.use_template_dsb_rad1.setChecked(True)
# self.use_template_dsb_rad1.setStyleSheet(modeling_window_rb_big)
self.use_template_dsb_rad1.clicked.connect(self.activate_template_dsb_frame)
self.use_template_dsb_rad_group.addButton(self.use_template_dsb_rad1)
self.use_template_dsb_rad2 = QtWidgets.QRadioButton("No")
# self.use_template_dsb_rad2.setStyleSheet(modeling_window_rb_big)
self.use_template_dsb_rad2.clicked.connect(self.inactivate_template_dsb_frame)
self.use_template_dsb_rad_group.addButton(self.use_template_dsb_rad2)
self.disulfides_page_interior_layout.addRow(self.use_template_dsb_rad1, self.use_template_dsb_rad2)
# Button for displaying the list of disulfide bridges found in the templates.
toggle_template_dsb_text = "List of templates' disulfides (white: conserved in target, gray: not conserved):"
# self.toggle_template_frame = QtWidgets.QHBoxLayout()
# self.toggle_template_dsb_label = QtWidgets.QLabel(toggle_template_dsb_text)
# self.toggle_template_frame.addWidget(self.toggle_template_dsb_label)
self.toggle_template_dsb_button = QtWidgets.QPushButton("Show template disulfides")
self.toggle_template_dsb_button.setStyleSheet(small_font_style)
self.toggle_template_dsb_button.clicked.connect(self.toggle_template_dsb)
self.disulfides_page_interior_layout.addRow(self.toggle_template_dsb_button)
self.toggle_template_dsb_button.setFixedWidth(self.toggle_template_dsb_button.sizeHint().width()+30)
self.template_dsb_show_state = False
# Build a frame with the list of all template disulfides (for each target).
self.build_templates_disulfides_frame()
# If there aren't templates with disulfide bridges.
else:
# Label for the information about the use of this feature.
information = "There aren't any templates with disulfide bridges."
self.template_disulfides_information = QtWidgets.QLabel(information)
self.template_disulfides_information.setStyleSheet(small_font_style)
self.disulfides_page_interior_layout.addRow(self.template_disulfides_information)
def activate_template_dsb_frame(self):
"""
Called when the "Yes" radiobutton of the "Use template disulfide" option is pressed.
"""
self.toggle_template_dsb_button.show()
def inactivate_template_dsb_frame(self):
"""
Called when the "No" radiobutton of the "Use template disulfide" option is pressed.
This is also called when the "Yes" radiobutton of the "Automatically build disulfides" is
pressed.
"""
self.toggle_template_dsb_button.hide()
self._hide_template_dsb()
def toggle_template_dsb(self):
"""
Called when the "Show" button is pressed to show the list of the dsb of the templates.
"""
if not self.template_dsb_show_state:
self._show_template_dsb()
else:
self._hide_template_dsb()
def _show_template_dsb(self):
self.template_disulfides_frame.show()
self.toggle_template_dsb_button.setText("Hide template disulfides")
self.template_dsb_show_state = True
def _hide_template_dsb(self):
self.template_disulfides_frame.hide()
self.toggle_template_dsb_button.setText("Show template disulfides")
self.template_dsb_show_state = False
def build_templates_disulfides_frame(self):
"""
Builds the frame for displaying disulfide bridges found in the templates.
"""
# Frame for template disulfides and its layout.
self.template_disulfides_frame = QtWidgets.QFrame()
# self.template_disulfides_frame.setStyleSheet(background='black', bd=1, relief = GROOVE, padx = 15, pady = 10)
self.disulfides_page_interior_layout.addRow(self.template_disulfides_frame)
self.template_disulfides_frame_layout = QtWidgets.QGridLayout()
self.template_disulfides_frame.setLayout(self.template_disulfides_frame_layout)
self.template_disulfides_frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
# Show information for every modeling cluster which have templates with disulfides.
row_counter = 0
for mci, mc in enumerate([mc for mc in self.protocol.modeling_clusters_list if mc.has_structures_with_disulfides()]):
target_label = QtWidgets.QLabel("Template disulfides for target: " + mc.target_name)
target_label.setStyleSheet(small_font_style + "; color: %s" % highlight_color)
self.template_disulfides_frame_layout.addWidget(target_label, row_counter, 0, 1, 2)
row_counter += 1
# Iterate through all the templates for this target.
for ei, element in enumerate([x for x in mc.suitable_templates_list if x.has_disulfides()]):
# Label with the name of the template.
disulfides_label = QtWidgets.QLabel("Template "+ element.my_header + " ")
disulfides_label.setStyleSheet(modeling_options_subsections_style)
self.template_disulfides_frame_layout.addWidget(disulfides_label, row_counter, 0)
tar_disulfides_label = QtWidgets.QLabel("Corresponding target residues")
tar_disulfides_label.setStyleSheet(modeling_options_subsections_style)
self.template_disulfides_frame_layout.addWidget(tar_disulfides_label, row_counter, 1)
row_counter += 1
# Begins a for cycle that is going to examine all disulfides bridges of the chain.
for dsb in element.get_disulfides():
# For now, display only intrachain bridges.
if dsb.type == "intrachain":
# Check if there are homologous CYS in the target according to the alignment.
# Take the target sequence.
target = mc.target.my_sequence
# CYS 1.
cys1_alignment_position = pmsm.get_residue_id_in_aligned_sequence(element.my_sequence, dsb.cys1_seq_index)
cys1_target_id = pmsm.get_residue_id_in_gapless_sequence(target, cys1_alignment_position)
if cys1_target_id is not None:
cys1_target_position = cys1_target_id + 1
cys1_is_conserved = pmsm.find_residue_conservation(element.my_sequence, target, dsb.cys1_seq_index)
cys1_homolog_residue = target[cys1_alignment_position] # The corresponding residue in the target.
else:
cys1_target_position = ""
cys1_is_conserved = False
cys1_homolog_residue = "gap"
# CYS 2.
cys2_alignment_position = pmsm.get_residue_id_in_aligned_sequence(element.my_sequence, dsb.cys2_seq_index)
cys2_target_id = pmsm.get_residue_id_in_gapless_sequence(target, cys2_alignment_position)
if cys2_target_id is not None:
cys2_target_position = cys2_target_id + 1
cys2_is_conserved = pmsm.find_residue_conservation(element.my_sequence, target, dsb.cys2_seq_index)
cys2_homolog_residue = target[cys2_alignment_position] # The corresponding residue in the target.
else:
cys2_target_position = ""
cys2_is_conserved = False
cys2_homolog_residue = "gap"
tem_label_text = "C%s - C%s" % (dsb.cys1_pdb_index, dsb.cys2_pdb_index)
# If both CYS that form the disulfide in the template are conserved in the target.
if cys1_is_conserved and cys2_is_conserved:
# Prints also if the CYS are conserved in the target according to the
# alignment.
tar_label_text = "C%s - C%s" % (cys1_target_position, cys2_target_position)
# tar_label_text += " (conserved)"
text_color = ""
else:
tar_label_text = "%s%s - %s%s" % (cys1_homolog_residue, cys1_target_position, cys2_homolog_residue, cys2_target_position)
# label_text += " (not conserved)"
text_color = "; color: %s" % modeling_options_inactive_label_color
# Labels for a single template disulfide bridge.
tem_disulfide_label = QtWidgets.QLabel(tem_label_text)
tem_disulfide_label.setStyleSheet(small_font_style)
self.template_disulfides_frame_layout.addWidget(tem_disulfide_label, row_counter, 0)
tar_disulfide_label = QtWidgets.QLabel(tar_label_text)
tar_disulfide_label.setStyleSheet(small_font_style + text_color)
self.template_disulfides_frame_layout.addWidget(tar_disulfide_label, row_counter, 1)
row_counter += 1
# Align to the left the widgets inside the frame.
self.template_disulfides_frame_layout.setAlignment(QtCore.Qt.AlignLeft)
# Don't show the frame initially.
self.template_disulfides_frame.hide()
def build_user_defined_dsb_frame(self):
"""
Builds the bottom frame, for the user-defined disulfides.
"""
# Main label for this feature.
self.user_dsb_label = QtWidgets.QLabel("Create new disulfides")
self.user_dsb_label.setStyleSheet(modeling_options_sections_style)
self.disulfides_page_interior_layout.addRow(self.user_dsb_label)
# Label for the information about the use of this feature.
information = "Define custom disulfide bridges to be included in the model. "
# information += ("NOTE: if the S atoms of\n" +
# "the two cysteines you selected are going to be located more than 2.5A apart in the\n" +
# "model, MODELLER will not build the bridge." )
self.user_disulfides_information = QtWidgets.QLabel(information)
self.user_disulfides_information.setStyleSheet(small_font_style)
self.disulfides_page_interior_layout.addRow(self.user_disulfides_information)
# Radiobuttons.
self.use_user_defined_dsb_rad_group = QtWidgets.QButtonGroup()
self.use_user_defined_dsb_rad1 = QtWidgets.QRadioButton("Yes")
# self.use_user_defined_dsb_rad1.setStyleSheet(modeling_window_rb_big)
self.use_user_defined_dsb_rad1.clicked.connect(self.activate_combo_box_frame)
self.use_user_defined_dsb_rad_group.addButton(self.use_user_defined_dsb_rad1)
self.use_user_defined_dsb_rad2 = QtWidgets.QRadioButton("No")
self.use_user_defined_dsb_rad2.setChecked(True)
# self.use_user_defined_dsb_rad2.setStyleSheet(modeling_window_rb_big)
self.use_user_defined_dsb_rad2.clicked.connect(self.inactivate_combo_box_frame)
self.use_user_defined_dsb_rad_group.addButton(self.use_user_defined_dsb_rad2)
self.disulfides_page_interior_layout.addRow(self.use_user_defined_dsb_rad1, self.use_user_defined_dsb_rad2)
# Frame where comboboxes and buttons for user defined disulfides are going to be placed.
# This is going to be gridded by the "activate_combo_box_frame()" method below.
self.user_defined_dsb_input_frame = QtWidgets.QFrame()
# self.user_defined_dsb_input_frame.setStyleSheet(background='black',pady = 5)
self.user_defined_dsb_input_frame_layout = QtWidgets.QFormLayout()
self.user_defined_dsb_input_frame.setLayout(self.user_defined_dsb_input_frame_layout)
self.disulfides_page_interior_layout.addRow(self.user_defined_dsb_input_frame)
# This will contain a list of User_dsb_selector objects that will store the information
# about user defined dsb.
self.user_dsb_selector_list = []
# Builds a frame where are going to be gridded a series of frames (one for each
# modeling cluster) in order to let the user define additional disulfide bridges
# for each target.
for (mci, mc) in enumerate(self.protocol.modeling_clusters_list):
uds = User_dsb_selector_frame_qt(parent=None, parent_window=self,
modeling_cluster=mc)
self.user_dsb_selector_list.append(uds)
self.user_defined_dsb_input_frame_layout.addRow(uds)
self.user_defined_dsb_input_frame.hide()
def activate_combo_box_frame(self):
self.user_defined_dsb_input_frame.show()
def inactivate_combo_box_frame(self):
self.user_defined_dsb_input_frame.hide()
def build_auto_dsb_frame(self):
"""
Builds a frame to display the option to make Modeller automatically create all dsb of the
model.
"""
# Main label for this feature.
self.auto_dsb_label = QtWidgets.QLabel("Automatically build disulfides")
self.auto_dsb_label.setStyleSheet(modeling_options_sections_style)
self.disulfides_page_interior_layout.addRow(self.auto_dsb_label)
# Label for the information about the use of this feature.
information = ("MODELLER will build a disulfide for every pair of cysteines if they are\n"
"sufficently close in the model. ")
# information += "NOTE: by using this option you will not be able to use the two options above."
self.auto_disulfides_information = QtWidgets.QLabel(information)
self.auto_disulfides_information.setStyleSheet(small_font_style)
self.disulfides_page_interior_layout.addRow(self.auto_disulfides_information)
# Radiobuttons.
self.auto_dsb_rad_group = QtWidgets.QButtonGroup()
self.auto_dsb_rad1 = QtWidgets.QRadioButton("Yes")
# self.auto_dsb_rad1.setStyleSheet(modeling_window_rb_big)
self.auto_dsb_rad1.clicked.connect(self.activate_auto_dsb)
self.auto_dsb_rad_group.addButton(self.auto_dsb_rad1)
self.auto_dsb_rad2 = QtWidgets.QRadioButton("No")
self.auto_dsb_rad2.setChecked(True)
# self.auto_dsb_rad2.setStyleSheet(modeling_window_rb_big)
self.auto_dsb_rad2.clicked.connect(self.inactivate_auto_dsb)
self.auto_dsb_rad_group.addButton(self.auto_dsb_rad2)
self.disulfides_page_interior_layout.addRow(self.auto_dsb_rad1, self.auto_dsb_rad2)
def activate_auto_dsb(self):
# Inactivates the "use template dsb" radiobuttons and selects the "No" radiobutton.
if self.protocol.check_structures_with_disulfides():
self.use_template_dsb_rad2.setChecked(True)
self.use_template_dsb_rad1.setEnabled(False)
self.use_template_dsb_rad2.setEnabled(False)
self.inactivate_template_dsb_frame()
# Inactivates the "create new dsb" radiobuttons and selects the "No" radiobutton.
self.use_user_defined_dsb_rad2.setChecked(True)
self.use_user_defined_dsb_rad1.setEnabled(False)
self.use_user_defined_dsb_rad2.setEnabled(False)
self.user_defined_dsb_input_frame.hide()
def inactivate_auto_dsb(self):
# Reactivates the "use template dsb" and the "create new dsb" radiobuttons.
if self.protocol.check_structures_with_disulfides():
self.use_template_dsb_rad1.setEnabled(True)
self.use_template_dsb_rad2.setEnabled(True)
self.use_user_defined_dsb_rad1.setEnabled(True)
self.use_user_defined_dsb_rad2.setEnabled(True)
def build_no_dsb_frame(self):
"""
Builds a frame that is displayed if the target sequence has less than 2 cys.
"""
self.no_dsb_label = QtWidgets.QLabel("No disulfide bridge can be built.")
self.no_dsb_label.setStyleSheet(modeling_options_sections_style)
self.disulfides_page_interior_layout.addRow(self.no_dsb_label)
information = "No target has at least two CYS residues needed to form a bridge."
self.no_disulfides_information = QtWidgets.QLabel(information)
self.no_disulfides_information.setStyleSheet(small_font_style)
self.disulfides_page_interior_layout.addRow(self.no_disulfides_information)
def get_use_template_dsb_var(self):
if self.protocol.check_targets_with_cys():
if self.protocol.check_structures_with_disulfides():
if self.use_template_dsb_rad1.isChecked():
return 1
elif self.use_template_dsb_rad2.isChecked():
return 0
else:
raise ValueError("No template disulfide option was selected.")
else:
return 0
else:
return 0
def get_use_user_defined_dsb_var(self):
if self.protocol.check_targets_with_cys():
if self.use_user_defined_dsb_rad1.isChecked():
return 1
elif self.use_user_defined_dsb_rad2.isChecked():
return 0
else:
raise ValueError("No custom disulfide option was selected.")
else:
return 0
def get_user_dsb_list(self):
"""
If some user-defined disulfide bridges have been built, get that information from GUI.
"""
return [sel.user_defined_disulfide_bridges for sel in self.user_dsb_selector_list]
def get_auto_dsb_var(self):
if self.protocol.check_targets_with_cys():
if self.auto_dsb_rad1.isChecked():
return 1
elif self.auto_dsb_rad2.isChecked():
return 0
else:
raise ValueError("No auto disulfide option was selected.")
else:
return 0
###########################################################################
# Options tab. #
###########################################################################
def build_options_page(self):
"""
Add the "Options" page on modeling window notebook.
"""
#----------------------------------
# Configures the the "Options" page. -
#----------------------------------
# Options page widget.
self.options_page = QtWidgets.QWidget()
self.notebook.addTab(self.options_page, "Options")
# Options page widget layout.
self.options_page_gridlayout = QtWidgets.QGridLayout()
self.options_page.setLayout(self.options_page_gridlayout)
# Scroll area for the options page.
self.options_page_scroll = QtWidgets.QScrollArea()
# Build the options page interior and set properties of the scrollbar.
self.options_page_interior = QtWidgets.QWidget()
self.options_page_scroll.setWidgetResizable(True)
self.options_page_scroll.setWidget(self.options_page_interior)
self.options_page_gridlayout.addWidget(self.options_page_scroll)
self.options_page_interior_layout = PyMod_QFormLayout()
self.options_page_interior.setLayout(self.options_page_interior_layout)
#--------------------------------------------
# Start to insert modeling options widgets. -
#--------------------------------------------
# Option to choose the number of models that Modeller has to produce.
if self.protocol.modeling_mode == "homology_modeling":
n_mod_default = 1
else:
n_mod_default = 10
self.max_models_enf = PyMod_entryfield_qt(label_text="Models to Build",
value=str(n_mod_default),
validate={'validator': 'integer',
'min': 1,
'max': self.protocol.max_models_per_session})
self.options_page_interior_layout.add_widget_to_align(self.max_models_enf)
# Option to choose if Modeller is going to include HETATMs.
if self.protocol.modeling_mode == "homology_modeling":
self.exclude_heteroatoms_rds = PyMod_radioselect_qt(label_text='Exclude Heteroatoms',
buttons=("Yes", "No"))
self.exclude_heteroatoms_rds.setvalue("No")
self.options_page_interior_layout.add_widget_to_align(self.exclude_heteroatoms_rds)
self.exclude_heteroatoms_rds.get_button_at(0).clicked.connect(lambda a=None: self.switch_all_hetres_checkbutton_states(0)) # Yes, inactivate.
self.exclude_heteroatoms_rds.get_button_at(1).clicked.connect(lambda a=None: self.switch_all_hetres_checkbutton_states(1)) # No, activate.
elif self.protocol.modeling_mode == "loop_refinement":
self.exclude_heteroatoms_rds = PyMod_radioselect_qt(label_text='Include Heteroatoms',
buttons=("Het + Water", "Het", "No"))
self.exclude_heteroatoms_rds.setvalue("No")
self.options_page_interior_layout.add_widget_to_align(self.exclude_heteroatoms_rds)
# Option to choose the level of optimization for Modeller.
self.optimization_level_rds = PyMod_radioselect_qt(label_text='Optimization Level',
buttons=self.optimization_level_choices)
self.optimization_level_rds.setvalue("Default")
self.options_page_interior_layout.add_widget_to_align(self.optimization_level_rds)
for button_i in range(0, 5):
button = self.optimization_level_rds.get_button_at(button_i)
button.clicked.connect(self.hide_optimization_level_frame)
self.optimization_level_rds.get_button_at(5).clicked.connect(self.show_optimization_level_frame)
optimization_level_frame_class = self.get_optimization_level_class()
self.optimization_level_frame = optimization_level_frame_class()
self.options_page_interior_layout.addRow(self.optimization_level_frame)
self.optimization_level_frame.hide()
# Option to customize the MODELLER objective function.
self.obj_func_choices = ("Default", "altMOD (v0.2)", "Customize")
self.obj_func_choices_vals = ("default", "altmod", "customize")
self.obj_func_choices_dict = dict([(k, v) for (k, v) in zip(self.obj_func_choices, self.obj_func_choices_vals)])
if self.protocol.modeling_mode == "homology_modeling":
custom_obj_func_label = 'Objective Function'
available_obj_func_choices = self.obj_func_choices
default_obj_func_choice = self.obj_func_choices[0]
elif self.protocol.modeling_mode == "loop_refinement":
custom_obj_func_label = "Customize Objective Function"
available_obj_func_choices = ("Yes", "No")
default_obj_func_choice = "No"
self.custom_obj_func_rds = PyMod_radioselect_qt(label_text=custom_obj_func_label,
buttons=available_obj_func_choices)
self.custom_obj_func_rds.setvalue(default_obj_func_choice)
self.options_page_interior_layout.add_widget_to_align(self.custom_obj_func_rds)
if self.protocol.modeling_mode == "homology_modeling":
self.custom_obj_func_rds.get_button_at(0).clicked.connect(self.hide_custom_obj_func_frame)
self.custom_obj_func_rds.get_button_at(1).clicked.connect(self.hide_custom_obj_func_frame)
self.custom_obj_func_rds.get_button_at(2).clicked.connect(self.show_custom_obj_func_frame)
elif self.protocol.modeling_mode == "loop_refinement":
self.custom_obj_func_rds.get_button_at(0).clicked.connect(self.show_custom_obj_func_frame)
self.custom_obj_func_rds.get_button_at(1).clicked.connect(self.hide_custom_obj_func_frame)
custom_obj_func_frame_class = self.get_custom_obj_func_frame_class()
self.custom_obj_func_frame = custom_obj_func_frame_class()
self.options_page_interior_layout.addRow(self.custom_obj_func_frame)
self.custom_obj_func_frame.hide()
# Option to choose the way to color the models.
self.color_models_choices = ("Default", "DOPE Score")
self.color_models_rds = PyMod_radioselect_qt(label_text='Color models by',
buttons=self.color_models_choices)
self.color_models_rds.setvalue("Default")
self.options_page_interior_layout.add_widget_to_align(self.color_models_rds)
# Option to choose whether to super models to template.
if self.protocol.modeling_mode == "homology_modeling":
self.superpose_models_to_templates_rds = PyMod_radioselect_qt(label_text='Superpose Models to Templates',
buttons=("Yes", "No"))
self.superpose_models_to_templates_rds.setvalue("Yes")
self.options_page_interior_layout.add_widget_to_align(self.superpose_models_to_templates_rds)
# Option to choose which should be the initial conformation of loops.
if self.protocol.modeling_mode == "loop_refinement":
self.loop_initial_conformation_rds = PyMod_radioselect_qt(label_text='Initial Conformation for Loops',
buttons=("Linearized", "Original"))
self.loop_initial_conformation_rds.setvalue("Linearized")
self.options_page_interior_layout.add_widget_to_align(self.loop_initial_conformation_rds)
# Option to choose the random seed of MODELLER.
self.random_seed_enf = PyMod_entryfield_qt(label_text="Random Seed (from -50000 to -2)",
value=str(self.protocol.default_modeller_random_seed),
validate={'validator': 'integer',
'min': self.protocol.min_modeller_random_seed,
'max': self.protocol.max_modeller_random_seed})
self.options_page_interior_layout.add_widget_to_align(self.random_seed_enf)
# Option to choose the number of parallel jobs to be used for MODELLER. When using a
# MODELLER installed in the PyMod conda directory, subprocesses with MODELLER (and thus
# parallele jobs) can not be used.
max_n_jobs = multiprocessing.cpu_count()
self.n_jobs_enf = PyMod_spinbox_entry_qt(label_text="N. of Parallel Jobs",
value=1,
# validate={'validator': 'integer', 'min': 1, 'max': max_n_jobs},
spinbox_min=1, spinbox_max=max_n_jobs
)
self.options_page_interior_layout.add_widget_to_align(self.n_jobs_enf)
self.options_page_interior_layout.set_input_widgets_width("auto", padding=20)
def show_optimization_level_frame(self):
self.optimization_level_frame.show()
def hide_optimization_level_frame(self):
self.optimization_level_frame.hide()
def get_optimization_level_class(self):
return Optimization_level_frame_qt
def hide_custom_obj_func_frame(self):
self.custom_obj_func_frame.hide()
def show_custom_obj_func_frame(self):
self.custom_obj_func_frame.show()
def get_custom_obj_func_frame_class(self):
return Custom_obj_func_frame_qt
def get_custom_obj_func_option(self):
if self.protocol.modeling_mode == "homology_modeling":
return self.obj_func_choices_dict[self.custom_obj_func_rds.getvalue()]
elif self.protocol.modeling_mode == "loop_refinement":
input_val = self.custom_obj_func_rds.getvalue()
if input_val == "Yes":
return self.obj_func_choices_vals[2]
elif input_val == "No":
return self.obj_func_choices_vals[0]
###################################################################################################
# Other classes for the homology modeling window GUI. #
###################################################################################################
#####################################################################
# Template selection window classes. #
#####################################################################
class Structure_frame_qt(QtWidgets.QFrame):
"""
A class to construct the template selection frame and to store all their Qt widgets and
information.
"""
labels_width = 16
# template_options_style = shared_gui_components.modeling_window_option_style.copy()
# template_options_style.update({"width": labels_width})
frames_padding = 7
def __init__(self, parent, parent_window,
template_element, template_idx,
modeling_cluster, modeling_cluster_idx,
*args, **configs):
super(Structure_frame_qt, self).__init__(parent, *args, **configs)
self.parent_window = parent_window
# Modeling cluster.
self.modeling_cluster = modeling_cluster
# This is the id of the modeling cluster containing a structure frame.
self.mc_id = modeling_cluster_idx
# These will contain a 'PyMod_sequence_element' type object.
self.template_element = template_element # self.structure_pymod_element
self.target_element = self.modeling_cluster.target
# self.target_pymod_element = target_pymod_element
# The int value that is passed in the for cycle in which the Structure_frame_qt objects are
# constructed. Identifies different Structure_frame_qt objects.
self.template_idx = template_idx # self.id
# This is needed to check what is the state of radiobutton for using hetres. If it is on,
# then this value should be 1 (by default it is 1 because of the default state of the
# radiobutton), when it is off, this vaule should be 0.
self.hetres_radiocluster_button_state = 1
# Sets the layout of the frame.
self.structure_frame_layout = QtWidgets.QGridLayout()
self.setLayout(self.structure_frame_layout)
self.tot_rows = 0
# Builds a frame for each template structure and all its options.
self.build_use_structure_frame()
# self.build_sequence_limit_frame()
self.build_hetres_frame()
self.build_water_frame()
self.structure_frame_layout.setAlignment(QtCore.Qt.AlignLeft)
self.setFrameShape(QtWidgets.QFrame.StyledPanel)
def build_use_structure_frame(self):
"""
Builds a Frame which will contain the the checkbox for using the structure as a template.
"""
# Initial label for the template.
template_name = self.template_element.my_header[0:-8]
# Avoids some problems templates with very long names.
# For really long names it will print something like: sp_P62987...Chain:A
if len(template_name) < 10:
template_name = self.template_element.my_header
else:
template_name = self.template_element.my_header[0:10] + "..." + self.template_element.my_header[-7:]
self.template_title_lab = QtWidgets.QLabel("Options for template: " + template_name)
self.template_title_lab.setStyleSheet(modeling_options_subsections_style)
self.structure_frame_layout.addWidget(self.template_title_lab, self.tot_rows, 0, 1, 2)
self.tot_rows += 1
# Label and checkbox for selecting a template.
self.template_label = QtWidgets.QLabel("Use as Template: ")
self.template_label.setStyleSheet(small_font_style)
# Shows the identity % between the two aligned sequences.
identity = pmsm.compute_sequence_identity(self.target_element.my_sequence, self.template_element.my_sequence)
# Checkbox for using the structure as a template.
checkbox_text = template_name + " (id: " + str(identity) + "%)"
self.template_checkbox = QtWidgets.QCheckBox(checkbox_text)
self.template_checkbox.setStyleSheet(small_font_style)
self.template_checkbox.clicked.connect(self.click_on_structure_checkbutton)
self.structure_frame_layout.addWidget(self.template_label, self.tot_rows, 0)
self.structure_frame_layout.addWidget(self.template_checkbox, self.tot_rows, 1)
self.tot_rows += 1
def click_on_structure_checkbutton(self):
"""
This is called when the checkbutton to use the structure as a template is pressed. If users
want to use hetero-atoms this method will activate the hetres and water checkbuttons, that
by default are disabled.
"""
# This is under the influence of the state of the "use hetatm" radiobutton in the
# options page.
if self.hetres_radiocluster_button_state == 1:
# The template is "activated", and so also its checkbuttons are.
if self.get_use_as_template_var():
self.activate_water_checkbutton()
if self.number_of_hetres > 0:
self.activate_het_checkbuttons()
# The template is "inactivated", also its checkbuttons are.
else:
self.inactivate_water_checkbutton()
if self.number_of_hetres > 0:
self.inactivate_het_checkbuttons()
def get_use_as_template_var(self):
return self.template_checkbox.isChecked()
def inactivate_het_checkbuttons(self):
"""
This is launched when the hetres radiobutton state is changed to "NO".
"""
self.use_all_hetres.setEnabled(False)
self.select_single_hetres.setEnabled(False)
self.do_not_use_hetres.setEnabled(False)
for c in self.structure_hetres_checkbuttons:
c.setEnabled(False)
def activate_het_checkbuttons(self):
"""
This is launched when the hetres radiobutton state is changed to "YES".
"""
if self.get_use_as_template_var():
self.use_all_hetres.setEnabled(True)
self.select_single_hetres.setEnabled(True)
self.do_not_use_hetres.setEnabled(True)
for c in self.structure_hetres_checkbuttons:
c.setEnabled(True)
def activate_water_checkbutton(self):
if self.template_element.has_waters():
if self.get_use_as_template_var():
self.water_checkbox.setEnabled(True)
def inactivate_water_checkbutton(self):
if self.template_element.has_waters():
self.water_checkbox.setEnabled(False)
def build_sequence_limit_frame(self):
"""
Frame for the sequence limits.
"""
pass
def build_hetres_frame(self):
"""
Builds a frame for the Hetero-residues selection.
"""
# This is going to contain the checkbox states of the HETRES of the structure.
self.hetres_options_var = 0
# self.structure_hetres_states = []
self.structure_hetres_checkbuttons = []
self.structure_hetres_dict = {}
# Label.
self.hetres_label = QtWidgets.QLabel("Hetero Residues: ")
self.hetres_label.setStyleSheet(small_font_style)
self.structure_frame_layout.addWidget(self.hetres_label, self.tot_rows, 0)
# Counts the hetres of this chain.
self.list_of_hetres = self.template_element.get_heteroresidues()
self.number_of_hetres = len(self.list_of_hetres)
# Radiobuttons for hetres options.
if self.number_of_hetres > 0:
self.hetres_options_var = 1
# Use all hetres checkbox.
use_all_hetres_text = "Use all heteroatomic residues (%s)" % (self.number_of_hetres)
self.use_all_hetres = QtWidgets.QRadioButton(use_all_hetres_text)
self.use_all_hetres.setStyleSheet(small_font_style)
self.use_all_hetres.clicked.connect(self.hide_select_single_hetres_frame)
self.use_all_hetres.setChecked(True)
self.use_all_hetres.setEnabled(False)
self.structure_frame_layout.addWidget(self.use_all_hetres, self.tot_rows, 1)
self.tot_rows += 1
# Select single hetres manually.
self.select_single_hetres = QtWidgets.QRadioButton("Select single heteroatomic residues")
self.select_single_hetres.setStyleSheet(small_font_style)
self.select_single_hetres.clicked.connect(self.show_select_single_hetres_frame)
self.select_single_hetres.setEnabled(False)
self.structure_frame_layout.addWidget(self.select_single_hetres, self.tot_rows, 1)
self.tot_rows += 1
# This is needed to count the "rows" used to grid HETRES checkboxes.
for hetres in self.list_of_hetres:
# Get the full name of the hetres.
checkbox_text = "%s (%s) %s" % (hetres.three_letter_code, hetres.hetres_type, hetres.db_index)
# Checkbox for each HETRES.
hetres_checkbutton = QtWidgets.QCheckBox(checkbox_text)
hetres_checkbutton.setStyleSheet(small_font_style + "; padding-left: 45px")
hetres_checkbutton.setEnabled(False)
self.structure_frame_layout.addWidget(hetres_checkbutton, self.tot_rows, 1)
self.tot_rows += 1
hetres_checkbutton.hide()
# Adds the single HETRES state to a list that contains the ones of the structure.
# self.structure_hetres_states.append(single_hetres_state)
self.structure_hetres_checkbuttons.append(hetres_checkbutton)
self.structure_hetres_dict.update({hetres: hetres_checkbutton})
# Do not use any hetres.
self.do_not_use_hetres = QtWidgets.QRadioButton("Do not use any heteroatomic residue")
self.do_not_use_hetres.setStyleSheet(small_font_style)
self.do_not_use_hetres.clicked.connect(self.hide_select_single_hetres_frame)
self.do_not_use_hetres.setEnabled(False)
self.structure_frame_layout.addWidget(self.do_not_use_hetres, self.tot_rows, 1)
self.tot_rows += 1
else:
self.no_hetres_label = QtWidgets.QLabel("No heteroatomic residue found")
self.no_hetres_label.setStyleSheet(small_font_style + "; color: %s" % modeling_options_inactive_label_color)
self.structure_frame_layout.addWidget(self.no_hetres_label, self.tot_rows, 1)
self.tot_rows += 1
self.hetres_options_var = 3
def get_hetres_options_var(self):
if self.number_of_hetres > 0:
if self.use_all_hetres.isChecked():
return 1
elif self.select_single_hetres.isChecked():
return 2
elif self.do_not_use_hetres.isChecked():
return 3
else:
raise ValueError("No hetres radiobuttun was pressed.")
else:
return 3
def show_select_single_hetres_frame(self):
for checkbox in self.structure_hetres_checkbuttons:
checkbox.show()
def hide_select_single_hetres_frame(self):
for checkbox in self.structure_hetres_checkbuttons:
checkbox.hide()
def build_water_frame(self):
"""
Builds a frame for letting the user choose to include water molecules in the model.
"""
# Label for water.
self.water_label = QtWidgets.QLabel("Include Water: ")
self.water_label.setStyleSheet(small_font_style)
self.structure_frame_layout.addWidget(self.water_label, self.tot_rows, 0)
# Checkbox for water
if self.template_element.has_waters():
n_water = len(self.template_element.get_waters())
text_for_water_checkbox = "%s water molecules" % (n_water)
self.water_checkbox = QtWidgets.QCheckBox(text_for_water_checkbox)
self.water_checkbox.setStyleSheet(small_font_style)
self.water_checkbox.setEnabled(False)
self.water_checkbox.clicked.connect(lambda x=self.template_idx: self.click_on_water_checkbutton(x))
self.structure_frame_layout.addWidget(self.water_checkbox, self.tot_rows, 1)
else:
self.no_water_label = QtWidgets.QLabel("This structure has no water molecules")
self.no_water_label.setStyleSheet(small_font_style + "; color: %s" % modeling_options_inactive_label_color)
self.structure_frame_layout.addWidget(self.no_water_label, self.tot_rows, 1)
def click_on_water_checkbutton(self,x):
"""
When a structure water checkbutton is pressed, this method deselects the water checkbutton of
all the other structures, because only water from one structure can be used to build the
model.
"""
for sf in self.parent_window.protocol.modeling_clusters_list[self.mc_id].structure_frame_list:
if sf.template_idx != self.template_idx and sf.template_element.has_waters():
sf.water_checkbox.setChecked(False)
def get_template_hetres_dict(self):
"""
Gets a dictionary that indicates which heteroresidue to include in the models.
"""
template_hetres_dict = {}
for h in self.structure_hetres_dict:
if self.get_hetres_options_var() == 1:
template_hetres_dict.update({h: 1})
elif self.get_hetres_options_var() == 2:
template_hetres_dict.update({h: int(self.structure_hetres_dict[h].isChecked())})
elif self.get_hetres_options_var() == 3:
template_hetres_dict.update({h: 0})
for water in self.template_element.get_waters():
template_hetres_dict.update({water: self.get_water_state_var()})
return template_hetres_dict
def is_selected(self):
return self.template_checkbox.isChecked()
def get_water_state_var(self):
if self.template_element.has_waters():
return int(self.water_checkbox.isChecked())
else:
return 0
class User_dsb_selector_frame_qt(QtWidgets.QFrame):
"""
Each modeling cluster will be used to build an object of this class. It will be used to let
users define custom disulfides bridges in the model chains.
"""
def __init__(self, parent, parent_window, modeling_cluster, *args, **configs):
self.parent_window = parent_window
self.protocol = self.parent_window.protocol
self.modeling_cluster = modeling_cluster
super(QtWidgets.QFrame, self).__init__(parent, *args, **configs)
self.initUI()
self.initialize_list()
self.use_dsb_selector_frame_layout.setAlignment(QtCore.Qt.AlignLeft)
self.setFrameShape(QtWidgets.QFrame.StyledPanel)
def initUI(self):
self.use_dsb_selector_frame_layout = QtWidgets.QGridLayout()
self.setLayout(self.use_dsb_selector_frame_layout)
label_text = ""
if self.modeling_cluster.has_target_with_multiple_cys():
label_text = "Select two CYS for target " + self.modeling_cluster.target_name
else:
label_text = "Target " + self.modeling_cluster.target_name + " does not have at least two CYS residues."
self.modeling_cluster_custom_dsb_label = QtWidgets.QLabel(label_text)
self.modeling_cluster_custom_dsb_label.setStyleSheet(modeling_options_subsections_style)
self.use_dsb_selector_frame_layout.addWidget(self.modeling_cluster_custom_dsb_label, 0, 0, 1, 3)
def initialize_list(self):
"""
Build the initial row in the user-defined disulfide bridges frame.
"""
self.target_list_of_cysteines = []
# The target chain sequence.
self.target_seq = self.modeling_cluster.target.my_sequence
# This is going to contain User_disulfide_combo_qt objects.
self.list_of_disulfide_combos = []
# This list is going to contain info about disulfide bridges defined by the user through the
# GUI. It is going to contain elements like this [[41,xx],[58,yy]] (the numbers are the
# position of the target cysteines in both the sequence and the alignment).
self.user_defined_disulfide_bridges = []
# Builds an interface to let the user define additional dsb only for targets which have at
# least two CYS residues.
if self.modeling_cluster.has_target_with_multiple_cys():
for (k, r) in enumerate(str(self.target_seq).replace("-", "")):
if r == "C":
cys = {"position": k + 1,
"alignment-position": pmsm.get_residue_id_in_aligned_sequence(self.target_seq, k),
"state": "free"}
self.target_list_of_cysteines.append(cys)
# If the target sequence has at least two cys, then creates the comboboxes.
first = User_disulfide_combo_qt(self, self.target_list_of_cysteines)
self.list_of_disulfide_combos.append(first)
def add_new_user_disulfide(self):
"""
This is called when the "Add" button to add a user-defined disulfide is pressed.
"""
cys_1_sel = self.list_of_disulfide_combos[-1].get_cys1_val()
cys_2_sel = self.list_of_disulfide_combos[-1].get_cys2_val()
# Checks that both the comboboxes have been used to select a cys.
if (cys_1_sel == "" or cys_2_sel == ""):
txt = "You have to select two cysteines residue to define a disulfide bridge!"
self.protocol.pymod.main_window.show_warning_message("Warning", txt)
return None
# Checks that the same cys has not been selected in both comboboxes.
elif cys_1_sel == cys_2_sel:
txt = "You cannot select the same cysteine to form a disulfide bridge!"
self.protocol.pymod.main_window.show_warning_message("Warning", txt)
return None
# Checks that the selected cys are not engaged in other bridges.
# ...
# If the two cys are free to form a bridge, then adds the new bridge and updates the
# frame with a new combobox row.
# Adds the new row with comboboxes and an "Add" button.
new_ds_combo = User_disulfide_combo_qt(self, self.target_list_of_cysteines)
# Activates the previous row and returns the name of the 2 selected cys.
cysteines = self.list_of_disulfide_combos[-1].activate()
# Finishes and adds the new row.
self.list_of_disulfide_combos.append(new_ds_combo)
# Adds the cys pair to the self.user_defined_disulfide_bridges, which is going to be
# used in the launch_modelization() method.
self.user_defined_disulfide_bridges.append(cysteines)
def remove_user_disulfide(self, udc_to_remove):
"""
This is called when the "Remove" button is pressed.
"""
# Deactivate and get the right bridge to remove.
dsb_to_remove = udc_to_remove.deactivate()
# Finishes to adds the new row.
self.list_of_disulfide_combos.remove(udc_to_remove)
# Also removes the bridge from the self.user_defined_disulfide_bridges.
self.user_defined_disulfide_bridges.remove(dsb_to_remove)
class User_disulfide_combo_qt:
"""
Class for building in the 'Disulfide' page in the modeling window a "row" with two comboboxes and
a button to add or remove a user defined disulfide bridge to be included in the model.
"""
# This is used in the constructor when a new combobox row is created.
id_counter = 0
def __init__(self, parent, cys_list):
self.parent = parent
# Selected have the "Add" button, unselected have the "Remove" button.
self.selected = False
User_disulfide_combo_qt.id_counter += 1
self.row = User_disulfide_combo_qt.id_counter
# The list of cysteines residues of the target sequence.
self.cys_list = cys_list
# The list of strings that is going to appear on the scrollable menus of the comboboxes.
self.scrollable_cys_list = []
for cys in self.cys_list:
self.scrollable_cys_list.append("CYS " + str(cys["position"]))
# Creates the first row with two comboboxes.
self.create_combobox_row()
combobox_padding = 30
button_padding = 40
def create_combobox_row(self):
"""
Builds a row with two comboboxes an "Add" button.
"""
# First CYS combobox.
self.cys1_combobox = QtWidgets.QComboBox() # Select the first CYS:
for item in self.scrollable_cys_list:
self.cys1_combobox.addItem(item)
self.cys1_combobox.setEditable(False)
self.cys1_combobox.setStyleSheet(small_font_style)
self.cys1_combobox.setFixedWidth(self.cys1_combobox.sizeHint().width() + self.combobox_padding)
# Second CYS combobox.
self.cys2_combobox = QtWidgets.QComboBox() # Select the second CYS:
for item in self.scrollable_cys_list:
self.cys2_combobox.addItem(item)
self.cys2_combobox.setEditable(False)
self.cys2_combobox.setStyleSheet(small_font_style)
self.cys2_combobox.setFixedWidth(self.cys2_combobox.sizeHint().width() + self.combobox_padding)
self.update_scrollable_cys_list()
# "Add" button.
self.new_disulfides_button = QtWidgets.QPushButton("Add")
self.new_disulfides_button.setStyleSheet(small_font_style)
self.new_disulfides_button.clicked.connect(self.press_add_button)
self.new_disulfides_button.setFixedWidth(self.new_disulfides_button.sizeHint().width() + self.button_padding)
self.parent.use_dsb_selector_frame_layout.addWidget(self.cys1_combobox, self.row, 0)
self.parent.use_dsb_selector_frame_layout.addWidget(self.cys2_combobox, self.row, 1)
self.parent.use_dsb_selector_frame_layout.addWidget(self.new_disulfides_button, self.row, 2)
User_disulfide_combo_qt.id_counter += 1
def select_cys(self,i):
"""
This is launched by the combobox when some cys is selected.
It should also be used to change the color of the cys according to their state.
"""
pass
def update_scrollable_cys_list(self):
"""
Adjust the cysteine list to be displayed on the combobox with the right colors.
"""
return None
# # cys = {"position": seq_counter, "alignment-position":k, "state":"free"}
# for (i,cys) in enumerate(self.cys_list):
# if cys["state"] == "free":
# self.cys1_combobox.component("scrolledlist").component("listbox").itemconfig(i,fg="black")
# self.cys2_combobox.component("scrolledlist").component("listbox").itemconfig(i,fg="black")
# elif cys["state"] == "engaged":
# self.cys1_combobox.component("scrolledlist").component("listbox").itemconfig(i,fg="gray")
# self.cys2_combobox.component("scrolledlist").component("listbox").itemconfig(i,fg="gray")
# # There must also be a condition used to mark cys residues engaged in disulfides
# # present in the templates.
def press_add_button(self):
"""
This is going to call a method of the 'User_dsb_selector_frame_qt' class.
"""
self.parent.add_new_user_disulfide()
def activate(self):
"""
This is going to return the information about which cys have been selected when the "Add"
button is pressed.
"""
self.selected = True
# Removes the "Add" button
self.remove_widget(self.new_disulfides_button)
self.new_disulfides_button = None
# Removes both comboboxes, but before get their values.
self.text1 = self.get_cys1_val()
self.remove_widget(self.cys1_combobox)
self.cys1_combobox = None
self.text2 = self.get_cys2_val()
self.remove_widget(self.cys2_combobox)
self.cys2_combobox = None
self.create_label_row()
return self.text1, self.text2
def remove_widget(self, widget):
self.parent.use_dsb_selector_frame_layout.removeWidget(widget)
widget.deleteLater()
def create_label_row(self):
"""
Build a row with two labels and a "Remove" button. Called when the "Add"
button is pressed.
"""
# Create dirst CYS label that tells which cys has been selected.
self.cys1_label = QtWidgets.QLabel(self.text1)
self.cys1_label.setStyleSheet(small_font_style)
self.cys1_label.setAlignment(QtCore.Qt.AlignCenter)
self.parent.use_dsb_selector_frame_layout.addWidget(self.cys1_label, self.row, 0)
# Second CYS label.
self.cys2_label = QtWidgets.QLabel(self.text2)
self.cys2_label.setStyleSheet(small_font_style)
self.cys2_label.setAlignment(QtCore.Qt.AlignCenter)
self.parent.use_dsb_selector_frame_layout.addWidget(self.cys2_label, self.row, 1)
# Adds the "Remove" button.
self.remove_disulfides_button = QtWidgets.QPushButton("Remove")
self.remove_disulfides_button.setStyleSheet(small_font_style)
self.remove_disulfides_button.clicked.connect(self.press_remove_button)
self.parent.use_dsb_selector_frame_layout.addWidget(self.remove_disulfides_button, self.row, 2)
def press_remove_button(self):
"""
This is going to call a method of the 'User_dsb_selector_frame_qt' class.
"""
self.parent.remove_user_disulfide(self)
def deactivate(self):
"""
This is going to return the information about which bridge has been removed when "Remove"
button is pressed.
"""
self.selected = False
self.remove_widget(self.cys1_label)
self.cys1_label = None
self.remove_widget(self.cys2_label)
self.cys2_label = None
self.remove_widget(self.remove_disulfides_button)
self.remove_disulfides_button = None
return self.text1, self.text2
def get_cys1_val(self):
return self.cys1_combobox.currentText()
def get_cys2_val(self):
return self.cys2_combobox.currentText()
###############################################################################
# Custom optimization level options. #
###############################################################################
class Optimization_level_frame_qt(QtWidgets.QFrame):
use_max_cg_iterations_enf = True
use_vtfm_schedule_rds = True
use_md_schedule_rds = True
md_schedule_rds_default_val = "very fast"
use_repeat_optimization_enf = True
use_max_obj_func_value_enf = True
# borderwidth=1
# relief='groove'
# pady=5
def __init__(self, parent=None, *args, **configs):
super(Optimization_level_frame_qt, self).__init__(parent, *args, **configs)
self.initUI()
self.setFrameShape(QtWidgets.QFrame.StyledPanel)
def initUI(self):
self.optimization_frame_layout = QtWidgets.QFormLayout()
# self.optimization_frame_layout.setVerticalSpacing(0)
self.setLayout(self.optimization_frame_layout)
self.title_label = QtWidgets.QLabel("Custom Optimization Options")
self.title_label.setStyleSheet(modeling_options_subsections_style)
self.optimization_frame_layout.addRow(self.title_label)
# Max CG iterations.
if self.use_max_cg_iterations_enf:
self.max_cg_iterations_enf = Modeling_option_entryfield_qt(None,
label_text="Max CG iterations",
# labelmargin=self.enf_labelmargin,
value="200", validate={'validator': 'integer', 'min': 1, 'max': 2000})
self.optimization_frame_layout.addRow(self.max_cg_iterations_enf)
# VTFM schedule radioselect.
if self.use_vtfm_schedule_rds:
self.vtfm_schedule_rds = Modeling_option_radioselect_qt(None,
label_text="VTFM optimization schedule",
buttons=("fastest", "very fast", "fast", "normal", "slow"))
self.vtfm_schedule_rds.setvalue("normal")
self.optimization_frame_layout.addRow(self.vtfm_schedule_rds)
# MD schedule radioselect.
if self.use_md_schedule_rds:
self.md_schedule_rds = Modeling_option_radioselect_qt(None,
label_text="MD refinement schedule",
buttons=("none", "very fast", "fast", "slow", "very slow"))
self.md_schedule_rds.setvalue(self.md_schedule_rds_default_val)
self.optimization_frame_layout.addRow(self.md_schedule_rds)
# Repeat optimization.
if self.use_repeat_optimization_enf:
self.repeat_optimization_enf = Modeling_option_entryfield_qt(None,
label_text="Number of times to repeat optimization",
value="1", validate={'validator': 'integer', 'min': 1, 'max': 10})
self.optimization_frame_layout.addRow(self.repeat_optimization_enf)
# Max objective function value.
if self.use_max_obj_func_value_enf:
self.max_obj_func_value_enf = Modeling_option_entryfield_qt(None,
label_text="Max objective function value: 10^",
value="7", validate={'validator': 'integer', 'min': 5, 'max': 10})
self.optimization_frame_layout.addRow(self.max_obj_func_value_enf)
class Modeling_option_widget_qt(QtWidgets.QWidget):
def initUI(self):
self.setStyleSheet("margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px")
class Modeling_option_entryfield_qt(Modeling_option_widget_qt):
def __init__(self, parent, label_text, value="", validate={},
use_checkbox=False, use_checkbox_command=None, active=True):
super(Modeling_option_entryfield_qt, self).__init__(parent)
self.initUI()
# Layout.
self.option_layout = QtWidgets.QFormLayout()
# self.option_layout.setVerticalSpacing(0)
self.setLayout(self.option_layout)
# Widgets.
self.use_checkbox = use_checkbox
if not self.use_checkbox:
self.label = QtWidgets.QLabel(label_text)
else:
self.checkbox = QtWidgets.QCheckBox(label_text)
self.use_checkbox_command = use_checkbox_command
if self.use_checkbox_command is not None:
self.checkbox.clicked.connect(self.use_checkbox_command)
self.label = self.checkbox
self.label.setStyleSheet(small_font_style)
self.entry = PyMod_entry_qt(value)
self.entry.set_pmw_validator(validate)
if active:
self.entry.setStyleSheet(active_entry_style + "; " + small_font_style)
else:
self.entry.setEnabled(False)
self.entry.setStyleSheet(inactive_entry_style + "; " + small_font_style)
self.entry.setFixedWidth(60)
self.option_layout.addRow(self.label, self.entry)
def getvalue(self, validate=False):
return self.entry.getvalue(validate=validate, option_name=self.label.text())
def setvalue(self, value):
return self.entry.setvalue(value)
def activate_entry(self):
self.entry.setEnabled(True)
self.entry.setStyleSheet(active_entry_style + "; " + small_font_style)
def inactivate_entry(self):
self.entry.setEnabled(False)
self.entry.setStyleSheet(inactive_entry_style + "; " + small_font_style)
class Modeling_option_radioselect_qt(Modeling_option_widget_qt):
def __init__(self, parent, label_text, buttons=[]):
super(Modeling_option_radioselect_qt, self).__init__(parent)
self.initUI()
# Layout.
self.option_layout = QtWidgets.QGridLayout()
# self.option_layout.setVerticalSpacing(0)
self.setLayout(self.option_layout)
# Widgets.
self.label = QtWidgets.QLabel(label_text)
self.label.setStyleSheet(small_font_style)
self.option_layout.addWidget(self.label, 0, 0)
self.button_group = QtWidgets.QButtonGroup()
self.buttons_names = []
self.buttons_dict = {}
for button_idx, button_name in enumerate(buttons):
radiobutton = QtWidgets.QRadioButton(button_name)
radiobutton.setStyleSheet(small_font_style)
self.buttons_names.append(button_name)
self.buttons_dict[button_name] = radiobutton
self.button_group.addButton(radiobutton)
self.option_layout.addWidget(radiobutton, button_idx, 1)
self.option_layout.setAlignment(QtCore.Qt.AlignLeft)
def get_buttons(self):
return self.button_group.buttons()
def get_button_at(self, index):
buttons = [b for b in self.get_buttons()]
return buttons[index]
def setvalue(self, value):
self.buttons_dict[value].setChecked(True)
def getvalue(self):
checked_button = self.button_group.checkedButton()
if checked_button is None:
return None
else:
return checked_button.text()
###############################################################################
# Customize objective function options. #
###############################################################################
class Custom_obj_func_frame_qt(QtWidgets.QFrame):
use_loop_stat_pot_rds = False
use_hddr_frame = True
use_hdar_frame = True
hdar_frame_text = "Homology-derived dihedral restraints. Weight: "
use_charmm22_frame = True
use_soft_sphere_frame = True
use_dope_frame = True
use_stat_pot_frame = False
use_lj_frame = False
use_gbsa_frame = False
max_weight_val = 3.0
initial_nb_cutoff_val = 4.0
# borderwidth=1
# relief='groove'
# pady=5
def __init__(self, parent=None, *args, **configs):
super(Custom_obj_func_frame_qt, self).__init__(parent, *args, **configs)
self.initUI()
self.setFrameShape(QtWidgets.QFrame.StyledPanel)
def initUI(self):
self.custom_obj_func_frame_layout = QtWidgets.QFormLayout()
self.setLayout(self.custom_obj_func_frame_layout)
self.title_label_1 = QtWidgets.QLabel("Customize Objective Function Terms")
self.title_label_1.setStyleSheet(modeling_options_subsections_style)
self.custom_obj_func_frame_layout.addRow(self.title_label_1)
if self.use_loop_stat_pot_rds:
self.loop_stat_pot_rds = Modeling_option_radioselect_qt(None,
label_text="Loop modeling class:",
buttons=("loopmodel", "DOPE loopmodel"))
self.loop_stat_pot_rds.setvalue("loopmodel")
self.custom_obj_func_frame_layout.addRow(self.loop_stat_pot_rds)
self.loop_stat_pot_rds.get_button_at(0).clicked.connect(self.activate_fm_loop_class)
self.loop_stat_pot_rds.get_button_at(1).clicked.connect(self.activate_dope_loop_class)
if self.use_hddr_frame:
self.hddr_frame = Modeling_option_entryfield_qt(parent=None,
label_text="Homology-derived distance restraints. Weight: ",
value="1.0", validate={'validator': 'real', 'min': 0.0, 'max': self.max_weight_val})
self.custom_obj_func_frame_layout.addRow(self.hddr_frame)
if self.use_hdar_frame:
self.hdar_frame = Modeling_option_entryfield_qt(parent=None,
label_text=self.hdar_frame_text,
value="1.0", validate={'validator': 'real', 'min': 0.0, 'max': self.max_weight_val})
self.custom_obj_func_frame_layout.addRow(self.hdar_frame)
if self.use_charmm22_frame:
self.charmm22_frame = Modeling_option_entryfield_qt(parent=None,
label_text="CHARMM22 stereochemical terms. Weight: ",
value="1.0", validate={'validator': 'real', 'min': 0.0, 'max': self.max_weight_val})
self.custom_obj_func_frame_layout.addRow(self.charmm22_frame)
if self.use_soft_sphere_frame:
self.soft_sphere_frame = Modeling_option_entryfield_qt(parent=None,
label_text="Sotf-sphere terms. Weight: ",
value="1.0", validate={'validator': 'real', 'min': 0.0, 'max': self.max_weight_val})
self.custom_obj_func_frame_layout.addRow(self.soft_sphere_frame)
if self.use_dope_frame:
self.dope_frame = Modeling_option_entryfield_qt(parent=None,
label_text="Include DOPE in the objective function. Weight: ",
value="0.5", validate={'validator': 'real', 'min': 0.0, 'max': self.max_weight_val},
use_checkbox=True, use_checkbox_command=self.set_nb_cutoff_on_activate_dope,
active=False)
self.custom_obj_func_frame_layout.addRow(self.dope_frame)
if self.use_stat_pot_frame:
self.stat_pot_frame = Modeling_option_entryfield_qt(parent=None,
label_text="Loop statistial potential. Weight: ",
value="1.0", validate={'validator': 'real', 'min': 0.0, 'max': self.max_weight_val})
self.custom_obj_func_frame_layout.addRow(self.stat_pot_frame)
if self.use_lj_frame:
self.lj_frame = Modeling_option_entryfield_qt(parent=None,
label_text="Lennard-Jones terms. Weight: ",
value="1.0", validate={'validator': 'real', 'min': 0.0, 'max': self.max_weight_val},
active=False)
self.custom_obj_func_frame_layout.addRow(self.lj_frame)
if self.use_gbsa_frame:
self.gbsa_frame = Modeling_option_entryfield_qt(parent=None,
label_text="GBSA terms. Weight: ",
value="1.0", validate={'validator': 'real', 'min': 0.0, 'max': self.max_weight_val},
active=False)
self.custom_obj_func_frame_layout.addRow(self.gbsa_frame)
self.title_2_label = QtWidgets.QLabel("Customize Objective Function Parameters")
self.title_2_label.setStyleSheet(modeling_options_subsections_style)
self.custom_obj_func_frame_layout.addRow(self.title_2_label)
self.nb_cutoff_frame = Modeling_option_entryfield_qt(parent=None,
label_text="Non bonded cutoff (%s): " % ("\u212B"),
value=str(self.initial_nb_cutoff_val), validate={'validator': 'real', 'min': 3.0, 'max': 14.0})
self.custom_obj_func_frame_layout.addRow(self.nb_cutoff_frame)
def set_nb_cutoff_on_activate_dope(self):
"""
Automatically change the nb interactions cutoff when including DOPE terms in the objective
function.
"""
if self.dope_frame.checkbox.isChecked():
self.nb_cutoff_frame.setvalue("8.0")
self.dope_frame.activate_entry()
else:
self.nb_cutoff_frame.setvalue("4.0")
self.dope_frame.inactivate_entry()
def get_use_dope_var(self):
if self.use_dope_frame:
return self.dope_frame.checkbox.isChecked()
else:
raise ValueError("A DOPE weight selection entry was not built.")
def activate_fm_loop_class(self):
"""
Activates lj and gbsa, inactivates soft sphere.
"""
self.lj_frame.inactivate_entry()
self.gbsa_frame.inactivate_entry()
self.soft_sphere_frame.activate_entry()
self.soft_sphere_frame.entry.setvalue("1.0")
self.stat_pot_frame.entry.setvalue("1.0")
self.nb_cutoff_frame.entry.setvalue("7.0")
def activate_dope_loop_class(self):
"""
Inactivates lj and gbsa, activates soft sphere.
"""
self.lj_frame.activate_entry()
self.lj_frame.entry.setvalue("1.0")
self.gbsa_frame.activate_entry()
self.gbsa_frame.entry.setvalue("1.0")
self.soft_sphere_frame.inactivate_entry()
self.stat_pot_frame.entry.setvalue("0.6")
self.nb_cutoff_frame.entry.setvalue("8.0")
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_protocols/structural_analysis_protocols/structural_divergence_plot.py | .py | 15,403 | 340 | # Copyright 2020 by Giacomo Janson. All rights reserved.
# This code is part of the PyMod package and governed by its license. Please
# see the LICENSE file that should have been included as part of this package
# or the main __init__.py file in the pymod3 folder.
"""
Module implementing a protocol for analyzing the structural divergence between aligned protein
structures in PyMod. Builds a plot with CA-CA distance for each residue or a RMSF plot.
"""
import os
import numpy as np
from pymol import cmd
from pymod_lib import pymod_vars
from pymod_lib.pymod_protocols.base_protocols import PyMod_protocol
from pymod_lib.pymod_gui.shared_gui_components_qt import (PyMod_protocol_window_qt,
PyMod_entryfield_qt,
PyMod_radioselect_qt,
PyMod_combobox_qt)
from pymod_lib.pymod_protocols.structural_analysis_protocols._base_structural_analysis import get_distance, Structural_analysis_mixin
from pymod_lib.pymod_plot.pymod_plot_qt import PyMod_plot_window_qt
from pymod_lib.pymod_threading import Protocol_exec_dialog
###################################################################################################
# Main class. #
###################################################################################################
class Structural_divergence_plot(PyMod_protocol, Structural_analysis_mixin):
"""
Class for implementing structural divergence analyses (sda) in PyMod.
"""
protocol_name = "structural_divergence_plot"
def __init__(self, pymod):
PyMod_protocol.__init__(self, pymod)
self.target_sequences = self.get_pymod_elements()
def launch_from_gui(self):
"""
Checks the condition for launching a structural divergence plot analysis.
"""
error_title = "Selection Error"
# Check that no nucleic acid structure has been selected.
if not self.check_protein_selection(error_title):
return None
# Check that at least two elements have been selected.
if len(self.target_sequences) < 2:
self.pymod.main_window.show_error_message(error_title,
"Please select at least two structures in the same alignment.")
return None
# Check for multiple aligned structures in the same cluster.
if not self.check_multiple_selection(error_title):
return None
if not self.target_sequences[0].mother.algorithm in pymod_vars.structural_alignment_tools:
message = pymod_vars.structural_alignment_warning % "Structural Divergence Plot"
self.pymod.main_window.show_warning_message("Alignment Warning", message)
# Opens the options window.
self.sda_options_window = SDA_options_window_qt(self.pymod.main_window,
protocol=self,
title="Structural Divergence Plot Options",
upper_frame_title="Options for Structural Divergence Plot",
submit_command=self.sda_state)
self.sda_options_window.show()
def sda_state(self):
#--------------------------------------
# Checks the parameters from the GUI. -
#--------------------------------------
# Analysis mode.
analysis_mode, analysis_mode_full_name = self.sda_options_window.get_analysis_mode()
self.reference_element_id = self.sda_options_window.get_reference_id()
self.reference_element = self.target_sequences[self.reference_element_id]
self.sda_options_window.destroy()
#----------------------------------
# Actually launches the analysis. -
#----------------------------------
if analysis_mode == "rmsf":
self.launch_rmsf_analysis()
elif analysis_mode == "distances":
self.launch_distances_divergence_analysis()
else:
KeyError(analysis_mode)
##########################################
# Root mean square fluctuation analysis. #
##########################################
def launch_rmsf_analysis(self):
"""
Launches the RMSF analysis. A plot containing the RMSF profile of the selected structures
will be shown.
"""
# Prepares the atomic coordinates of the structures.
ali_seqs_dicts = []
res_dicts = []
for element in self.target_sequences:
ali_seq_dict, res_dict = self._get_sda_data(element)
ali_seqs_dicts.append(ali_seq_dict)
res_dicts.append(res_dict)
# Actually computes the RMSF of the residues.
ali_len = len(self.target_sequences[0].my_sequence)
rmsf_list = []
residues_additional_data = []
for ali_pos in range(0, ali_len):
# For each alignment position, get the coordinates of the residues.
coords_list = []
reference_res = None
for structure_idx, (ali_seq_dict, res_dict) in enumerate(zip(ali_seqs_dicts, res_dicts)):
# Gets a residue.
res = self._get_res(ali_pos, ali_seq_dict)
# Gets its coordinates.
coords_i = self._get_coords(res, res_dict)
if coords_i is None:
continue
coords_list.append(coords_i)
# Stores the reference residue.
if structure_idx == self.reference_element_id:
reference_res = res
# Get the reference structure information.
if reference_res is not None:
residues_additional_data.append({"residue_name": reference_res.three_letter_code,
"residue_pdb_position": reference_res.db_index,
"pymol_selector": reference_res.get_pymol_selector(),
"export_label": "%s %s" % (reference_res.three_letter_code, reference_res.db_index)})
else:
residues_additional_data.append({"residue_name": "none",
"residue_pdb_position": "-",
"pymol_selector": None,
"export_label": "None"})
# For each alignment position, get the coordinates of the residues.
if len(coords_list) > 1:
coords_list = np.array(coords_list)
# Take the centroid.
centroid = coords_list.mean(axis=0)
# Computes the RMSF.
rmsf = np.sqrt(np.mean([np.linalg.norm(ci-centroid)**2 for ci in coords_list]))
rmsf_list.append(round(rmsf, 3))
elif len(coords_list) == 1:
rmsf_list.append(None)
else:
rmsf_list.append(None)
# Builds the structural divergence plot.
cp = PyMod_plot_window_qt(self.pymod.main_window)
cp.initialize(pymod=self.pymod, title="RMSF Plot")
messagebar_text_on_update_qt = ("Selected: __residue_name__ __residue_pdb_position__ " +
self.reference_element.compact_header +
" (alignment position: __x__), RMSF value: __y__ " + "\u212B")
cp.build_plotting_area(messagebar_initial_text="Set the 'Interact on click' option to 'Yes' to click on the plot and to highlight residues in PyMOL.",
update_messagebar=True,
messagebar_text_on_update=messagebar_text_on_update_qt,
on_click_action=self._highlight_in_pymol_from_sda_plot_qt,
x_label_text="Alignment position",
y_label_text="RMSF %s" % "\u212B",)
# Values on the x-axis.
x_series = list(range(1, ali_len+1))
# Adds the RMSF plot.
cp.add_plot(x_series, rmsf_list, label="RMSF plot", additional_data=residues_additional_data)
# Actually shows the plot.
cp.show()
#################################
# Distance divergence analysis. #
#################################
def launch_distances_divergence_analysis(self):
"""
Launches the "Distance Divergence" analysis. Once the user has selected a reference structure,
the distances between its CA atoms and the aligned CA atoms of the other structures will be
calculated. A plot with the CA-CA distance profiles (one profile for each structure aligned
to the reference one) will be shown.
"""
# Prepares the atomic coordinates of the structures. First, get the reference element data.
ref_ali_seq_dict, ref_res_dict = self._get_sda_data(self.reference_element)
# Get the data for the rest of the elements.
ali_seqs_dicts = []
res_dicts = []
structures_to_analyze = [e for e in self.target_sequences if e is not self.reference_element]
for element in structures_to_analyze:
ali_seq_dict, res_dict = self._get_sda_data(element)
ali_seqs_dicts.append(ali_seq_dict)
res_dicts.append(res_dict)
# Initializes the plot.
cp = PyMod_plot_window_qt(self.pymod.main_window)
cp.initialize(pymod=self.pymod,
title="CA-CA Distance Plot with reference: %s" % self.reference_element.compact_header)
messagebar_text_on_update_qt = ("Selected: __residue_name__ __residue_pdb_position__"
" of __plot_name__ (alignment position: __x__), CA-CA"
" distance value: __y__ " + "\u212B")
cp.build_plotting_area(messagebar_initial_text="Set the 'Interact on click' option to 'Yes' to click on the plot and to highlight residues in PyMOL.",
update_messagebar=True,
messagebar_text_on_update=messagebar_text_on_update_qt,
on_click_action=self._highlight_in_pymol_from_sda_plot_qt,
x_label_text="Alignment position",
y_label_text="CA distance %s" % "\u212B",)
# Values on the x-axis.
ali_len = len(self.target_sequences[0].my_sequence)
y_series_list = [[] for i in range(0, len(structures_to_analyze))]
additional_data_list = [[] for i in range(0, len(structures_to_analyze))]
# For each alignment position, get the coordinates of the reference residue (if present in
# that position).
for ali_pos in range(0, ali_len):
# Gets a reference residue and its coordinates.
ref_res = self._get_res(ali_pos, ref_ali_seq_dict)
ref_coords_i = self._get_coords(ref_res, ref_res_dict)
# Cycle through all the structures aligned to the reference one.
for ali_seq_dict, res_dict, y_series, additional_data in zip(ali_seqs_dicts,
res_dicts,
y_series_list,
additional_data_list):
# Gets a residue and its coordinates.
res = self._get_res(ali_pos, ali_seq_dict)
coords_i = self._get_coords(res, res_dict)
# The reference structure does not have coordinates in this alignment position.
if coords_i is None or ref_coords_i is None:
y_series.append(None)
additional_data.append({"residue_name": "none",
"residue_pdb_position": "-",
"pymol_selector": None,
"export_label": "None"})
continue
# Gets the distance between the reference residue and the target one.
dist = get_distance(ref_coords_i, coords_i)
y_series.append(round(dist, 3))
additional_data.append({"residue_name": res.three_letter_code,
"residue_pdb_position": res.db_index,
"pymol_selector": res.get_pymol_selector(),
"export_label": "%s %s" % (res.three_letter_code, res.db_index)})
# Adds the CA-CA distances plot.
x_series = list(range(1, ali_len+1))
for element, y_series, additional_data in zip(structures_to_analyze,
y_series_list,
additional_data_list):
cp.add_plot(x_series, y_series, label=element.compact_header,
additional_data=additional_data)
# Actually shows the plot.
cp.show()
def _highlight_in_pymol_from_sda_plot_qt(self, point_data):
sel = point_data["pymol_selector"]
if sel is not None:
cmd.select("pymod_selection", sel)
cmd.center("pymod_selection")
###################################################################################################
# GUI. #
###################################################################################################
class SDA_options_window_qt(PyMod_protocol_window_qt):
"""
Window used in the contact map analysis.
"""
analysis_modes_list = ["CA-CA Distances", "CA RMSF"]
def build_protocol_middle_frame(self):
# Analysis mode.
self.analysis_mode_rds = PyMod_radioselect_qt(label_text="Analysis Mode",
buttons=self.analysis_modes_list)
self.analysis_mode_rds.setvalue(self.analysis_modes_list[0])
self.middle_formlayout.add_widget_to_align(self.analysis_mode_rds)
# Reference structure combobox.
structures_list = [element.my_header for element in self.protocol.target_sequences]
self.reference_combobox = PyMod_combobox_qt(label_text="Reference Structure",
items=structures_list)
self.reference_combobox.combobox.setCurrentIndex(0)
self.middle_formlayout.add_widget_to_align(self.reference_combobox)
self.middle_formlayout.set_input_widgets_width("auto", padding=10)
def get_analysis_mode(self):
feature_type = self.analysis_mode_rds.getvalue()
if feature_type == self.analysis_modes_list[0]:
return "distances", feature_type
elif feature_type == self.analysis_modes_list[1]:
return "rmsf", feature_type
else:
raise KeyError(feature_type)
def get_reference_id(self):
try:
return self.reference_combobox.get_index()
except:
print("- WARNING: could not obtain the reference structure id.")
return 0
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_protocols/structural_analysis_protocols/psipred.py | .py | 14,917 | 306 | # Copyright 2016 by Chengxin Zhang, Giacomo Janson. All rights reserved.
# This code is part of the PyMod package and governed by its license. Please
# see the LICENSE file that should have been included as part of this package
# or the main __init__.py file in the pymod3 folder.
import os
from pymod_lib import pymod_os_specific as pmos
from pymod_lib.pymod_vars import psipred_output_extensions
from pymod_lib.pymod_protocols.base_protocols import PyMod_protocol
from pymod_lib.pymod_protocols.similarity_searches_protocols.psiblast import PSI_BLAST_common
from pymod_lib.pymod_threading import Protocol_exec_dialog
from pymod_lib.pymod_exceptions import catch_protocol_exception
class PSIPRED_prediction(PyMod_protocol, PSI_BLAST_common):
"""
Class for a psipred prediction protocol.
"""
protocol_name = "psipred"
error_title = "PSIPRED error"
def __init__(self, pymod, target_sequences=None):
PyMod_protocol.__init__(self, pymod)
self.target_sequences = self.get_pymod_elements(target_sequences)
@catch_protocol_exception
def launch_from_gui(self):
if len(self.target_sequences) == 0:
self.pymod.main_window.show_error_message("PSIPRED Error",
"Please select at least one sequence to be analyzed with PSIPRED.")
return False
if not self.check_psipred_parameters():
return False
# Run psipred on all the selected sequences.
self.predicted_sequences = []
if not self.pymod.use_protocol_threads:
self.predict_all_sequences()
else:
label_text = ("Running psipred on %s. Please wait for the process to"
" complete..." % self.get_seq_text(self.target_sequences))
p_dialog = Protocol_exec_dialog(app=self.pymod.main_window, pymod=self.pymod,
function=self.predict_all_sequences,
args=(),
title="Running psipred",
label_text=label_text)
p_dialog.exec_()
# Colors the sequences by predicted secondary structure.
for sequence in self.predicted_sequences:
sequence.predicted_secondary_structure = True
self.pymod.main_window.color_element_by_pred_sec_str(sequence, color_structure=True)
def check_psipred_parameters(self): # predict_secondary_structure(self, elements=None):
"""
Checks that the files needed to run PSIPRED exists on users' machines.
"""
# First checks for PSIPRED installation.
if not self.pymod.psipred.tool_dir_exists(parameter_name="exe_dir_path"):
self.pymod.psipred.tool_dir_not_found()
return False
psipred_exe_dirpath = self.pymod.psipred["exe_dir_path"].get_value()
for _exe_filename in ("chkparse", "psipred", "psipass2"):
exe_filename = pmos.get_exe_file_name(_exe_filename)
if not os.path.isfile(os.path.join(psipred_exe_dirpath, exe_filename)):
message = ("A PSIPRED executable file ('%s') does not exists in"
" the PSIPRED executables directory specified in the PyMod"
" Options Window ('%s'). If you want to use PSIPRED, please"
" specify in the Options Window a PSIPRED executables directory"
" where a '%s' file is found." % (exe_filename, psipred_exe_dirpath, exe_filename))
self.pymod.main_window.show_error_message(self.error_title, message)
return False
# Then checks for PSIPRED datafiles.
if not self.pymod.psipred.tool_dir_exists(parameter_name="data_dir_path"):
message = ("PSIPRED 'data' directory not found! Please specify an existent"
" directory in the PSIPRED Options Window of PyMod.")
self.pymod.main_window.show_error_message(self.error_title, message)
return False
psipred_data_dirpath = self.pymod.psipred["data_dir_path"].get_value()
if len(os.listdir(psipred_data_dirpath)) == 0:
message = ("PSIPRED 'data' directory is empty! Please specify a data"
" directory actually containing PSIPRED data file in the"
" in the Options Window of PyMod.")
self.pymod.main_window.show_error_message(self.error_title, message)
return False
# Checks for PSI-BLAST on the user's system.
if not self.pymod.blast_plus.tool_dir_exists(parameter_name="exe_dir_path"):
self.pymod.blast_plus.tool_dir_not_found()
return False
psiblast_exe_dirpath = self.pymod.blast_plus["exe_dir_path"].get_value()
if not os.path.isfile(os.path.join(psiblast_exe_dirpath, pmos.get_exe_file_name("psiblast"))):
message = ("The PSI-BLAST executable file ('psiblast') does not exists in"
" the BLAST+ suite executables directory specified in the PyMod"
" Options Window ('%s'). If you want to use PSIPRED, please"
" specify in the Options Window a BLAST+ suite executables directory"
" where a 'psiblast' file is found." % (psiblast_exe_dirpath))
self.pymod.main_window.show_error_message(self.error_title, message)
return False
# And finally checks for a BLAST database.
if not self.pymod.psipred.tool_dir_exists(parameter_name="database_dir_path"):
message = ("A directory containing a BLAST database was not found! Please"
" specify an existent directory in the PSIPRED options in the options window of PyMod.")
self.pymod.main_window.show_error_message(self.error_title, message)
return False
dbpath = self.pymod.psipred["database_dir_path"].get_value()
if not self.verify_valid_blast_dbdir(dbpath, remove_temp_files=True):
message = ("The database '%s' directory does not contain a valid set"
" of database files." % (dbpath))
self.pymod.main_window.show_error_message(self.error_title, message)
return False
return True
def predict_all_sequences(self):
for sequence in self.target_sequences:
# Actually calls the method that launches PSIPRED.
prediction_successful = self.run_psipred(sequence)
if prediction_successful:
self.predicted_sequences.append(sequence)
def run_psipred(self, element):
"""
Actually runs PSIPRED, collects its results and map them on the sequences in PyMod main
window.
"""
print_output = False
sequence_header = element.my_header
if print_output:
print("- Beginning PSIPRED prediction for:", sequence_header)
# The name of the BLAST database file.
# If the database files are contained in a folder like this: /home/user/pymod/databases/swissprot/swissprot
dbpath = self.pymod.psipred["database_dir_path"].get_value() # e.g.: /home/user/pymod/databases/swissprot
if print_output:
print("- dbpath:", dbpath)
# Where the NCBI programs have been installed.
ncbidir = self.pymod.blast_plus["exe_dir_path"].get_value()
if print_output:
print("- ncbidir:", ncbidir)
# Where the PSIPRED V2 programs have been installed.
execdir = self.pymod.psipred["exe_dir_path"].get_value()
if print_output:
print("- execdir:", execdir)
# Where the PSIPRED V2 data files have been installed.
datadir = self.pymod.psipred["data_dir_path"].get_value()
if print_output:
print("- datadir",datadir)
# Write the temporary input fasta file, setting its basename.
basename = "psipred_temp"
if print_output:
print("- basename: ", basename)
self.pymod.build_sequence_file([element], basename, file_format="fasta", remove_indels=True, new_directory=self.pymod.psipred_dirpath)
#---------------------
# Execute PSI-BLAST. -
#---------------------
if print_output:
print("- Running PSI-BLAST with sequence", basename ,"...")
try:
self.execute_psiblast(
ncbi_dir = ncbidir,
db_path = dbpath,
query = os.path.join(self.pymod.psipred_dirpath, basename+".fasta"),
inclusion_ethresh = 0.001,
out_pssm = os.path.join(self.pymod.psipred_dirpath, basename+".chk"),
out = os.path.join(self.pymod.psipred_dirpath, basename+".blast"),
num_iterations = 3,
num_alignments = 0)
# psiblast_output = open("%s.blast" % os.path.join(self.pymod.psipred_dirpath, basename),"w")
# self.pymod.execute_subprocess(psiblast_command, new_stdout=psiblast_output)
# psiblast_output.close()
except:
if print_output:
print("- FATAL: Error whilst running psiblast - script terminated!")
raise Exception("There was an error while running PSI-BLAST, so PSIPRED cannot perform a prediction for %s." % (sequence_header))
#--------------------
# Execute chkparse. -
#--------------------
if print_output:
print("- Predicting secondary structure...")
chkdir_command = (pmos.build_commandline_path_string(os.path.join(execdir, pmos.get_exe_file_name("chkparse"))) + " " +
pmos.build_commandline_path_string("%s.chk" % os.path.join(self.pymod.psipred_dirpath, basename)))
try:
chkdir_output = open("%s.mtx" % os.path.join(self.pymod.psipred_dirpath, basename),"w")
self.pymod.execute_subprocess(chkdir_command, new_stdout=chkdir_output)
chkdir_output.close()
except:
if print_output:
print("- FATAL: Error whilst running chkdir - script terminated!")
raise Exception("No homologous sequences were found by PSI-BLAST for %s, so PSIPRED cannot perform a prediction for this sequence." % (sequence_header))
#--------------------------
# Execute PSIPRED pass 1. -
#--------------------------
psipass1_command = (pmos.build_commandline_path_string(os.path.join(execdir, pmos.get_exe_file_name("psipred"))) + " " +
pmos.build_commandline_path_string("%s.mtx" % os.path.join(self.pymod.psipred_dirpath, basename)) + " " +
pmos.build_commandline_path_string(os.path.join(datadir, "weights.dat")) + " " +
pmos.build_commandline_path_string(os.path.join(datadir, "weights.dat2")) + " " +
pmos.build_commandline_path_string(os.path.join(datadir, "weights.dat3")))
try:
psipass1_output = open("%s.ss" % os.path.join(self.pymod.psipred_dirpath, basename),"w")
self.pymod.execute_subprocess(psipass1_command, new_stdout=psipass1_output)
psipass1_output.close()
except Exception as e:
if print_output:
print("- FATAL: Error whilst running psipred 1 - script terminated!")
raise Exception("There was an error while running PSIPRED and no prediction was made for %s." % (sequence_header))
#--------------------------
# Execute PSIPRED pass 2. -
#--------------------------
psipass2_command = (pmos.build_commandline_path_string(os.path.join(execdir, pmos.get_exe_file_name("psipass2"))) + " " +
"%s 1 1.0 1.0" % pmos.build_commandline_path_string(os.path.join(datadir,"weights_p2.dat")) + " " +
pmos.build_commandline_path_string("%s.ss2" % os.path.join(self.pymod.psipred_dirpath, basename)) + " " +
pmos.build_commandline_path_string("%s.ss" % os.path.join(self.pymod.psipred_dirpath, basename)))
try:
psipass2_output = open("%s.horiz" % os.path.join(self.pymod.psipred_dirpath, basename),"w")
self.pymod.execute_subprocess(psipass2_command, new_stdout=psipass2_output)
psipass2_output.close()
except:
if print_output:
print("- FATAL: Error whilst running psipass 2 - script terminated!")
raise Exception("There was an error while running PSIPRED and no prediction was made for %s." % (sequence_header))
#--------------------------
# Clean up PSIPRED files. -
#--------------------------
if print_output:
print("- Cleaning up ...")
# Remove temporary files.
self.remove_psipred_temp_files()
# Renames the output files.
output_files_name = pmos.clean_file_name(element.my_header)
for ext in psipred_output_extensions:
os.rename(os.path.join(self.pymod.psipred_dirpath, basename+ext),
os.path.join(self.pymod.psipred_dirpath, output_files_name+ext))
if print_output:
print("- Final output files:" + output_files_name + ".ss2 " + output_files_name + ".horiz")
print("- Finished.")
#----------------------------------------------
# Parses the results from .horiz output file. -
#----------------------------------------------
results_file = open(os.path.join(self.pymod.psipred_dirpath, output_files_name+".horiz"),"r")
confs = "" # String for confidence scores of each residue.
preds = "" # String for the secondary structure elements prediction of each residue.
for l in results_file.readlines():
if l.startswith("Conf:"):
rl = l[6:66].replace(" ","").replace("\n","")
confs += rl
elif l.startswith("Pred:"):
rl = l[6:66].replace(" ","").replace("\n","")
preds += rl
results_file.close()
# Actually stores in the PyMod elements the results.
element.psipred_elements_list = []
for c, e, res in zip(confs, preds, element.get_polymer_residues()):
res.psipred_result = {"confidence": int(c), "sec-str-element": e}
return True
def remove_psipred_temp_files(self):
try:
for f in os.listdir(self.pymod.psipred_dirpath):
if not os.path.splitext(f)[1] in psipred_output_extensions:
os.remove(os.path.join(self.pymod.psipred_dirpath,f))
except:
pass
def quit_protocol(self):
self.remove_psipred_temp_files()
PyMod_protocol.quit_protocol(self)
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_protocols/structural_analysis_protocols/__init__.py | .py | 0 | 0 | null | Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_protocols/structural_analysis_protocols/dope_assessment.py | .py | 19,833 | 410 | # Copyright 2020 by Giacomo Janson. All rights reserved.
# This code is part of the PyMod package and governed by its license. Please
# see the LICENSE file that should have been included as part of this package
# or the main __init__.py file in the pymod3 folder.
"""
Module used to compute the DOPE scores (using the MODELLER package) of elements loaded in PyMod.
"""
import os
import sys
import numpy as np
from pymol import cmd
try:
import modeller
from modeller.scripts import complete_pdb
except:
pass
import pymod_lib.pymod_seq.seq_manipulation as pmsm
from pymod_lib.pymod_protocols.base_protocols import PyMod_protocol, MODELLER_common
from pymod_lib.pymod_threading import Protocol_exec_dialog
from pymod_lib.pymod_exceptions import catch_protocol_exception
from pymod_lib.pymod_gui.shared_gui_components_qt import askyesno_qt
from pymod_lib.pymod_plot.pymod_plot_qt import PyMod_plot_window_qt
###################################################################################################
# DOPE PROFILES. #
###################################################################################################
class DOPE_assessment(PyMod_protocol, MODELLER_common):
"""
Compute the DOPE (Discrete optimized protein energy) of a polypeptidic chain using MODELLER.
"""
script_file_basename = "dope_profile_script"
script_file_name = "%s.py" % script_file_basename
script_temp_output_name = "dope_profile_temp_out.txt"
protocol_name = "dope_assessment"
def additional_initialization(self):
MODELLER_common.__init__(self)
self.selected_sequences = []
self.unfiltered_dope_scores_dict = {} # Items will contain DOPE scores for ligands and water molecules.
self.dope_scores_dict = {} # Items will contain DOPE scores of only polymer residues.
self.assessed_structures_list = []
self.global_dope_scores = []
self.remove_temp_files = True
@catch_protocol_exception
def launch_from_gui(self):
"""
Called when users decide calculate DOPE of a structure loaded in PyMod.
"""
self.selected_sequences = self.pymod.get_selected_sequences() # self.get_pymod_elements(self.selected_sequences)
#-----------------------------------------------
# Checks if the DOPE profiles can be computed. -
#-----------------------------------------------
modeller_error = self.pymod.modeller.check_exception()
if modeller_error is not None:
message = "In order to compute DOPE scores of a structure, MODELLER must be installed and configured correctly. %s" % modeller_error
self.pymod.main_window.show_error_message("MODELLER Error", message)
return None
if len(self.selected_sequences) == 0:
self.pymod.main_window.show_error_message("Selection Error", "Please select at least one structure to assess.")
return None
if any([e.polymer_type == "nucleic_acid" for e in self.selected_sequences]):
self.pymod.main_window.show_error_message("Selection Error", "Can not perform DOPE assessment on nucleci acids structures.")
return None
if not self.pymod.all_sequences_have_structure(self.selected_sequences):
self.pymod.main_window.show_error_message("Selection Error", "Please select only elements that have a 3D structure currently loaded in PyMOL.")
return None
if len(self.selected_sequences) > 1:
mothers_set = set([seq.mother for seq in self.selected_sequences])
if self.pymod.root_element in mothers_set or len(mothers_set) > 1:
self.pymod.main_window.show_error_message("Selection Error", "You can assess multiple structures DOPE only if they are aligned in the same cluster.")
return None
# Ask users if they would like to color the sequences according to their DOPE values.
title = "Color Option"
message = "Would you like to color the selected sequences by their DOPE values, once they have been calculated?"
color_by_dope_choice = askyesno_qt(message=message, title=title, parent=self.pymod.get_qt_parent())
#----------------------------------------
# Initializes the MODELLER environment. -
#----------------------------------------
if self.run_modeller_internally:
with open(os.devnull, "w") as n_fh: # Silence some MODELLER output.
original_stdout = sys.stdout
sys.stdout = n_fh
env = self._initialize_env()
sys.stdout = original_stdout
else:
env = None
#------------------------------------------------------------------------------------
# Actually computes the DOPE scores of the polypeptide chains in the user selection -
# and assigns to each residue of a corresponding color according to its DOPE. -
#------------------------------------------------------------------------------------
if not self.pymod.use_protocol_threads:
self.compute_all_dopes(env=env)
self.assign_dope_items()
else:
label_text = ("Computing DOPE of %s. Please wait for the process to"
" complete..." % self.get_seq_text(self.selected_sequences, "structure"))
p_dialog = Protocol_exec_dialog(app=self.pymod.main_window, pymod=self.pymod,
function=self._launch_dope_thread,
args=(None, ), wait_start=1.25, wait_end=0.25,
title="Computing DOPE scores.",
label_text=label_text,
lock=True, # a thread with MODELLER can not exit safely.
lock_title=self.pymod.modeller_lock_title,
stdout_silence=True,
lock_message=self.pymod.modeller_lock_message)
p_dialog.exec_()
#----------------------
# Color the elements. -
#----------------------
if color_by_dope_choice:
for element in self.selected_sequences:
self.pymod.main_window.color_element_by_dope(element)
#--------------------------------
# Shows the DOPE profiles plot. -
#--------------------------------
if len(self.selected_sequences) == 1:
dope_graph_mode = "single"
elif len(self.selected_sequences) >= 2:
dope_graph_mode = "multiple"
# Prepares the data to show in the plot.
self.dope_plot_data = self.prepare_dope_plot_data(self.selected_sequences, mode=dope_graph_mode)
# Shows the plot.
self.show_plot()
#-----------------------------
# Shows an assessment table. -
#-----------------------------
column_headers = ["Structure Name", "DOPE score"]
data_array = list(zip([e.get_pymol_selector() for e in self.assessed_structures_list], self.global_dope_scores))
assessment_table_args = {"column_headers": column_headers,
# "row_headers": [m["name"] for m in a.outputs],
"data_array": data_array,
"title": "Assessment of Selected Structures",
"width": 850, "height": 420,
"sortable": True,
}
self.pymod.show_table(**assessment_table_args)
def add_element(self, pymod_element):
self.selected_sequences.append(pymod_element)
def _launch_dope_thread(self, env):
self.compute_all_dopes(env=env)
self.assign_dope_items()
def compute_all_dopes(self, env=None):
for element in self.selected_sequences:
self._compute_dope_of_element(element, env=env)
def _compute_dope_of_element(self, element, env=None):
# Prepares the input for MODELLER.
e_file_name = element.get_structure_file(strip_extension=False)
e_file_shortcut = os.path.join(self.pymod.structures_dirpath, e_file_name)
e_profile_file_shortcut = os.path.join(self.output_directory, e_file_name+".profile")
# Computes the DOPE of the 3D structure of the chain of the 'element'.
global_dope_score = self._compute_dope_of_structure_file(e_file_shortcut, e_profile_file_shortcut, env=env)
# Reads the output file produced by MODELLER with the DOPE scores of the chain of the
# 'element'.
dope_scores = self._get_dope_profile(e_profile_file_shortcut)
# Removes the temporary profile file.
if self.remove_temp_files:
os.remove(e_profile_file_shortcut)
# Stores the results.
self.unfiltered_dope_scores_dict.update({element: dope_scores})
self.assessed_structures_list.append(element)
self.global_dope_scores.append(global_dope_score)
def _compute_dope_of_structure_file(self, str_file_path, profile_file_path, env=None):
return self._compute_dope(str_file_path, profile_file_path, env=env,)
def _compute_dope(self, str_file_path, profile_file_path, env=None):
"""
Uses MODELLER to compute the DOPE of a polypeptidic chain, and ouptuts the results in
'profile_file_path'. When 'env' is set to 'None', MODELLER will be initialized. If
MODELLER has already been initialized, the its 'env' varibale can be passed in this
argument so that it is not initialized again.
"""
if env == None:
env = self._initialize_env()
modstr = complete_pdb(env, str(str_file_path))
# Assess with DOPE.
s = modeller.selection(modstr).only_std_residues() # only_het_residues, only_std_residues, only_water_residues
# Gets the DOPE score.
score = s.assess_dope(output='ENERGY_PROFILE NO_REPORT',file=str(profile_file_path), normalize_profile=True, smoothing_window=15)
return score
def _get_dope_profile(self, profile_file_name, seq=None):
"""
Read 'profile_file' into a Python list, and add gaps corresponding to the alignment
sequence 'seq'.
"""
profile_file = open(profile_file_name,"r")
vals = []
for line in profile_file.readlines():
res_three_letter_code = line[8:11]
# Read all non-comment and non-blank lines from the file:
if not line.startswith('#') and len(line) > 10:
# Initially do not exclude also water molecules (named 'TIP3') and heteroresidues
# from the graph.
spl = line.split()
vals.append(float(spl[-1]))
profile_file.close()
return vals
def assign_dope_items(self):
# Retain only the DOPE values for residues of the chain (standard and modified residues).
for chain_element in self.assessed_structures_list:
all_chain_dope_scores = self.unfiltered_dope_scores_dict[chain_element]
filtered_chain_dope_scores = []
for res, score in zip(chain_element.residues, all_chain_dope_scores):
if res.is_polymer_residue():
filtered_chain_dope_scores.append(score)
self.dope_scores_dict.update({chain_element: filtered_chain_dope_scores})
# Builds a list of all DOPE values of the residues in the selection.
ldope = []
for chain_element in self.assessed_structures_list:
ldope.extend(self.dope_scores_dict[chain_element])
# Takes the min and max values among all the selected residues.
min_value = min(ldope)
max_value = max(ldope)
# An array with the equally sapced limits generated with the list above.
bins = np.array(np.linspace(min_value, max_value, num=10))
for chain_element in self.assessed_structures_list:
# An array with all the DOPE values of a single chain in the selection.
adope = np.array(self.dope_scores_dict[chain_element])
# An array with the id of the bins where those values reside.
inds = np.digitize(adope, bins)
# Returns a list like:
# [(-0.052, 4), (-0.03, 3), (-0.04, 5), (-0.04, 6), (-0.041, 7), (-0.042, 8), (-0.043, 10), ...]
# which contains for all standard residues of a polypeptidic chain a tuple. The
# first value of the tuple is the DOPE score of that residues, the second is the id
# (going from 1 to 10) of the bin where that value resides.
dope_items = []
for dope_score, bin_id in zip(adope, inds): # zip(ldope, inds):
dope_items.append({"score": dope_score, "interval": bin_id})
# Actually assigns the DOPE score to the residues of the PyMod element.
for res, dope_item in zip(chain_element.get_polymer_residues(), dope_items):
res.dope_score = dope_item
chain_element._has_dope_scores = True
def prepare_dope_plot_data(self, selection, start_from=0, mode="single"):
"""
Takes a selection of 'PyMod_elemet' objects, takes their DOPE scores and returns the data in
a dictionary which can be supplied as an argument to the 'show_dope_plot()' in order to
display it in a plot.
"""
dope_plot_data = []
for element in selection:
# Prepares a list with the PyMOL additional data for each residue of the chain, so that
# when clicking on some point, the corresponding residue will be highlighted in PyMOL,
# and the message bar of the plot will be updated.
residues_names = [res.three_letter_code for res in element.get_polymer_residues()]
residues_pdb_positions = [res.db_index for res in element.get_polymer_residues()]
pymol_selectors = [res.get_pymol_selector() for res in element.get_polymer_residues()]
residue_additional_data = []
for r_name, r_position, r_selector in zip(residues_names, residues_pdb_positions, pymol_selectors):
residue_additional_data.append({"residue_name": r_name,
"residue_pdb_position": r_position,
"pymol_selector": r_selector,
"export_label": "%s %s"%(r_name, r_position)})
element_dope_scores = self.dope_scores_dict[element][:]
# If the sequences in the selection are aligned, adjust the profiles by inserting 'None'
# values for gap positions.
if mode == "multiple":
# Insert gaps into the profile corresponding to those in seq:
# R: seq = str(seq).replace("X","-")
ri = 0
seq = element.my_sequence
for i, res in enumerate(seq):
if res != "-":
# If the first residue is preceeded by some indels.
first_residue_with_preceeding_gaps = False
if ri == 0 and i != 0:
n_gaps = i
for gap in range(n_gaps):
element_dope_scores.insert(ri, None)
residue_additional_data.insert(ri, {"export_label": "Gap"})
ri += 1 + n_gaps
first_residue_with_preceeding_gaps = True
# Applies to the rest of residues in the sequence.
if not first_residue_with_preceeding_gaps:
n_gaps = pmsm.get_leading_gaps(seq, i)
for gap in range(n_gaps):
element_dope_scores.insert(ri+1, None)
residue_additional_data.insert(ri+1, {"export_label": "Gap"})
ri += 1 + n_gaps
# For DOPE plots of multiple chains models and templates.
for g in range(start_from):
element_dope_scores.insert(0, None)
residue_additional_data.insert(0, {None: None})
# Prepares the data.
dope_plot_data.append({"dope_scores": element_dope_scores,
"additional_data": residue_additional_data,
"label": element.compact_header})
return dope_plot_data
def show_plot(self):
show_dope_plot(self.dope_plot_data, self.pymod.get_qt_parent(), pymod=self.pymod)
class DOPE_profile_window_session:
"""
A class used to show DOPE plots. The constructor takes as first argument the output of the
'prepare_dope_plot_data' method of the 'DOPE_assessment' class.
"""
def __init__(self, dope_plot_data, parent_window, pymod=None):
self.dope_plot_data = dope_plot_data
self.parent_window = parent_window
self.pymod = pymod
def show(self):
"""
Uses the 'pymod_plot' module to show a DOPE profile.
"""
x_label_text = None
messagebar_text_on_update = None
if len(self.dope_plot_data) > 1:
x_label_text = "Alignment position"
messagebar_text_on_update_qt = "Selected: __residue_name__ __residue_pdb_position__ of __plot_name__ (alignment position: __x__), DOPE value: __y__"
else:
x_label_text = "Residue position"
messagebar_text_on_update_qt = "Selected: __residue_name__ __residue_pdb_position__ of __plot_name__, DOPE value: __y__"
cp = PyMod_plot_window_qt(self.pymod.main_window)
cp.initialize(pymod=self.pymod, title="DOPE Profile")
cp.build_plotting_area(messagebar_initial_text="Set the 'Interact on click' option to 'Yes' to click on the plot and to highlight residues in PyMOL.",
update_messagebar=True,
messagebar_text_on_update=messagebar_text_on_update_qt,
on_click_action=self._highlight_in_pymol_from_dope_plot_qt,
x_label_text=x_label_text,
y_label_text="DOPE score")
for chain_dope_data in self.dope_plot_data:
# Adds the new plot corresponding to the current chain.
x_data = list(range(1, len(chain_dope_data["dope_scores"])+1))
y_data = chain_dope_data["dope_scores"]
cp.add_plot(x_data, y_data,
label=chain_dope_data["label"],
additional_data=chain_dope_data["additional_data"])
cp.show()
def _highlight_in_pymol_from_dope_plot_qt(self, point_data):
cmd.select("pymod_selection", point_data["pymol_selector"])
cmd.center("pymod_selection")
def show_dope_plot(dope_plot_data, parent_window, pymod=None):
"""
Shortcut function to use the 'DOPE_profile_window_session' class.
"""
dpw = DOPE_profile_window_session(dope_plot_data, parent_window, pymod=pymod)
dpw.show()
def compute_dope_of_structure_file(pymod, str_file_path, profile_file_path, env=None):
"""
Quickly computes the DOPE energy of the molecules contained in a structure file.
"""
model_dope_protocol = DOPE_assessment(pymod)
dope_score = model_dope_protocol._compute_dope_of_structure_file(str_file_path, profile_file_path, env=env)
return dope_score
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_protocols/structural_analysis_protocols/secondary_structure_assignment.py | .py | 9,292 | 219 | # Copyright 2016 by Chengxin Zhang, Giacomo Janson. All rights reserved.
# This code is part of the PyMod package and governed by its license. Please
# see the LICENSE file that should have been included as part of this package
# or the main __init__.py file in the pymod3 folder.
import os
import subprocess
from pymol import cmd, stored
from pymod_lib.pymod_protocols.base_protocols import PyMod_protocol
class Secondary_structure_assignment(PyMod_protocol):
"""
Observed secondary structure assignment protocol.
"""
protocol_name = "secondary_structure_assignment"
def __init__(self, pymod, pymod_element):
PyMod_protocol.__init__(self, pymod)
self.pymod_element = pymod_element
def assign_secondary_structure(self, algorithm="ksdssp"):
if algorithm == "ksdssp":
# If ksdssp is present, use it by default.
if self.pymod.ksdssp.tool_file_exists():
self.assign_with_ksdssp()
# Otherwise use PyMOL built-in dss algorithm.
else:
self.assign_with_pymol_dss()
elif algorithm == "dss":
self.assign_with_pymol_dss()
else:
raise Exception("Unknown secondary structure assignment algorithm.")
self.pymod_element.assigned_secondary_structure = True
###############################################################################################
# Ksdssp. #
###############################################################################################
def assign_with_ksdssp(self):
# Runs ksdssp.
ksdssp_fp = self.pymod.ksdssp["exe_file_path"].get_value()
input_filepath = os.path.join(self.pymod.structures_dirpath, self.pymod_element.get_structure_file())
dssptext = self.runKSDSSP(input_filepath, ksdssp_exe=ksdssp_fp)
# Parses ksdssp's output, that is, an series of pdb format 'HELIX' and 'SHEET' record lines.
dsspout = dssptext.split("\n")
helices = set() # A set to store the sequence numbers of the residues in helical conformation.
sheets = set() # A set to store the sequence numbers of the residues in sheet conformation.
for line in dsspout:
if line.startswith("HELIX"):
new_residues_set = set(range(int(line[21:25]), int(line[33:37])+1))
helices.update(new_residues_set)
elif line.startswith("SHEET"):
new_residues_set = set(range(int(line[22:26]), int(line[33:37])+1))
sheets.update(new_residues_set)
# Assigns to the PyMod element the observed secondaey structure observed using ksdssp.
for residue in self.pymod_element.get_polymer_residues():
if residue.db_index in helices:
self.assign_sec_str_to_residue(residue, "H")
rsel = residue.get_pymol_selector()
cmd.alter(rsel,"ss='H'") # Set the residue new conformation in PyMOL.
elif residue.db_index in sheets:
self.assign_sec_str_to_residue(residue, "S")
rsel = residue.get_pymol_selector()
cmd.alter(rsel,"ss='S'") # Set the residue new conformation in PyMOL.
else:
self.assign_sec_str_to_residue(residue, "L")
rsel = residue.get_pymol_selector()
cmd.alter(rsel,"ss='L'") # Set the residue new conformation in PyMOL.
# Update in PyMOL.
cmd.rebuild()
def runKSDSSP(self, PDB_file, output_file=None, energy_cutoff=-0.5,
minimum_helix_length=3, minimum_strand_length=3,
summary_file=None, ksdssp_exe="ksdssp"):
"""Command line wrapper for ksdssp,
an implementation of the algorithm described in Wolfgang Kabsch and
Christian Sander, "Dictionary of Protein Secondary Structure: Pattern
Recognition of Hydrogen-Bonded and Geometrical Features," Biopolymers,
22, 2577-2637 (1983).
http://www.cgl.ucsf.edu/Overview/software.html#ksdssp
Example:
>>> PDB_file = "1TSR.pdb"
>>> output_file = "1TSR.ksdssp"
>>> ksdssp_cline = runKSDSSP(PDB_file, output_file)
Arguments:
PDB_file
The input Protein Data Bank (PDB) file may contain any
legal PDB records. Only ATOM records will be used. All others
are silently discarded.
output_file (default: None)
The output of ksdssp is a set of PDB HELIX and SHEET records.
If no output_file argument is given, the records will be returned
by runKSDSSP
energy_cutoff (default -0.5)
The default energy cutoff for defining hydrogen bonds as
recommended by Kabsch and Sander is -0.5 kcal/mol.
minimum_helix_length (default 3)
Normally, HELIX records for helices of length three residues or
greater are generated. This option allows the user to change the
minimum helix length.
minimum_strand_length (default 3)
Normally, SHEET records for strands of length three residues or
greater are generated. This option allows the user to change the
minimum strand length. Reducing the minimum strand length to 1 is
not recommended, as there are bridges in many structures that
confuse the algorithm for defining sheets.
summary_file (default None)
Normally, ksdssp silently discards all the hydrogen-bonding
information after generating the HELIX and SHEET records. This
option makes ksdssp print the information to a file.
ksdssp_exe (default 'ksdssp')
location of KSDSSP executable
"""
PDB_file_isfile=True
if os.path.isfile(PDB_file)==False:
# Assume PDB_file is the content of a PDB file
PDB_file_isfile=False
fp=open(".runKSDSSP.PDB_file.tmp",'w')
print(PDB_file, file=fp)
fp.close()
PDB_file=".runKSDSSP.PDB_file.tmp"
if not os.path.isfile(ksdssp_exe):
print("Warning! cannot find KSDSSP executable!")
print("Specify ksdssp_exe parameter to point to KSDSSP.")
cline=[ksdssp_exe,
"-c", str(energy_cutoff),
"-h", str(minimum_helix_length),
"-s", str(minimum_strand_length)]
if summary_file != None:
cline.append("-S")
cline.append(summary_file)
cline.append(PDB_file)
if output_file != None:
cline.append(output_file)
try:
return_code = subprocess.call(cline)
except:
return_code = ''
else:
fp=open(".runKSDSSP.std.tmp",'w')
try:
return_code = subprocess.call(cline, stdout=fp)
except:
return_code = ''
fp.close()
fp=open(".runKSDSSP.std.tmp",'r')
return_code=fp.read()
fp.close()
try:
os.remove(".runKSDSSP.std.tmp")
except:
print("Fail to remove temporary file .runKSDSSP.std.tmp")
if PDB_file_isfile==False:
try:
os.remove(".runKSDSSP.PDB_file.tmp")
except:
print("Fail to remove temporary file .runKSDSSP.PDB_file.tmp'")
return return_code
###############################################################################################
# PyMOL dss. #
###############################################################################################
def assign_with_pymol_dss(self):
"""
Uses PyMOL's DSS algorithm to assign the secondary structure to a sequence according to atom
coordinates of its PDB file.
"""
selection = "object %s and n. CA" % self.pymod_element.get_pymol_selector()
stored.resi_set = set()
stored.temp_sec_str = []
stored.pymol_info = []
stored.pymod_resi_set = set([res.db_index for res in self.pymod_element.get_polymer_residues()])
def include_sec_str_val(ca_tuple):
if not ca_tuple[1] in stored.resi_set and ca_tuple[1] in stored.pymod_resi_set:
stored.temp_sec_str.append(ca_tuple[0])
stored.resi_set.add(ca_tuple[1])
stored.pymol_info.append(ca_tuple)
stored.include_val = include_sec_str_val
cmd.iterate(selection, "stored.include_val((ss, resv))")
sec_str_results = list(stored.temp_sec_str)
if not (len(sec_str_results) == len(self.pymod_element.get_polymer_residues())):
# raise Exception("Error in secondary structure assignment by PyMOL dss.")
pass # TODO.
list(map(lambda t: self.assign_sec_str_to_residue(t[0], t[1]), list(zip(self.pymod_element.get_polymer_residues(), sec_str_results))))
def assign_sec_str_to_residue(self, res, ssr):
res.secondary_structure = ssr
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_protocols/structural_analysis_protocols/_base_structural_analysis.py | .py | 3,895 | 99 | # Copyright 2020 by Giacomo Janson. All rights reserved.
# This code is part of the PyMod package and governed by its license. Please
# see the LICENSE file that should have been included as part of this package
# or the main __init__.py file in the pymod3 folder.
"""
Common functions and classes for the structural analysis protocols in PyMod.
"""
import math
import numpy as np
from pymol import cmd
class Structural_analysis_mixin:
"""
Mixin class used in the 'Contact Map' and 'Structural Divergence Plot' protocols.
"""
def check_protein_selection(self, error_title="Selection Error"):
if any([e.polymer_type == "nucleic_acid" for e in self.target_sequences]):
self.pymod.main_window.show_error_message(error_title,
"Can not perform the analysis for nucleic acids structures.")
return False
return True
def check_multiple_selection(self, error_title="Selection Error"):
# Check that all elements are currently aligned.
if not all([e.is_child() for e in self.target_sequences]):
self.pymod.main_window.show_error_message(error_title,
"Not all the selected elements are currently in an alignment.")
return False
# Check that all elements are currently in the same alignment.
if len(set([e.mother.unique_index for e in self.target_sequences])) != 1:
self.pymod.main_window.show_error_message(error_title,
"Not all the selected elements are currently in the same alignment.")
return False
# Check that all elements have a structure loaded in PyMod.
if not all([e.has_structure() for e in self.target_sequences]):
self.pymod.main_window.show_error_message(error_title,
"Please select only elements having a 3D structure loaded in PyMOL.")
return False
# Check the alignment length.
if len(set([len(element.my_sequence) for element in self.target_sequences])) != 1:
self.pymod.main_window.show_error_message(error_title,
("Alignment error: the selected elements do not have aligned sequences of"
" the same length. Try to align the elements again or to modify the alignment."))
return False
return True
def _get_sda_data(self, pymod_element, interaction_center="ca"):
"""
This method takes a 'pymod_element' as argument and returns two dictionaries.
'ali_seq_dict' associates the alignment ids to the corresponding PyMod residues.
'res_dict' associates PyMod residues to the atomic coordinates of the corresponding
interaction center (specified in the 'interaction_center' argument) and their PyMOL selector.
"""
rc = 0
ali_seq_dict = {}
residues = pymod_element.get_polymer_residues()
for ali_pos, p in enumerate(pymod_element.my_sequence):
if p != "-":
ali_seq_dict[ali_pos] = residues[rc]
rc += 1
residues, coords_array, selectors = self.get_coords_array(pymod_element, interaction_center)
res_dict = dict([(res, (c, s)) for (res, c, s) in zip(residues, coords_array, selectors)])
return ali_seq_dict, res_dict
def _get_res(self, ali_pos, ali_seq_dict):
try:
return ali_seq_dict[ali_pos]
except KeyError:
return None
def _get_coords(self, res, res_dict):
try:
return res_dict[res][0]
except KeyError:
return None
def _get_selector(self, res, res_dict):
try:
return res_dict[res][1]
except KeyError:
return None
def get_distance(coords_1, coords_2):
return math.sqrt((coords_1[0]-coords_2[0])**2 + (coords_1[1]-coords_2[1])**2 + (coords_1[2]-coords_2[2])**2)
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_protocols/structural_analysis_protocols/ramachandran_plot.py | .py | 33,596 | 789 | # Copyright 2016 by Chengxin Zhang, Giacomo Janson. All rights reserved.
# This code is part of the PyMod package and governed by its license. Please
# see the LICENSE file that should have been included as part of this package
# or the main __init__.py file in the pymod3 folder.
import os
import math
import time
import warnings
import pymod_lib.pymod_seq.seq_manipulation as pmsm
from pymod_lib.pymod_protocols.base_protocols import PyMod_protocol
from pymod_lib.pymod_vars import prot_standard_one_letter, prot_standard_three_letters
class Ramachandran_plot(PyMod_protocol):
protocol_name = "ramachandran_plot"
def __init__(self, pymod, target_sequences=None):
PyMod_protocol.__init__(self, pymod)
self.target_sequences = self.get_pymod_elements(target_sequences)
def launch_from_gui(self):
"""
PROCHEK style Ramachandran Plot.
"""
if not len(self.target_sequences) == 1 or not self.target_sequences[0].has_structure():
self.pymod.main_window.show_error_message("Selection Error", "Please select one structure to display its Ramachandran Plot.")
return None
if True in [e.polymer_type == "nucleic_acid" for e in self.target_sequences]:
self.pymod.main_window.show_error_message("Selection Error", "Can not build a Ramachandran plot for nucleic acids structures.")
return None
if not len(str(self.target_sequences[0].my_sequence).replace('-','')):
self.pymod.main_window.show_error_message("Selection Error", "No residue for Ramachandran Plot generation")
return None
self.target_sequence = self.target_sequences[0]
self.title = self.target_sequence.my_header
self.PDB_file = [self.target_sequence.get_structure_file(basename_only=False)]
# Show an options window to choose kind of aa to plot.
self.options_window = Ramachandran_plot_options_window_qt(
parent=self.pymod.main_window,
protocol=self,
title="Ramachandran Plot Options",
upper_frame_title="Options for Ramachandran Plot",
submit_command=self.options_window_state)
self.options_window.show()
def options_window_state(self):
#----------------
# Checks input. -
#----------------
aa_list = None
if self.options_window.get_aa_selection_mode() == "single":
aa_list = ''
for aa in prot_standard_one_letter:
if self.options_window.aa_checkbutton[aa].isChecked():
aa_list += aa
if aa_list:
self.title += " (Amino Acids: " + aa_list + ")"
else:
self.pymod.main_window.show_error_message("Selection Error",
"No amino acids for Ramachandran Plot generation. Please select some amino acids.")
return
self.options_window.destroy()
time.sleep(0.25)
#---------------------------------------------------------------------
# Extract the data from the 3D structures. This is performed here in -
# order to quit the protocol if something goes wrong. -
#---------------------------------------------------------------------
self.input_filepath = self.target_sequence.get_structure_file(basename_only=False)
PDB_file = self.input_filepath
if isinstance(PDB_file, str):
PDB_file = [PDB_file]
# Parses the PDB structure and gets the phi and psi angles.
residues_tags = []
try:
for structure_idx, filepath in enumerate(PDB_file):
structure = PDB.PDBParser(QUIET=True).get_structure("structure_%s" % structure_idx, filepath)
for model in structure:
for chain in model:
polypeptides = PDB.CaPPBuilder().build_peptides(chain)
for poly_idx,poly in enumerate(polypeptides):
phi_psi = poly.get_phi_psi_list()
for res_idx, residue in enumerate(poly):
residue_tags = {}
if aa_list != None and not code_standard[residue.resname] in aa_list:
continue
if not residue.resname in code_standard:
continue
phi, psi = phi_psi[res_idx]
if not (phi and psi):
residue_tags["region"] = "end_res"
residues_tags.append(residue_tags)
continue
het, resseq, icode = residue.id
phi_str = "%.2f" % (phi/math.pi*180)
psi_str = "%.2f" % (psi/math.pi*180)
# key = residue.resname + str(resseq)
residue_tags.update({"resname": residue.resname,
"position": str(resseq),
"phi": phi, "psi": psi,
"phi_str": phi_str, "psi_str": psi_str})
# Glycines.
if residue.resname == "GLY":
residue_tags["region"] = "gly"
# Prolines.
elif residue.resname == "PRO":
residue_tags["region"] = "pro"
# Other residues.
else:
region = procheck[int(18-psi/math.pi*18)][int(phi/math.pi*18+18)]
residue_tags["region"] = region
residues_tags.append(residue_tags)
except Exception as e:
title = "Error"
message = ("The Ramachandran plot could not be computed beacause of the"
" following error: %s" % str(e))
self.pymod.main_window.show_error_message(title, message)
return None
#------------------------
# Show the plot window. -
#------------------------
ramachandra_plot_window = Ramachandran_plot_window_qt(self.pymod.main_window)
ramachandra_plot_window.initialize_plot(pymod=self.pymod,
target_element=self.target_sequence,
residues_tags=residues_tags,
plot_title=self.title,
aa_list=aa_list)
ramachandra_plot_window.show()
###################################################################################################
# GUI. #
###################################################################################################
from pymol.Qt import QtWidgets, QtCore, QtGui
from pymod_lib.pymod_gui.shared_gui_components_qt import (PyMod_protocol_window_qt,
PyMod_entryfield_qt,
PyMod_radioselect_qt,
PyMod_combobox_qt,
small_font_style)
class Ramachandran_plot_options_window_qt(PyMod_protocol_window_qt):
def build_protocol_middle_frame(self):
"""
Allow to choose between plotting all amino acids types or only a subset
of them.
"""
# Radioselect.
aa_select_choices = ("Use all amino acids", "Select amino acids types")
aa_select_choices_values = ["all", "single"]
self.aa_select_choices_dict = dict([(k, v) for (k, v) in zip(aa_select_choices, aa_select_choices_values)])
self.aa_select_rds = PyMod_radioselect_qt(label_text="Select Amino Acids",
buttons=aa_select_choices)
self.aa_select_rds.setvalue(aa_select_choices[0])
self.aa_select_rds.buttons_dict[aa_select_choices[0]].clicked.connect(self.hide_select_single_aa_frame)
self.aa_select_rds.buttons_dict[aa_select_choices[1]].clicked.connect(self.show_select_single_aa_frame)
self.middle_formlayout.add_widget_to_align(self.aa_select_rds)
# Checkboxes for selecting single amino acids.
self.aa_select_grid_layout = QtWidgets.QGridLayout()
self.aa_select_rds.input.addLayout(self.aa_select_grid_layout)
self.aa_checkbutton = {}
self.aa_freq_dict = {}
self.aa_checkbutton_list = []
for i, aa in enumerate(prot_standard_one_letter):
# Get the number of aa in the sequence.
aa_freq = str(self.protocol.target_sequence.my_sequence).count(aa)
self.aa_freq_dict[aa] = aa_freq
# Build a checkbox for the aa.
checkbox = QtWidgets.QCheckBox(pmsm.one2three(aa) + " (" + str(aa_freq) + ")")
checkbox.setEnabled(False)
self.aa_select_grid_layout.addWidget(checkbox, int(i%10), int(i/10))
self.aa_checkbutton[aa] = checkbox
self.aa_checkbutton_list.append(checkbox)
self.aa_select_grid_layout.setAlignment(QtCore.Qt.AlignLeft)
self.middle_formlayout.set_input_widgets_width("auto", padding=40)
def show_select_single_aa_frame(self):
for aa in prot_standard_one_letter:
# Only enable selection of aa present in protein sequence.
if self.aa_freq_dict[aa] != 0:
self.aa_checkbutton[aa].setEnabled(True)
def hide_select_single_aa_frame(self):
for checkbox in self.aa_checkbutton_list:
checkbox.setEnabled(False)
def get_aa_selection_mode(self):
return self.aa_select_choices_dict[self.aa_select_rds.getvalue()]
###################################################################################################
# INTERACTIVE RAMACHANDRAN PLOT. #
###################################################################################################
from Bio import PDB
from pymol import cmd
# Global variable for Ramachandran Plots
procheck=[ # 4 regions defined by PROCHECK
"AFFFFFFFFFFAAAGGDDDDDGGGGGDDDDDGGGGA", # F - Favored
"AFFFFFFFFFFFAAAGGDDDDDDDDDDDDDDGGGAA", # A - Additional allowed
"AFFFFFFFFFFFAAAGGGGDDDDDDDDDDDDGGAAA", # G - Generously allowed
"AAFFFFFFFFFFFAAAAGGDDDDDDDDDDDDGGGAA", # D - Disallowed
"AAFFFFFFFFFFFFAAGGGDDDDDDDDDDDDGGGGA",
"AAFFFFFFFFFFFAAAGGGDDDDDDDDDDDDDGGGA",
"AAAFFFFFFFFFAAAAGGGDDDGGGGGGDDDDDGGA",
"AAAAFFFFFFFAAAAAAGGGGGGGGGGGDDDDDGGA",
"AAAAAFAAFAAAAAAAAGGGGGGGAAGGDDDDDGGA",
"AAAAAAAAAAAAAAGGGGGGGAAAAGGGDDDDDGGG",
"AAAAAAAAAAAAGGGGGGGGGAAAAGGGDDDDDGGG",
"GAAAAAAAAAAAAGGDDDDGGGAAAGGGGDDDDGGG",
"GGAAAAAAAAAAAGGDDDDGGAAAAAAGGDDDDGGG",
"GGAAAAAAAAAAGGGDDDDGGAAFAAGGGDDDDGGG",
"GAAAAAAAAAAAGGGDDDDGGGAFFAGGGDDDDGGG",
"GAAAAAAFAAAAAGGGDDDGGGAAAAAGGDDDDGGG",
"GAAAAAFFFFAAAGGGGDDDGGGAAAGGGDDDDGGG",
"GAAAAAFFFFFAAAGGGDDDGGGGAAAGGDDDDGGG",
"GAAAAFFFFFFFAAAGGGDDGGGAGAAGGDDDDGGG",
"GAAAAAFFFFFFFAAGGGGDGGGGGGGGGDDDDGGG",
"GGAAAAFFFFFFFFAAGGGDGGGGGGGGGDDDDGGG",
"GGAAAAAFFFFFFFAAAGGGDDDDDDDDDDDDDGGG",
"GGGAAAAAFFFFFFFAAGGGDDDDDDDDDDDDDGGG",
"GAAAAAAAAFFFFFFAAAGGGDDDDDDDDDDDDGGG",
"AAGAAAAAAAAFFFFAAAGGGDDDDDDDDDDDDGGG",
"GGGAAAAAAAAAAAAAAAAGGDDDDDDDDDDDDGGG",
"GGGGGAAAAAAAAAAAAAGGGDDDDDDDDDDDDGGG",
"DGGGGAAAAAAAAAAGGGGGGDDDDDDDDDDDDDDD",
"DDDGGGGGGGGAGGGGGGGGDDDDDDDDDDDDDDDD",
"DDDGGGGAAGGGGGGGGDDDDDDDDDDDDDDDDDDD",
"GGGGGAAGGGGGGGDDDDDDDGGGGGDDDDDDDDDD",
"GGGGGGAAAAGGGGDDDDDDDGGGGGDDDDDDDDDD",
"GAAAGAAAAAGGGGGDDDDDDGGAGGGDDDDDDDDD",
"GAAAAAAAAAAGGGGDDDDDDGGAGGGDDDDDDGGG",
"GAAAAAAAAAAAAGGDDDDDDGGAAGGDDDDDDGGG",
"AAAAAAAAAAAAAGGDDDDDDGGGGGGDDDDDDGGA"]
code_standard = { # dict for 20 standard amino acids
'ALA':'A', 'VAL':'V', 'PHE':'F', 'PRO':'P', 'MET':'M',
'ILE':'I', 'LEU':'L', 'ASP':'D', 'GLU':'E', 'LYS':'K',
'ARG':'R', 'SER':'S', 'THR':'T', 'TYR':'Y', 'HIS':'H',
'CYS':'C', 'ASN':'N', 'GLN':'Q', 'TRP':'W', 'GLY':'G'}
class Ramachandran_plot_items_mixin:
def common_initialization(self, i, j, tags, parent_window, pen, brush):
self.parent_window = parent_window
self.plot_tags = tags
self.set_paiting_tools(pen, brush)
self.setAcceptHoverEvents(True)
self.i_val = i
self.j_val = j
def set_paiting_tools(self, pen, brush):
if pen is None:
pen = self.parent_window.default_pen
self.setPen(pen)
if brush is None:
brush = self.parent_window.default_brush
self.original_brush = brush
self.setBrush(brush)
def hoverEnterEvent(self, e):
self.parent_window.canvas_plot_move_event(self.plot_tags)
self.setBrush(self.parent_window.highlight_brush)
def hoverLeaveEvent(self, e):
self.setBrush(self.original_brush)
self.parent_window.canvas_plot_title_reset(self.plot_tags, "resname")
def highlight_region(self):
self.setBrush(self.parent_window.highlight_region_brush)
def inactivate_region(self):
self.setBrush(self.original_brush)
def mousePressEvent(self, e):
if e.button() == QtCore.Qt.LeftButton:
self.parent_window.click_residue_with_left_button(self.plot_tags)
elif e.button() == QtCore.Qt.MiddleButton:
self.parent_window.click_residue_with_middle_button(self.plot_tags)
elif e.button() == QtCore.Qt.RightButton:
self.parent_window.click_residue_with_right_button(self.plot_tags)
def mouseReleaseEvent(self, e):
if e.button() == QtCore.Qt.LeftButton:
self.parent_window.release_residue_with_left_button(self.plot_tags)
class Ramachandran_plot_triangle(QtWidgets.QGraphicsPolygonItem, Ramachandran_plot_items_mixin):
def __init__(self, i, j, tags, mark_size, parent_window, pen=None, brush=None):
# Build the polygon object representing a triangle.
with warnings.catch_warnings():
warnings.simplefilter("ignore")
polygon = QtGui.QPolygonF([QtCore.QPointF(i, j-2*mark_size),
QtCore.QPointF(i-1.7*mark_size, j+mark_size),
QtCore.QPointF(i+1.7*mark_size, j+mark_size)])
# Initialize.
super(Ramachandran_plot_triangle, self).__init__(polygon)
self.common_initialization(i, j, tags, parent_window, pen, brush)
class Ramachandran_plot_rectangle(QtWidgets.QGraphicsRectItem, Ramachandran_plot_items_mixin):
def __init__(self, i, j, tags, mark_size, parent_window, pen=None, brush=None):
super(Ramachandran_plot_rectangle, self).__init__(i-mark_size, j-mark_size, mark_size*2, mark_size*2)
self.common_initialization(i, j, tags, parent_window, pen, brush)
class Ramachandran_plot_circle(QtWidgets.QGraphicsEllipseItem, Ramachandran_plot_items_mixin):
def __init__(self, i, j, tags, mark_size, parent_window, pen=None, brush=None):
super(Ramachandran_plot_circle, self).__init__(i-mark_size, j-mark_size, mark_size*2, mark_size*2)
self.common_initialization(i, j, tags, parent_window, pen, brush)
class Ramachandran_plot_info_labels(QtWidgets.QLabel):
def __init__(self, text, message, region, active, parent_window):
super(Ramachandran_plot_info_labels, self).__init__(text)
self.message_to_show = message
self.plot_region = region
self.activate_plot = active
self.parent_window = parent_window
def enterEvent(self, e):
if not self.activate_plot:
return None
self.parent_window.info_label_move_event(self.plot_region, self.message_to_show)
def leaveEvent(self, e):
if not self.activate_plot:
return None
self.parent_window.info_label_title_reset(self.plot_region)
class Ramachandran_plot_window_qt(QtWidgets.QMainWindow):
"""
PyQt class for a window containing a PROCHECK style Ramachandran plot.
Biopython is required.
"""
is_pymod_window = True
def initialize_plot(self, pymod, target_element, residues_tags, plot_title, aa_list):
self.pymod = pymod
self.target_element = target_element
self.residues_tags = residues_tags
self.plot_title = plot_title
self.setWindowTitle("%s Ramachandran Plot" % self.target_element.my_header)
self.aa_list = aa_list
# Frame of the window containing a row for some control buttons, a row for
# the plot and a row for a messagebar.
self.plot_frame = QtWidgets.QWidget()
self.plot_frame_layout = QtWidgets.QGridLayout()
self.plot_frame.setLayout(self.plot_frame_layout)
self.setCentralWidget(self.plot_frame)
# Control frame.
self.controls_frame = QtWidgets.QWidget()
self.controls_frame_layout = QtWidgets.QGridLayout()
self.controls_frame.setLayout(self.controls_frame_layout)
self.plot_frame_layout.addWidget(self.controls_frame, 0, 0)
self.scale_factor = 0
self.scale_down_button = QtWidgets.QPushButton("Zoom out")
try:
self.scale_down_button.setIcon(QtGui.QIcon.fromTheme("go-down"))
except:
pass
self.scale_down_button.clicked.connect(lambda a=None: self.scale_plot_down())
self.controls_frame_layout.addWidget(self.scale_down_button, 0, 0)
self.scale_up_button = QtWidgets.QPushButton("Zoom in")
try:
self.scale_up_button.setIcon(QtGui.QIcon.fromTheme("go-up"))
except:
pass
self.scale_up_button.clicked.connect(lambda a=None: self.scale_plot_up())
self.controls_frame_layout.addWidget(self.scale_up_button, 0, 1)
self.controls_frame_layout.setAlignment(QtCore.Qt.AlignLeft)
# Frame containing the plot (with a scrollbar).
self.canvas_plot_frame = QtWidgets.QWidget()
self.canvas_plot_frame.setStyleSheet("background-color: white")
self.canvas_plot_frame_layout = QtWidgets.QGridLayout()
self.canvas_plot_frame.setLayout(self.canvas_plot_frame_layout)
self.canvas_plot_scrollarea = QtWidgets.QScrollArea()
self.canvas_plot_scrollarea.setWidgetResizable(True)
self.canvas_plot_scrollarea.setWidget(self.canvas_plot_frame)
self.plot_frame_layout.addWidget(self.canvas_plot_scrollarea, 1, 0)
self.default_pen = QtGui.QPen(QtGui.QColor(0, 0, 0, 255), 1)
self.default_brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 230))
self.highlight_brush = QtGui.QBrush(QtGui.QColor(255, 0, 255))
self.highlight_region_brush = QtGui.QBrush(QtGui.QColor(0, 255, 255))
# Builds the scene where to draw the Ramachandran plot.
self.canvas_plot_scene = QtWidgets.QGraphicsScene()
# Builds the graphics view containing the scene above.
self.canvas_plot_view = QtWidgets.QGraphicsView(self.canvas_plot_scene)
self.canvas_plot_frame_layout.addWidget(self.canvas_plot_view)
# A bottom frame fo the window, containing some buttons to interact with the graph.
self.message_frame = QtWidgets.QFrame()
self.message_frame_layout = QtWidgets.QFormLayout()
self.message_frame.setLayout(self.message_frame_layout)
self.plot_frame_layout.addWidget(self.message_frame, 1, 1)
# Label to show which residue/position pair is currently being hovered by the mouse pointer.
self.view_label_prefix = "Showing: "
self.default_message = "Hover dots to color residues of the same type" # Hover over title.
self.message_label = QtWidgets.QLabel(self.default_message)
self.message_label.setStyleSheet(small_font_style)
self.message_frame_layout.addRow(self.message_label)
# Actually draws the plot.
self.draw_plot()
# Shows some data about the type of residues and their dihedral angles.
self.regions_labels_dict = {}
tot_regular_res = float(self.residues_count["T"])
label_params = [("F", "Residues in the most favoured regions", "residues in most favoured regions", True, True),
("A", "Residues in additional allowed regions", "residues in additional allowed regions", True, True),
("G", "Residues in generously allowed regions", "residues in generously allowed regions", True, True),
("D", "Residues in disallowed regions", "residues in disallowed regions", True, True),
("T", "Non-gly and non-pro residues (circles)", "non-glycine and non-proline residues", True, True),
("end_res", "End-residues", "end residues", False, False),
("gly", "Gly residues (triangles)", "glycine residues", True, False),
("pro", "Pro residues (squares)", "proline residues", True, False),
("total", "Total number of residues", "all residues", True, False)]
for region, label, message, active, use_ratio in label_params:
region_label = Ramachandran_plot_info_labels(label, message, region, active, self)
region_label.setStyleSheet(small_font_style)
if use_ratio:
text = "%s (%s%%)" % (self.residues_count[region], round(self.residues_count[region]/tot_regular_res*100, 1))
else:
text = str(self.residues_count[region])
region_label_count = QtWidgets.QLabel(text)
region_label_count.setStyleSheet(small_font_style)
self.message_frame_layout.addRow(region_label, region_label_count)
self.regions_labels_dict[region] = {"info": region_label, "data": region_label_count}
def draw_plot(self):
self.pymol_selection = self.target_element.get_pymol_selector()
imin = 60
jmin = 40
imax = imin+360
jmax = jmin+360
mark_size = 2
xticks_num = [-180,-135,-90,-45,0,45,90,135,180]
yticks_num = [-180,-135,-90,-45,0,45,90,135,180]
height = 10
width = 10
#--------------------------------------------------------------
# Draws the background and the axes of the Ramachandran plot. -
#--------------------------------------------------------------
# Draws the background of the Ramachandran plot.
line_pen = QtGui.QPen(QtGui.QColor(0, 0, 0, 255), 1)
for ii in range(0,36):
for jj in range(0,36):
region = procheck[ii][jj]
color = "#ffffff" #[ 1.0, 1.0, 1.0]
if region == 'F':
color = "#f20000" #[.949, 0.0, 0.0]
elif region == 'A':
color = "#f2f200" #[.949,.949, 0.0]
elif region == 'G':
color = "#f2f2a9" #[.949,.949,.663]
qcolor = QtGui.QColor(0, 0, 0)
qcolor.setNamedColor(color)
brush = QtGui.QBrush(qcolor)
# edgecolor = color
left = imin + jj*width
top = jmin + ii*height
# Actually draws the backgound.
self.canvas_plot_scene.addRect(left, top, width, height, qcolor, brush)
# Draw the countours of the various background regions.
if ii: # top border
region_prev = procheck[ii-1][jj]
if ((region_prev=='F' and region!='F' ) or
(region_prev=='A' and region in "GD") or
(region_prev=='G' and region=='D' )):
self.canvas_plot_scene.addLine(left-.5, top, left+width+.5, top, line_pen)
if jj: # left border
region_prev=procheck[ii][jj-1]
if ((region_prev=='F' and region!='F' ) or
(region_prev=='A' and region in "GD") or
(region_prev=='G' and region=='D' )):
self.canvas_plot_scene.addLine(left, top-.5, left, top+height+.5, line_pen)
# Create axis lines.
def add_text_to_canvas(x, y, text, anchor=None, font_color="black", font_size=6, html_font_size=10):
_text = str(text)
text_item = self.canvas_plot_scene.addText(_text)
w = text_item.boundingRect().width()
h = text_item.boundingRect().height()
text_item.setPos(int(x-w/2.5), int(y-h/2.5))
text_item.setFont(QtGui.QFont(text_item.font().family(), font_size))
imid = (imin+imax)/2 # midpoint of X-axis
jmid = (jmin+jmax)/2 # midpoint of Y-axis
self.canvas_plot_scene.addLine(imin, jmax, imax, jmax)
self.canvas_plot_scene.addLine(imin, jmin, imin, jmax)
self.canvas_plot_scene.addLine(imin, jmin, imax, jmin)
self.canvas_plot_scene.addLine(imax, jmin, imax, jmax)
self.canvas_plot_scene.addLine(imid, jmin, imid, jmax)
self.canvas_plot_scene.addLine(imin, jmid, imax, jmid)
# Create tick marks and labels
x_x_offset = 0 # 20
x_y_offset = 14 # 5
tic = imin
for label in xticks_num:
self.canvas_plot_scene.addLine(tic, jmax+5, tic, jmax)
add_text_to_canvas(tic+x_x_offset, jmax+x_y_offset, label)
if len(xticks_num)!=1:
tic+=(imax-imin)/(len(xticks_num)-1)
tic = jmax
y_x_offset = 20 # 40
y_y_offset = 0 # 10
for label in yticks_num:
self.canvas_plot_scene.addLine(imin , tic, imin-5, tic)
add_text_to_canvas(imin-y_x_offset, tic-y_y_offset, text=label)
if len(yticks_num)!=1:
tic-=(jmax-jmin)/(len(yticks_num)-1)
# Phi label.
add_text_to_canvas((imin+imax)/2+5, jmax+35, text="\u03D5 (degrees)")
# Psi label.
add_text_to_canvas(imin/2-10, (jmin+jmax)/2, text="\u03A8")
#---------------------------------------------------------
# Actually plots the data for each residue on the scene. -
#---------------------------------------------------------
# Parses the PDB structure and gets the phi and psi angles.
self.residues_count = {"F": 0, # Favored
"A": 0, # Additional allowed
"G": 0, # Generously allowed
"D": 0, # Disallowed
"gly": 0, # Glycines
"pro": 0, # Prolines
"end_res": 0, # end-residues
"total": 0, # total number of residues
}
self.regions_items_dict = {k: [] for k in self.residues_count}
self.residues_items_dict = {k: [] for k in prot_standard_three_letters}
for res_idx, res_tags in enumerate(self.residues_tags):
self.residues_count["total"] += 1
if res_tags["region"] == "end_res":
self.residues_count["end_res"] +=1
continue
i = imin+(180+res_tags["phi"]/math.pi*180)
j = jmin+(180-res_tags["psi"]/math.pi*180)
# Glycines.
if res_tags["resname"] == "GLY":
item = Ramachandran_plot_triangle(i=i, j=j, tags=res_tags,
mark_size=mark_size,
parent_window=self)
self.canvas_plot_scene.addItem(item)
self.regions_items_dict["gly"].append(item)
self.residues_count["gly"] += 1
# Prolines.
elif res_tags["resname"] == "PRO":
item = Ramachandran_plot_rectangle(i=i, j=j, tags=res_tags,
mark_size=mark_size,
parent_window=self)
self.canvas_plot_scene.addItem(item)
self.regions_items_dict["pro"].append(item)
self.residues_count["pro"] += 1
# Other residues.
else:
item = Ramachandran_plot_circle(i=i, j=j, tags=res_tags,
mark_size=mark_size,
parent_window=self)
self.canvas_plot_scene.addItem(item)
if res_tags["region"] in self.residues_count:
self.regions_items_dict[res_tags["region"]].append(item)
self.residues_count[res_tags["region"]] += 1
if res_tags["resname"] in self.residues_items_dict:
self.residues_items_dict[res_tags["resname"]].append(item)
self.residues_count["T"] = sum([self.residues_count[k] for k in ("F", "A", "G", "D")])
self.regions_items_dict["T"] = [i for k in ("F", "A", "G", "D") for i in self.regions_items_dict[k]]
def canvas_plot_move_event(self, residue_tags):
residue_message = "%s %s (phi: %s, psi: %s)" % (residue_tags["resname"], residue_tags["position"],
residue_tags["phi_str"], residue_tags["psi_str"])
self.message_label.setText(self.view_label_prefix + residue_message)
self._activate_residues(residue_tags["resname"])
def canvas_plot_title_reset(self, residue_tags, group): # mouse leaves title
self.message_label.setText(self.default_message)
if group == "resname":
self._inactivate_residues(residue_tags["resname"])
elif group == "region":
self._inactivate_region(residue_tags["region"])
else:
raise KeyError("Unknown 'group': %s" % group)
def info_label_move_event(self, region, message):
self.message_label.setText(self.view_label_prefix + message)
self._activate_region(region)
def info_label_title_reset(self, region):
self.message_label.setText(self.default_message)
self._inactivate_region(region)
def _activate_region(self, region):
if region in self.regions_items_dict:
for item in self.regions_items_dict[region]:
item.highlight_region()
def _inactivate_region(self, region):
if region in self.regions_items_dict:
for item in self.regions_items_dict[region]:
item.inactivate_region()
def _activate_residues(self, resname):
if resname in self.residues_items_dict:
for item in self.residues_items_dict[resname]:
item.highlight_region()
def _inactivate_residues(self, resname):
if resname in self.residues_items_dict:
for item in self.residues_items_dict[resname]:
item.inactivate_region()
def click_residue_with_left_button(self, residue_tags): # show residue in sticks
sel = self.pymol_selection + " and resn " + residue_tags["resname"] + " and resi " + residue_tags["position"]
try:
cmd.show("sticks", sel)
except:
pass
def release_residue_with_left_button(self, residue_tags): # back to cartoon
sel = self.pymol_selection + " and resn " + residue_tags["resname"] + " and resi " + residue_tags["position"]
try:
cmd.hide("sticks", sel)
cmd.hide("lines", sel)
cmd.delete("pymod_selection")
except:
pass
def click_residue_with_middle_button(self, residue_tags): # center & select residue
sel = self.pymol_selection + " and resn " + residue_tags["resname"] + " and resi " + residue_tags["position"]
try:
cmd.center(sel)
cmd.select("pymod_selection", sel)
cmd.refresh() # causes the scene to be refresh as soon as it is safe to do so.
except:
pass
def click_residue_with_right_button(self, residue_tags): # center residue
sel = self.pymol_selection + " and resn " + residue_tags["resname"] + " and resi " + residue_tags["position"]
try:
cmd.center(sel, animate=1)
cmd.delete("pymod_selection")
cmd.refresh() # causes the scene to be refresh as soon as it is safe to do so.
except:
pass
def scale_plot_up(self):
if self.scale_factor > 10:
return None
self.canvas_plot_view.scale(1.25, 1.25)
self.scale_factor += 1
if self.scale_factor > 10:
self.scale_up_button.setEnabled(False)
self.scale_down_button.setEnabled(True)
def scale_plot_down(self):
if self.scale_factor < -10:
return None
self.canvas_plot_view.scale(0.8, 0.8)
self.scale_factor -=1
if self.scale_factor < -10:
self.scale_down_button.setEnabled(False)
self.scale_up_button.setEnabled(True)
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_protocols/structural_analysis_protocols/contact_map_analysis.py | .py | 34,486 | 859 | # Copyright 2020 by Giacomo Janson. All rights reserved.
# This code is part of the PyMod package and governed by its license. Please
# see the LICENSE file that should have been included as part of this package
# or the main __init__.py file in the pymod3 folder.
"""
Module implementing a protocol for building and analyzing contact and distance maps in PyMod.
"""
import os
import math
import warnings
import numpy as np
from pymol import cmd
from pymol.Qt import QtWidgets, QtGui, QtCore
from pymod_lib.pymod_protocols.base_protocols import PyMod_protocol
from pymod_lib.pymod_gui.shared_gui_components_qt import (PyMod_protocol_window_qt,
PyMod_entryfield_qt,
PyMod_radioselect_qt,
PyMod_combobox_qt)
from pymod_lib.pymod_protocols.structural_analysis_protocols._base_structural_analysis import get_distance
from pymod_lib.pymod_protocols.structural_analysis_protocols._base_structural_analysis import Structural_analysis_mixin
from pymod_lib.pymod_vars import viridis_colors
from pymod_lib.pymod_threading import Protocol_exec_dialog
viridis_colors_rev = list(reversed(viridis_colors))
###################################################################################################
# Main class. #
###################################################################################################
class Contact_map_analysis(PyMod_protocol, Structural_analysis_mixin):
"""
Class for implementing in PyMod contact and distance map analyses.
"""
protocol_name = "contact_map_analysis"
def __init__(self, pymod):
PyMod_protocol.__init__(self, pymod)
self.target_sequences = self.get_pymod_elements()
def launch_from_gui(self):
"""
Checks the condition for launching a contact map analysis.
"""
error_title = "Selection Error"
# Check that the selection is not empty.
if len(self.target_sequences) == 0:
self.pymod.main_window.show_error_message(error_title,
"Please select at least one structure to display its contact map.")
return None
# Check that no nucleic acid structure has been selected.
if not self.check_protein_selection(error_title):
return None
# Check the right conditions for the protocol.
if len(self.target_sequences) == 1: # Single structure.
if not self.target_sequences[0].has_structure():
self.pymod.main_window.show_error_message(error_title,
"Please select only elements with a 3D structure loaded in PyMOL to display their contact maps.")
return None
self.target_sequence = self.target_sequences[0]
else: # Multiple structures.
# Check for multiple aligned structures in the same cluster.
if not self.check_multiple_selection(error_title):
return None
# Opens the options window.
self.contact_map_options_window = Contact_map_options_window_qt(self.pymod.main_window,
protocol=self,
title="Contact Map Options",
upper_frame_title="Options for Contact Map Analysis",
submit_command=self.contact_map_analysis_state)
self.contact_map_options_window.show()
def validate_input(self):
try:
# Feature type.
self.feature_type, self.feature_type_full_name = self.contact_map_options_window.get_feature_type()
# Interaction center.
self.interaction_center = self.contact_map_options_window.get_interaction_center()
# Distance threshold.
self.dist_threshold = self.contact_map_options_window.dist_threshold_enf.getvalue(validate=True)
# Pixel size.
self.pixel_size = 5
# Reference structure.
if len(self.target_sequences) > 1:
self.reference_element = self.target_sequences[self.contact_map_options_window.get_reference_id()]
else:
self.reference_element = self.target_sequence
except (ValueError, KeyError) as e:
return str(e)
return None
def contact_map_analysis_state(self):
#------------------------------------
# Gets the parameters from the GUI. -
#------------------------------------
input_error = self.validate_input()
if input_error is not None:
self.pymod.main_window.show_error_message("Input Error", input_error)
return None
self.contact_map_options_window.destroy()
#-------------------------------------
# Actually computes the contact map. -
#-------------------------------------
# Assign function to fill the target map.
if self.feature_type == "contact":
self.get_map_pixel = self._get_contact_val
elif self.feature_type == "distance":
self.get_map_pixel = self._get_distance_val
elif self.feature_type == "distances_difference":
self.get_map_pixel = self._get_distances_difference_val
elif self.feature_type == "distances_mean":
self.get_map_pixel = self._get_distances_mean
elif self.feature_type == "distances_std":
self.get_map_pixel = self._get_distances_std
else:
raise KeyError(self.feature_type)
if not self.pymod.use_protocol_threads:
self.compute_target_map()
else:
label_text = ("Computing %s map on %s. Please wait for the process to"
" complete..." % (self.feature_type_full_name, self.get_seq_text(self.target_sequences)))
p_dialog = Protocol_exec_dialog(app=self.pymod.main_window, pymod=self.pymod,
function=self.compute_target_map,
args=(), lock=True,
wait_start=0.25, wait_end=0.25,
title="Computing %s map" % self.feature_type_full_name,
label_text=label_text)
p_dialog.exec_()
#------------------------
# Show the contact map. -
#------------------------
# Gets the title of the window.
if self.feature_type in ("contact", "distance"):
title = "%s %s Map." % (self.target_sequence.my_header, self.feature_type_full_name[0:-1])
elif self.feature_type == "distances_difference":
title = "Distances Difference Map."
elif self.feature_type == "distances_mean":
title = "Distances Mean Map."
elif self.feature_type == "distances_std":
title = "Distances Std Map."
# Initializes the contact/distance map window.
cp = Contact_map_analysis_window_qt(self.pymod.main_window)
cp.initialize_map(pymod=self.pymod,
data_array=self.target_map,
pymod_elements=self.target_sequences,
ref_residues=self.ref_residues,
ref_selectors=self.ref_selectors,
title=title,
pixel_size=self.pixel_size,
feature_type=self.feature_type,
threshold=self.dist_threshold,
interaction_center=self.interaction_center)
cp.show()
def compute_target_map(self):
# Reference residues and selectors lists. Used to interact with the 3D structures loaded in
# PyMOL.
self.target_map = []
self.ref_residues = []
self.ref_selectors = []
#----------------------------------------------------------------------------------
# Builds the array with the contact/distance maps to show for a single structure. -
#----------------------------------------------------------------------------------
if self.feature_type in ("contact", "distance"):
# Get the coordinates of the residues.
residues, coords_array, selectors = self.get_coords_array(self.target_sequence, self.interaction_center)
self.target_map = np.zeros((len(residues), len(residues)))
for res_idx_i, res_i in enumerate(residues):
for res_idx_j, res_j in enumerate(residues):
if res_idx_i >= res_idx_j:
continue
dist = get_distance(coords_array[res_idx_i], coords_array[res_idx_j])
self.target_map[res_idx_i][res_idx_j] = self.get_map_pixel(dist)
self.target_map[res_idx_j][res_idx_i] = self.target_map[res_idx_i][res_idx_j]
self.ref_residues = residues
self.ref_selectors = selectors
#---------------------------------------------------------------------------
# Builds the array with the distance maps to show for multiple structures. -
#---------------------------------------------------------------------------
elif self.feature_type in ("distances_difference", "distances_mean", "distances_std"):
# Get the coordinates of the residues for all the structures.
ali_seq_dict_list = []
res_dict_list = []
for element in self.target_sequences:
ali_seq_dict, res_dict = self._get_sda_data(element, self.interaction_center)
ali_seq_dict_list.append(ali_seq_dict)
res_dict_list.append(res_dict)
if element is self.reference_element:
ref_ali_seq_dict = ali_seq_dict
ref_res_dict = res_dict
# Iter through all the positions of the alignment.
ali_len = len(self.target_sequences[0].my_sequence)
self.target_map = np.zeros((ali_len, ali_len))
self.target_map[:] = -1 # Diagonal elements and alignment posisions with gaps will have -1 as a value.
for ali_pos_i in range(0, ali_len):
# Get the reference residues.
ref_res = self._get_res(ali_pos_i, ref_ali_seq_dict)
ref_sel = self._get_selector(ref_res, ref_res_dict)
if ref_sel is None:
self.ref_residues.append(None)
self.ref_selectors.append(None)
else:
self.ref_residues.append(ref_res)
self.ref_selectors.append(ref_sel)
# Computes the distances for each pair of alignment columns.
for ali_pos_j in range(0, ali_len):
if ali_pos_i >= ali_pos_j:
continue
# For each alignment column get the corresponding residues and coordinates.
dist_list = []
for ali_seq_dict, res_dict in zip(ali_seq_dict_list, res_dict_list):
coords_i = self._get_coords(self._get_res(ali_pos_i, ali_seq_dict), res_dict)
if coords_i is None:
continue
coords_j = self._get_coords(self._get_res(ali_pos_j, ali_seq_dict), res_dict)
if coords_j is None:
continue
dist_list.append(get_distance(coords_i, coords_j))
if len(dist_list) > 1:
self.target_map[ali_pos_i][ali_pos_j] = self.get_map_pixel(dist_list)
self.target_map[ali_pos_j][ali_pos_i] = self.target_map[ali_pos_i][ali_pos_j]
def _get_contact_val(self, v):
"""
Binary values.
"""
return int(v <= self.dist_threshold)
def _get_distance_val(self, v):
"""
Continuous values.
"""
return v
def _get_distances_difference_val(self, v):
"""
Absolute difference bewteen two distances.
"""
if len(v) < 2:
return -1
else:
return abs(v[0]-v[1])
def _get_distances_mean(self, v):
"""
Mean between a list of distances.
"""
return get_mean(v)
def _get_distances_std(self, v):
"""
Standard deviation between a list of distances.
"""
return get_std(v)
def get_mean(v):
return sum(v)/len(v)
def get_std(v):
n = len(v)
if n == 1:
return 0
m = get_mean(v)
return math.sqrt(sum([i**2 for i in v])/n - m**2)
###################################################################################################
# GUI. #
###################################################################################################
###############################################################################
# Options window. #
###############################################################################
class Contact_map_options_window_qt(PyMod_protocol_window_qt):
"""
Window with options for the contact map analysis.
"""
feature_types_list = ["Contacts", "Distances", "Distance Difference", "Distance Mean", "Distance Std"]
interaction_centers_list = ["Carbon alpha", "Carbon beta"]
default_contact_threshold = 8.0
default_distance_threshold = 18.0
default_distance_diff_threshold = 3.5
default_distance_mean_threshold = default_distance_threshold
default_distance_std_threshold = default_distance_diff_threshold
def build_protocol_middle_frame(self):
# Feature type selection.
if len(self.protocol.target_sequences) == 1: # Contact and distance.
sel_option_idx = 0
all_options_idx = (0, 1)
elif len(self.protocol.target_sequences) == 2: # Distance difference, mean and std.
sel_option_idx = 2
all_options_idx = (2, 3, 4)
elif len(self.protocol.target_sequences) > 2: # Distance mean and std.
sel_option_idx = 3
all_options_idx = (3, 4)
features_buttons = [self.feature_types_list[i] for i in all_options_idx]
self.feature_type_rds = PyMod_radioselect_qt(label_text="Feature Type",
buttons=features_buttons)
for button, option_idx in zip(self.feature_type_rds.get_buttons(), all_options_idx):
button.clicked.connect(lambda e=None, o=option_idx: self.feature_type_state(o))
self.feature_type_rds.setvalue(self.feature_types_list[sel_option_idx])
self.middle_formlayout.add_widget_to_align(self.feature_type_rds)
# Distance threshold for contacts.
if len(self.protocol.target_sequences) == 1:
threshold = self.default_contact_threshold
elif len(self.protocol.target_sequences) == 2:
threshold = self.default_distance_diff_threshold
else:
threshold = self.default_distance_threshold
self.dist_threshold_enf = PyMod_entryfield_qt(label_text="Contact Threshold (%s)" % ("\u212B"),
value=str(threshold),
validate={'validator': 'real',
'min': 1.0, 'max': 100.0})
self.middle_formlayout.add_widget_to_align(self.dist_threshold_enf)
# Interaction center selection.
self.interaction_center_rds = PyMod_radioselect_qt(label_text="Interaction Center",
buttons=self.interaction_centers_list)
self.interaction_center_rds.setvalue(self.interaction_centers_list[0])
self.middle_formlayout.add_widget_to_align(self.interaction_center_rds)
# Reference structure combobox.
if len(self.protocol.target_sequences) > 1:
structures_list = [element.my_header for element in self.protocol.target_sequences]
self.reference_combobox = PyMod_combobox_qt(label_text="Reference Structure",
items=structures_list)
self.reference_combobox.combobox.setCurrentIndex(0)
self.middle_formlayout.add_widget_to_align(self.reference_combobox)
self.middle_formlayout.set_input_widgets_width("auto", padding=10)
def feature_type_state(self, state):
"""
Launched when the user changes the "Feature Type" in the Options window.
"""
# Change the status of the Tkinter checkbutton.
if state == 0:
self.feature_type_rds.setvalue(self.feature_types_list[0])
self.dist_threshold_enf.setvalue(str(self.default_contact_threshold))
elif state == 1:
self.feature_type_rds.setvalue(self.feature_types_list[1])
self.dist_threshold_enf.setvalue(str(self.default_distance_threshold))
elif state == 2:
self.feature_type_rds.setvalue(self.feature_types_list[2])
self.dist_threshold_enf.setvalue(str(self.default_distance_diff_threshold))
elif state == 3:
self.feature_type_rds.setvalue(self.feature_types_list[3])
self.dist_threshold_enf.setvalue(str(self.default_distance_mean_threshold))
elif state == 4:
self.feature_type_rds.setvalue(self.feature_types_list[4])
self.dist_threshold_enf.setvalue(str(self.default_distance_std_threshold))
else:
KeyError(state)
def get_feature_type(self):
feature_type = self.feature_type_rds.getvalue()
if feature_type == self.feature_types_list[0]:
return "contact", feature_type
elif feature_type == self.feature_types_list[1]:
return "distance", feature_type
elif feature_type == self.feature_types_list[2]:
return "distances_difference", feature_type
elif feature_type == self.feature_types_list[3]:
return "distances_mean", feature_type
elif feature_type == self.feature_types_list[4]:
return "distances_std", feature_type
else:
raise KeyError(feature_type)
def get_interaction_center(self):
int_center_string = self.interaction_center_rds.getvalue()
if int_center_string == self.interaction_centers_list[0]:
return "ca"
elif int_center_string == self.interaction_centers_list[1]:
return "cb"
else:
raise KeyError(int_center_string)
def get_reference_id(self):
try:
return self.reference_combobox.get_index()
except:
print("- WARNING: could not obtain the reference structure id.")
return 0
###############################################################################
# Results window. #
###############################################################################
class Contact_map_graphics_view(QtWidgets.QGraphicsView):
pass
class Contact_map_pixel(QtWidgets.QGraphicsRectItem):
"""
Custom class for drawing on a graphic scene of PyQt rectangles corresponding
to pixels of a contact/distance map.
"""
def __init__(self, x, y, w, h, contact_map_window, pen, brush, i, j):
super(Contact_map_pixel, self).__init__(x, y, w, h)
self.contact_map_window = contact_map_window
self.setPen(pen)
self.original_brush = brush
self.setBrush(brush)
self.setAcceptHoverEvents(True)
self.i_idx = i
self.j_idx = j
def mousePressEvent(self, e):
self.contact_map_window.canvas_plot_left_click_event(self.i_idx, self.j_idx)
def hoverEnterEvent(self, e):
self.setBrush(self.contact_map_window.highlight_brush)
self.contact_map_window.canvas_plot_move_event(self.i_idx, self.j_idx)
def hoverLeaveEvent(self, e):
self.setBrush(self.original_brush)
class Contact_map_analysis_window_qt(QtWidgets.QMainWindow):
"""
Class for a window containing a PyQt widget in which a contact/distance map
will be drawn. Minimal PyQt implementation of a graphical contact map. NumPy
is required.
Note: for large protein, building every rectangle in the canvas takes a lot
of time and there is room for optimization.
"""
is_pymod_window = True
distance_count = 0
def initialize_map(self, pymod, data_array,
pymod_elements,
ref_residues,
ref_selectors,
title=None,
pixel_size=5,
feature_type="contact",
threshold=8.0,
interaction_center="ca"):
# Sets the attributes.
self.data_array = data_array
self.pixel_size = pixel_size
self.feature_type = feature_type
self.threshold = threshold
self.interaction_center = interaction_center
if self.feature_type in ("contact", "distance"):
self.pymod_elements = pymod_elements
self.pymod_element = self.pymod_elements[0]
else:
self.pymod_elements = pymod_elements
# Get the PyMod residues for each residue having an interaction center and the PyMOL selectors
# for each residue.
self.ref_residues = ref_residues
self.ref_selectors = ref_selectors
# Assign the methods to get the labels.
if self.feature_type == "contact":
self.get_value_label = self._get_value_label_contact
elif self.feature_type == "distance":
self.get_value_label = self._get_value_label_distance
elif self.feature_type == "distances_difference":
self.get_value_label = self._get_value_label_distance_diff
elif self.feature_type == "distances_mean":
self.get_value_label = self._get_value_label_distance_mean
elif self.feature_type == "distances_std":
self.get_value_label = self._get_value_label_distance_std
else:
raise KeyError(self.feature_type)
# Set the canvas size.
min_size = 150
h = self.pixel_size*len(self.data_array)
win_size = min((910, h))
win_size = max((min_size, win_size))
if title:
self.setWindowTitle(title)
# Set some appearance parameters.
self.controls_padding = 4
if self.feature_type in ("contact", "distance"):
self.controls_font = "helvetica 11 bold"
else:
self.controls_font = "helvetica 10 bold"
self.controls_config = {"fg": "black", "font": self.controls_font,
"padx": self.controls_padding,
"pady": self.controls_padding}
self.labels_pack_config = {"side": "left", "pady": (0, 5), "padx": (5, 0)}
self.buttons_pack_config = {"side": "left", "pady": (0, 5), "padx": (1, 0)}
# Frame of the window containing a row for some control buttons, a row for
# the plot and a row for a messagebar.
self.plot_frame = QtWidgets.QWidget()
self.plot_frame_layout = QtWidgets.QGridLayout()
self.plot_frame.setLayout(self.plot_frame_layout)
self.setCentralWidget(self.plot_frame)
# Control frame.
self.controls_frame = QtWidgets.QWidget()
self.controls_frame_layout = QtWidgets.QGridLayout()
self.controls_frame.setLayout(self.controls_frame_layout)
self.plot_frame_layout.addWidget(self.controls_frame)
self.delete_distances_button = QtWidgets.QPushButton("Delete all distances in PyMOL")
self.delete_distances_button.setEnabled(False)
self.delete_distances_button.clicked.connect(lambda a=None: self.clear_plot())
self.controls_frame_layout.addWidget(self.delete_distances_button, 0, 0)
self.scale_factor = 0
self.scale_down_button = QtWidgets.QPushButton("Zoom out")
try:
self.scale_down_button.setIcon(QtGui.QIcon.fromTheme("go-down"))
except:
pass
self.scale_down_button.clicked.connect(lambda a=None: self.scale_plot_down())
self.controls_frame_layout.addWidget(self.scale_down_button, 0, 1)
self.scale_up_button = QtWidgets.QPushButton("Zoom in")
try:
self.scale_up_button.setIcon(QtGui.QIcon.fromTheme("go-up"))
except:
pass
self.scale_up_button.clicked.connect(lambda a=None: self.scale_plot_up())
self.controls_frame_layout.addWidget(self.scale_up_button, 0, 2)
self.controls_frame_layout.setAlignment(QtCore.Qt.AlignLeft)
# Frame containing the plot (with a scrollbar).
self.canvas_plot_frame = QtWidgets.QWidget()
self.canvas_plot_frame.setStyleSheet("background-color: white")
self.canvas_plot_frame_layout = QtWidgets.QGridLayout()
self.canvas_plot_frame.setLayout(self.canvas_plot_frame_layout)
self.canvas_plot_scrollarea = QtWidgets.QScrollArea()
self.canvas_plot_scrollarea.setWidgetResizable(True)
self.canvas_plot_scrollarea.setWidget(self.canvas_plot_frame)
self.plot_frame_layout.addWidget(self.canvas_plot_scrollarea)
# Builds the scene where to draw the contact map.
self.canvas_plot_scene = QtWidgets.QGraphicsScene()
# Builds the graphics view containing the scene above.
self.canvas_plot_view = Contact_map_graphics_view(self.canvas_plot_scene)
self.canvas_plot_frame_layout.addWidget(self.canvas_plot_view)
# A bottom frame fo the window, containing some buttons to interact with the graph.
self.message_frame = QtWidgets.QFrame()
self.message_frame_layout = QtWidgets.QHBoxLayout()
self.message_frame.setLayout(self.message_frame_layout)
self.plot_frame_layout.addWidget(self.message_frame)
# Label to show which residue/position pair is currently being hovered by the mouse pointer.
if self.feature_type in ("contact", "distance"):
view_label_text = "Couple:"
else:
view_label_text = "Alignment positions:"
self.view_label = QtWidgets.QLabel(view_label_text)
# self.view_label.setStyleSheet(self.controls_config)
self.message_frame_layout.addWidget(self.view_label)
# Actually draws the contact map.
self.draw_map()
# self._test_plot()
def draw_map(self):
"""
Methods that actually draw the contact/distance map on a canvas widget.
"""
w = self.pixel_size
# Prepare the brushes.
self.viridis_brushes = []
with warnings.catch_warnings():
warnings.simplefilter("ignore")
for c in viridis_colors_rev:
brush = QtGui.QBrush(QtGui.QColor(round(c[0]*255), round(c[1]*255), round(c[2]*255)))
self.viridis_brushes.append(brush)
self.default_brush = QtGui.QBrush(QtGui.QColor(242, 242, 242))
self.highlight_brush = QtGui.QBrush(QtGui.QColor(255, 0, 0))
# Function to get the color of pixels.
if self.feature_type == "contact":
self.get_color = self._get_color_contact
elif self.feature_type in ("distance", "distances_mean"):
self._dist_bins = np.linspace(2.5, self.threshold, 63)
self.get_color = self._get_color_distance
elif self.feature_type in ("distances_difference", "distances_std"):
self._dist_bins = np.linspace(0.0, self.threshold, 63)
self.get_color = self._get_color_distance
else:
raise KeyError(self.feature_type)
#-------------------------------
# Draws the map on the canvas. -
#-------------------------------
# Use a transparent pen for the border pf the pixels.
pen = QtGui.QPen(QtGui.QColor(0, 0, 0, 0), 0)
for i in range(0, len(self.data_array)):
for j in range(0, len(self.data_array)):
if i <= j:
# Gets the color brush.
color_brush = self.get_color(self.data_array[i][j])
# Builds rectangles for both the upper and lower part of the
# matrix and adds them to the graphics scene.
pid = Contact_map_pixel(j*w, i*w, w, w, i=i, j=j,
contact_map_window=self,
pen=pen, brush=color_brush)
self.canvas_plot_scene.addItem(pid)
pid = Contact_map_pixel(i*w, j*w, w, w, i=j, j=i,
contact_map_window=self,
pen=pen, brush=color_brush)
self.canvas_plot_scene.addItem(pid)
# Add events to the canvas.
if self.feature_type in ("contact", "distance"):
# Draws the map of a single structure on the canvas.
self.canvas_plot_move_event = self.move_on_plot
self.canvas_plot_left_click_event = self.click_on_plot
else:
# Draws the map of multiple structures on the canvas.
self.canvas_plot_move_event = self.move_on_plot_ali
self.canvas_plot_left_click_event = self.click_on_plot_ali
# Click on the plot.
def click_on_plot(self, i, j):
"""
When clicking on a square, draw a distance in the PyMOL viewer between the corresponding
residues. Used when analyzing a single structure.
"""
res_1 = self.ref_residues[i]
res_2 = self.ref_residues[j]
if res_1 is res_2:
return None
sel_1 = self.ref_selectors[i]
sel_2 = self.ref_selectors[j]
cmd.distance("pymod_dist_%s" % self.distance_count, sel_1, sel_2)
# cmd.center("pymod_distance_%s" % self.distance_count)
self.distance_count += 1
self.delete_distances_button.setEnabled(True)
def click_on_plot_ali(self, i, j):
"""
Used when analyzing multiple structures. The residues of the reference structures will be
used in PyMOL.
"""
if i == j:
return None
sel_1 = self.ref_selectors[i]
sel_2 = self.ref_selectors[j]
if sel_1 is None or sel_2 is None:
return None
cmd.distance("pymod_dist_%s" % self.distance_count, sel_1, sel_2)
self.distance_count += 1
self.delete_distances_button.setEnabled(True)
# Move the mouse on the plot.
def move_on_plot(self, i, j):
"""
Used when showing the contact/distance map of a single structure.
"""
val = self.data_array[i][j]
res_1 = self.ref_residues[i]
res_2 = self.ref_residues[j]
self.view_label.setText("Couple: %s %s - %s %s (%s)." % (res_1.three_letter_code, res_1.db_index,
res_2.three_letter_code, res_2.db_index,
self.get_value_label(val)))
def move_on_plot_ali(self, i, j):
"""
Used when showing the distance map of multiple structures.
"""
val = self.data_array[i][j]
res_1 = self.ref_residues[i]
res_2 = self.ref_residues[j]
label = "Alignment positions: %s - %s (%s)." % (i+1, j+1, self.get_value_label(val))
if res_1 is not None and res_2 is not None:
label += " Reference: %s %s - %s %s" % (res_1.three_letter_code, res_1.db_index,
res_2.three_letter_code, res_2.db_index)
self.view_label.setText(label)
# Get the labels to show on the bottom of the window.
def _get_value_label_contact(self, value):
if value == 1:
return "contact"
else:
return "non contact"
def _get_value_label_distance(self, value):
return str(round(value, 2)) + " \u212B"
def _get_value_label_distance_diff(self, value):
return self._get_value_label_distance_ali(value, "diff")
def _get_value_label_distance_mean(self, value):
return self._get_value_label_distance_ali(value, "mean")
def _get_value_label_distance_std(self, value):
return self._get_value_label_distance_ali(value, "std")
def _get_value_label_distance_ali(self, value, label):
if value == -1:
return "not aligned"
else:
return "%s = %s %s" % (label, round(value, 2), " \u212B")
# Get the colors for pixels in the map.
def _get_color_contact(self, v):
if v == 0:
return self.viridis_brushes[-1] # "white"
else:
return self.viridis_brushes[0] # "gray"
def _get_color_distance(self, v):
"""
Assignes the bin for the distance value and returns the corresponding color.
"""
if v == -1:
return self.default_brush
return self.viridis_brushes[np.digitize(v, self._dist_bins)]
# Events influecing the whole plot.
def clear_plot(self):
"""
Remove all distances which have been drawn.
"""
cmd.delete("pymod_dist_*")
self.delete_distances_button.setEnabled(False)
def scale_plot_up(self):
if self.scale_factor > 10:
return None
self.canvas_plot_view.scale(1.25, 1.25)
self.scale_factor += 1
if self.scale_factor > 10:
self.scale_up_button.setEnabled(False)
self.scale_down_button.setEnabled(True)
def scale_plot_down(self):
if self.scale_factor < -10:
return None
self.canvas_plot_view.scale(0.8, 0.8)
self.scale_factor -=1
if self.scale_factor < -10:
self.scale_down_button.setEnabled(False)
self.scale_up_button.setEnabled(True)
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_protocols/similarity_searches_protocols/local_blast.py | .py | 3,566 | 84 | # Copyright 2020 by Giacomo Janson. All rights reserved.
# This code is part of the PyMod package and governed by its license. Please
# see the LICENSE file that should have been included as part of this package
# or the main __init__.py file in the pymod3 folder.
"""
Launch BLAST using an executable and databases found on the user's system.
The classes in this model build up on the ones for PSI-BLAST.
"""
import os
from pymod_lib.pymod_protocols.similarity_searches_protocols.psiblast import PSI_BLAST_search, PSI_BLAST_options_window_qt
from pymod_lib.pymod_threading import Protocol_exec_dialog
###################################################################################################
# LOCAL BLAST. #
###################################################################################################
class LOC_BLAST_search(PSI_BLAST_search):
blast_version = "blastp"
protocol_name = blast_version
exe_filename = "blastp"
min_inclusion_eval_default = 0.005
def get_blast_window_class_qt(self):
return Local_BLAST_options_window_qt
def run_psiblast(self):
"""
Launches a standalone version of BLAST installed locally when using the BLAST
option in the plugin main menu.
"""
# Builds a temporary file with the sequence of the query needed by psiblast.
query_file_name = "query"
self.pymod.build_sequence_file([self.blast_query_element], query_file_name,
file_format="fasta", remove_indels=True,
new_directory=self.output_directory)
# Sets some parameters in needed to run PSI-BLAST.
ncbi_dir = self.pymod.blast_plus["exe_dir_path"].get_value()
args = {"ncbi_dir": ncbi_dir,
"db_path": self.db_path,
"query": os.path.join(self.output_directory, query_file_name+".fasta"),
"inclusion_ethresh": None,
"outfmt": 5,
"out": os.path.join(self.output_directory, self.xml_blast_output_file_name),
"num_iterations": None,
"evalue": self.evalue_cutoff,
"max_target_seqs": self.max_hsp_num,
"blast_version": "blastp"}
if not self.pymod.use_protocol_threads:
self.execute_psiblast(**args)
else:
label_text = "Running BLASTp. Please wait for the process to complete..."
p_dialog = Protocol_exec_dialog(app=self.pymod.main_window, pymod=self.pymod,
function=self.execute_psiblast,
args=args,
title="Running BLASTp",
label_text=label_text)
p_dialog.exec_()
# If everything went ok, return 'True', so that the results window can be opened.
return True
def get_options_from_gui_specific(self):
self.get_options_from_gui_blast()
###################################################################################################
# GUI. #
###################################################################################################
class Local_BLAST_options_window_qt(PSI_BLAST_options_window_qt):
def build_algorithm_advanced_options_widgets(self):
pass
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_protocols/similarity_searches_protocols/psiblast.py | .py | 17,751 | 408 | # Copyright 2020 by Giacomo Janson. All rights reserved.
# This code is part of the PyMod package and governed by its license. Please
# see the LICENSE file that should have been included as part of this package
# or the main __init__.py file in the pymod3 folder.
"""
Module for running PSI-BLAST in PyMod.
"""
import os
import shutil
from Bio.Blast import NCBIXML
import pymod_lib.pymod_os_specific as pmos
from pymod_lib.pymod_protocols.similarity_searches_protocols._base_blast import Generic_BLAST_search
from pymod_lib.pymod_threading import Protocol_exec_dialog
from pymod_lib.pymod_exceptions import catch_protocol_exception
temp_output_dir_name = "__blast_temp__"
class PSI_BLAST_common:
"""
A mixin class for using PSI-BLAST in other protocols (such as in psipred) other than the
PSI-BLAST protocol itself.
"""
def verify_valid_blast_dbdir(self, dbpath, remove_temp_files=False):
"""
Checks if the folder specified in 'dbpath' contains a valid set of sequence database files.
"""
if os.path.isfile(dbpath):
return ""
if remove_temp_files:
for fn in os.listdir(dbpath):
if fn == temp_output_dir_name:
fp = os.path.join(dbpath, fn)
if os.path.isfile(fp):
os.remove(fp)
elif os.path.isdir(fp):
shutil.rmtree(fp)
dbprefix = self._get_blast_database_prefix(dbpath)
return dbprefix
def _get_blast_database_prefix(self, dbpath):
database_files = []
for fn in os.listdir(dbpath):
if fn == ".DS_Store":
pass
elif fn.startswith("taxdb"):
pass
else:
prefix = fn.split(".")[0]
prefix.replace("_v5", "")
database_files.append(prefix)
return os.path.commonprefix(database_files)
def execute_psiblast(self, ncbi_dir, db_path, query,
inclusion_ethresh=0.001, num_iterations=3,
evalue=None, max_target_seqs=None, num_alignments=None,
out=None, outfmt=None, out_pssm=None,
blast_version="psiblast"):
"""
Execute the locally installed PSI-BLAST. Used when running PSI-BLAST through the 'PSI-BLAST'
command on the plugin main menu or when predicting secondary structures with PSIPRED.
"""
self.check_blast_version(blast_version)
# Gests the prefix of the database folder.
moved_to_db_dir = False
try:
dp_prefix = self.verify_valid_blast_dbdir(db_path)
# Makes a temporary directory in the folder of the selected database.
os.mkdir(os.path.join(db_path, temp_output_dir_name))
# Copies the .fasta file of the query in the temporary folder.
query_file_name = os.path.split(query)[1]
shutil.copy(query, os.path.join(db_path, temp_output_dir_name, query_file_name))
# Moves in the database directory.
os.chdir(db_path)
moved_to_db_dir = True
# Sets the input and output file names.
temp_query_shortcut = os.path.join(temp_output_dir_name, query_file_name)
temp_out_file_shortcut = None
if out != None:
temp_out_file_shortcut = os.path.join(temp_output_dir_name, os.path.split(out)[1])
temp_out_pssm_file_shortcut = None
if out_pssm != None:
temp_out_pssm_file_shortcut = os.path.join(temp_output_dir_name, os.path.split(out_pssm)[1])
# Builds the PSI-BLAST commandline.
psiblast_command = self.build_psiblast_commandline(
ncbi_dir = ncbi_dir,
db_path = dp_prefix,
query = temp_query_shortcut,
inclusion_ethresh = inclusion_ethresh,
num_iterations = num_iterations,
evalue = evalue,
max_target_seqs = max_target_seqs,
num_alignments = num_alignments,
out = temp_out_file_shortcut,
outfmt = outfmt,
out_pssm = temp_out_pssm_file_shortcut,
blast_version=blast_version)
# Execute PSI-BLAST.
self.pymod.execute_subprocess(psiblast_command)
# Goes back to the original directory.
os.chdir(self.pymod.current_project_dirpath)
# Removes the query temp file.
os.remove(os.path.join(db_path, temp_output_dir_name, query_file_name))
# Moves the temporary files in the originally specified output directory.
for output_file in os.listdir(os.path.join(db_path, temp_output_dir_name)):
new_output_filepath = os.path.join(os.path.split(query)[0], output_file)
if os.path.isfile(new_output_filepath):
os.remove(new_output_filepath)
shutil.move(os.path.join(db_path, temp_output_dir_name, output_file), os.path.split(query)[0])
# Remove the temporary directory.
shutil.rmtree(os.path.join(db_path, temp_output_dir_name))
except Exception as e:
# If something goes wrong while executing PSI-BLAST, go back to the project directory
# and removes the temporary directory in the database folder, it it was built.
if moved_to_db_dir:
os.chdir(self.pymod.current_project_dirpath)
if os.path.isdir(os.path.join(db_path, temp_output_dir_name)):
shutil.rmtree(os.path.join(db_path, temp_output_dir_name))
raise e
def build_psiblast_commandline(self, ncbi_dir, db_path, query,
inclusion_ethresh=0.001, num_iterations=3,
evalue=None, max_target_seqs=None, num_alignments=None,
out=None, outfmt=None, out_pssm=None,
blast_version="psiblast"):
self.check_blast_version(blast_version)
# blastdbcmd -db "\"Users\joeuser\My Documents\Downloads\mydb\"" -info
# blastdbcmd -db ' "path with spaces/mydb" ' -info
psiblast_path = pmos.build_commandline_path_string(os.path.join(ncbi_dir, pmos.get_exe_file_name(blast_version)))
db_path = pmos.build_commandline_file_argument("db", db_path)
query = pmos.build_commandline_file_argument("query", query)
if inclusion_ethresh != None:
inclusion_ethresh = " -inclusion_ethresh %s" % (inclusion_ethresh)
else:
inclusion_ethresh = ""
if num_iterations != None:
num_iterations = " -num_iterations %s" % (num_iterations)
else:
num_iterations = ""
if evalue != None:
evalue = " -evalue %s" % (evalue)
else:
evalue = ""
if outfmt != None:
outfmt = " -outfmt %s" % (outfmt) # 5 produces an .xml output file.
else:
outfmt = ""
if out != None:
out = pmos.build_commandline_file_argument("out", out)
else:
out = ""
if max_target_seqs != None:
max_target_seqs = " -max_target_seqs %s" % (max_target_seqs)
else:
max_target_seqs = ""
if out_pssm != None:
out_pssm = pmos.build_commandline_file_argument("out_pssm", out_pssm)
else:
out_pssm = ""
if num_alignments != None:
num_alignments = " -num_alignments %s" % (num_alignments)
else:
num_alignments = ""
psiblast_command = (psiblast_path + db_path + query +
inclusion_ethresh + out + outfmt + out_pssm +
num_iterations + evalue + max_target_seqs +
num_alignments)
return psiblast_command
def check_blast_version(self, blast_version):
if not blast_version in ("psiblast", "blastp"):
raise KeyError("Unknown BLAST version: %s." % blast_version)
###################################################################################################
# PSI-BLAST protocol. #
###################################################################################################
class PSI_BLAST_search(Generic_BLAST_search, PSI_BLAST_common):
blast_version = "psi-blast"
protocol_name = blast_version
exe_filename = "psiblast"
# PSI-BLAST minimum inclusion E-value.
min_inclusion_eval_default = 0.005
def additional_initialization(self):
Generic_BLAST_search.additional_initialization(self)
self.tool = self.pymod.blast_plus
def get_blast_window_class_qt(self):
return PSI_BLAST_options_window_qt
def check_blast_input_parameters(self):
# Check if a valid database for PSI-BLAST was provided.
db_full_path = self.get_database_from_gui()
if db_full_path == None:
title = "Input Error"
message = "Please choose a valid database."
self.pymod.main_window.show_error_message(title, message)
return False
if not self.verify_valid_blast_dbdir(db_full_path, remove_temp_files=True):
title = "Input Error"
message = "The database '%s' directory does not contain a valid set of database files." % (db_full_path)
self.pymod.main_window.show_error_message(title, message)
return False
# Check all the other input fields.
try:
self.blast_options_window.check_general_input()
except Exception as general_input_error:
title = "Input Error"
message = str(general_input_error)
self.pymod.main_window.show_error_message(title, message)
return False
if not self.check_min_max_seqid_input():
return False
# Returns 'True' only if all input parameters are valid.
return True
@catch_protocol_exception
def run_blast_program(self):
return self.run_psiblast()
def get_blast_record(self, result_handle):
"""
Convert it to a list because when a using .parse(), Biopython returns a generator.
"""
records = list(NCBIXML.parse(result_handle))
return records[0]
#################################################################
# PSI-BLAST specific. #
#################################################################
def run_psiblast(self):
"""
Launches a standalone version of PSI-BLAST installed locally when using the PSI-BLAST
option in the plugin main menu.
"""
# Builds a temporary file with the sequence of the query needed by psiblast.
query_file_name = "query"
self.pymod.build_sequence_file([self.blast_query_element], query_file_name,
file_format="fasta", remove_indels=True,
new_directory=self.output_directory)
# Sets some parameters in needed to run PSI-BLAST.
ncbi_dir = self.pymod.blast_plus["exe_dir_path"].get_value()
args = {"ncbi_dir": ncbi_dir,
"db_path": self.db_path,
"query": os.path.join(self.output_directory, query_file_name+".fasta"),
"inclusion_ethresh": self.evalue_inclusion_cutoff,
"outfmt": 5,
"out": os.path.join(self.output_directory, self.xml_blast_output_file_name),
"num_iterations": self.iterations,
"evalue": self.evalue_cutoff,
"max_target_seqs": self.max_hsp_num}
if not self.pymod.use_protocol_threads:
self.execute_psiblast(**args)
else:
label_text = "Running PSI-BLAST. Please wait for the process to complete..."
p_dialog = Protocol_exec_dialog(app=self.pymod.main_window, pymod=self.pymod,
function=self.execute_psiblast,
args=args,
title="Running PSI-BLAST",
label_text=label_text)
p_dialog.exec_()
# If everything went ok, return 'True', so that the results window can be opened.
return True
def get_options_from_gui_specific(self):
self.get_options_from_gui_blast()
self.iterations = self.blast_options_window.psiblast_iterations_enf.getvalue()
if self.blast_options_window.showing_advanced_widgets:
self.evalue_inclusion_cutoff = self.blast_options_window.psiblast_eval_threshold_enf.getvalue()
else:
self.evalue_inclusion_cutoff = self.min_inclusion_eval_default
def build_blast_db_list(self):
"""
Generates a list of dictionaries each containing information about the sequence databases
present in the default BLAST database directory.
"""
blast_db_dir = self.tool["database_dir_path"].get_value()
list_of_databases_directories = []
# If there are multiple directories containing database files with the same prefixes, this
# will rename their prefixes so that the database radioselect will not have multiple buttons
# with the same name.
def get_new_prefix(prefix, list_of_databases_directories, n=1, prefix_root=None):
if prefix_root == None:
prefix_root = prefix
if prefix in [dbd["prefix"] for dbd in list_of_databases_directories]:
new_prefix = prefix_root + "-" + str(n)
return get_new_prefix(new_prefix, list_of_databases_directories, n+1, prefix_root)
else:
return prefix
for path in os.listdir(blast_db_dir):
full_path = os.path.join(blast_db_dir, path)
prefix = self.verify_valid_blast_dbdir(full_path, remove_temp_files=True)
if prefix:
prefix = get_new_prefix(prefix, list_of_databases_directories)
dbd = {"full-path": full_path, "prefix": prefix}
list_of_databases_directories.append(dbd)
return list_of_databases_directories
def get_database_from_gui(self):
button_name = self.blast_options_window.psiblast_database_rds.getvalue()
for dbd in self.databases_directories_list:
if dbd["prefix"] == button_name:
return dbd["full-path"]
return None
###################################################################################################
# GUI. #
###################################################################################################
from pymod_lib.pymod_gui.shared_gui_components_qt import PyMod_entryfield_qt, PyMod_radioselect_qt
from pymod_lib.pymod_protocols.similarity_searches_protocols._base_blast import BLAST_base_options_window_qt
class PSI_BLAST_options_window_qt(BLAST_base_options_window_qt):
"""
Window for PSI-BLAST searches.
"""
def build_algorithm_standard_options_widgets(self):
# Makes the user chose the folder where the BLAST database files are stored locally.
# A list containing information about the databases present in PyMod BLAST database
# folder.
db_list = [k["prefix"] for k in self.protocol.databases_directories_list]
self.psiblast_database_rds = PyMod_radioselect_qt(label_text="Database Selection",
buttons=db_list)
self.middle_formlayout.add_widget_to_align(self.psiblast_database_rds)
# Number of PSI-BLAST iterations.
if self.protocol.blast_version == "psi-blast":
self.psiblast_iterations_enf = PyMod_entryfield_qt(label_text="PSI-BLAST Iterations",
value='3',
validate={'validator': 'integer',
'min': 1, 'max': 10})
self.middle_formlayout.add_widget_to_align(self.psiblast_iterations_enf, validate=True)
def build_algorithm_advanced_options_widgets(self):
if self.protocol.blast_version == "psi-blast":
self.psiblast_eval_threshold_enf = PyMod_entryfield_qt(
label_text="Inclusion E-value",
value=str(self.protocol.min_inclusion_eval_default),
validate={'validator': 'real', 'min': 0.0, 'max': 1000.0})
self.middle_formlayout.add_widget_to_align(self.psiblast_eval_threshold_enf,
advanced_option=True, validate=True)
# Use current cluster for PSI-BLAST PSSM.
# if self.blast_query_element.is_child:
# self.use_current_pssm_rds = PyMod_radioselect(self.midframe, label_text = 'Use current cluster as PSSM')
# for text in ('Yes', 'No'):
# self.use_current_pssm_rds.add(text)
# self.use_current_pssm_rds.setvalue('No')
# # self.use_current_pssm_rds.pack(side = 'top', padx = 10, pady = 10, anchor="w")
# self.add_widget_to_align(self.use_current_pssm_rds)
# self.add_advanced_widget(self.use_current_pssm_rds)
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_protocols/similarity_searches_protocols/jackhmmer.py | .py | 9,999 | 261 | # Copyright 2020 by Giacomo Janson. All rights reserved.
# This code is part of the PyMod package and governed by its license. Please
# see the LICENSE file that should have been included as part of this package
# or the main __init__.py file in the pymod3 folder.
"""
Module for performing jackhmmer searches in PyMod. It mainly builds up on the code used to perform
BLAST searches and phmmer searches.
"""
import os
from pymod_lib.pymod_protocols.similarity_searches_protocols.phmmer import PHMMER_search, Phmmer_options_window_qt
from pymod_lib.pymod_os_specific import get_exe_file_name
from pymod_lib.pymod_gui.shared_gui_components_qt import PyMod_radioselect_qt, PyMod_entryfield_qt
################################################################################################
# JACKHMMER. #
################################################################################################
class Jackhmmer_search(PHMMER_search):
blast_version = "jackhmmer"
protocol_name = blast_version
exe_filename = "jackhmmer"
# JACKHMMER minimum inclusion E-value.
min_inclusion_eval_default = 0.001
def get_blast_window_class_qt(self):
return Jackhmmer_options_window_qt
def execute_hmmer_program(self, query_filepath, out_filepath, db_filepath, exe_filepath,
report_evalue=10e-6,
inclusion_evalue_threshold=10e-6,
n_iterations=3):
"""
Execute the locally installed jackhmmer.
"""
command_ls = [exe_filepath,
"-o", out_filepath, "--domE", str(report_evalue),
# "--incE", str(inclusion_evalue_threshold), # Full sequences.
"--incdomE", str(inclusion_evalue_threshold), # Domains.
"-N", str(n_iterations),
query_filepath, db_filepath]
self.pymod.new_execute_subprocess(command_ls)
def get_search_record(self):
phmmer_query_result = parse_jackhmmer_output(self.result_filepath)
return phmmer_query_result
def get_hsp_query_seq(self, hsp_obj):
return hsp_obj.query_seq
def get_hsp_subj_seq(self, hsp_obj):
return hsp_obj.hit_seq
def get_hsp_evalue(self, hsp):
return hsp.evalue, hsp.cond_evalue
def get_subj_start(self, hsp):
return hsp.hit_start
def build_hsp_list(self):
hsp_list = []
query_seq = self.blast_query_element.my_sequence.replace("-", "")
for hsp in self.search_record:
hsp._title = hsp.hit_name
# In jackhmmer the query sequence is changed (it becomes the profile's consensus), so it
# has to be restored back to its original.
hsp_query_seq = hsp.query_seq
hsp_q_res_len = len(hsp_query_seq.replace("-", ""))
hsp_q_start_index = hsp.query_start
original_query_frag = query_seq[hsp_q_start_index:hsp_q_start_index+hsp_q_res_len]
aligned_query_frag = []
rc = 0
for p in hsp_query_seq:
if p != "-":
aligned_query_frag.append(original_query_frag[rc])
rc += 1
else:
aligned_query_frag.append("-")
aligned_query_frag = "".join(aligned_query_frag)
hsp.query_seq = aligned_query_frag
# Gets additional information on the hsp (such as its the id % and query span).
hsp.pymod_info = self.get_hsp_info(hsp)
hsp_list.append(hsp)
# Sort by evalue.
hsp_list = list(sorted(hsp_list, key=lambda h: h.evalue))
return hsp_list
###################################################################################################
# GUI. #
###################################################################################################
class Jackhmmer_options_window_qt(Phmmer_options_window_qt):
"""
Window for JACKHMMER searches.
"""
# geometry_string = "450x650"
def build_additional_hmmer_widgets(self):
# Jackhmmer iterations enf.
self.jackhmmer_iterations_enf = PyMod_entryfield_qt(label_text="JACKHMMER Iterations",
value='3',
validate={'validator': 'integer',
'min': 1, 'max': 5})
self.middle_formlayout.add_widget_to_align(self.jackhmmer_iterations_enf, validate=True)
def build_algorithm_advanced_options_widgets(self):
# Inclusion E-value selection.
self.inclusion_e_value_threshold_enf = PyMod_entryfield_qt(
label_text="Max Inclusion c-Evalue",
value=str(self.protocol.min_inclusion_eval_default),
validate={'validator': 'real', 'min': 0.0, 'max': 1000.0})
self.middle_formlayout.add_widget_to_align(self.inclusion_e_value_threshold_enf,
advanced_option=True, validate=True)
def get_additional_hmmer_parameters(self):
if not self.showing_advanced_widgets:
inclusion_evalue_threshold = self.protocol.min_inclusion_eval_default
else:
inclusion_evalue_threshold = self.inclusion_e_value_threshold_enf.getvalue()
return {"inclusion_evalue_threshold": inclusion_evalue_threshold,
"n_iterations": self.jackhmmer_iterations_enf.getvalue()}
###################################################################################################
# Jackhmmer output parser. #
###################################################################################################
import re
class Jackhmmer_hsp:
def __init__(self, hit_name=None, evalue=None, cond_evalue=None):
self.hit_name = hit_name
self.cond_evalue = cond_evalue
self.evalue = evalue
self.query_seq = ""
self.hit_seq = ""
self.hit_start = None
self.hit_end = None
self.query_start = None
self.query_end = None
def _get_int(field_string):
try:
return int(field_string)
except ValueError:
return None
def parse_jackhmmer_output(output_filepath):
"""
Parses a jackhmmer output file and returns a list of 'Jackhmmer_hsp' object (one object for each
domain hit).
"""
last_round_line_id = None
with open(output_filepath, "r") as r_fh:
for i, l in enumerate(r_fh):
if l.startswith("@@ Continuing to next round."):
last_round_line_id = i
if last_round_line_id is None:
last_round_line_id = 0
hits_names_list = []
domains_list = []
new_alignments_found = False
hits_found = False
query_line = None
with open(output_filepath, "r") as r_fh:
for i, l in enumerate(r_fh):
if i < last_round_line_id:
continue
# A new sequence hit is found.
if l.startswith(">>"):
hits_names_list.append(l[3:].rstrip())
new_alignments_found = False
hits_found = True
domains_i_value_list = []
domain_count = 0
elif l.startswith(" == domain"):
# Add a new domain hit is found for the current sequence hit.
hit_name = hits_names_list[-1].split(" ")[0]
domains_list.append(Jackhmmer_hsp(hit_name=hit_name,
cond_evalue=float(l.split(":")[-1]),
evalue=domains_i_value_list[domain_count]))
new_domain = domains_list[-1]
new_alignments_found = True
query_line = True
domain_count += 1
else:
# Gets the aligned query and domain hit sequences.
if new_alignments_found:
fields = l.rstrip().split()
if len(fields) == 0:
continue
if fields[-1] in ("RF", "PP"):
continue
if len(fields) < 3:
continue
_end = _get_int(fields[-1])
_start = _get_int(fields[-3])
if _start is not None and _end is not None:
seq_label = "Q" if query_line else "H"
if query_line:
if new_domain.query_start is None:
new_domain.query_start = _start - 1
new_domain.query_end = _end # + 1
new_domain.query_seq += fields[-2].upper().replace(".", "-")
query_line = False
else:
if new_domain.hit_start is None:
new_domain.hit_start = _start - 1
new_domain.hit_end = _end # + 1
new_domain.hit_seq += fields[-2].upper()
query_line = True
else:
# Gets the i-evalues from the table summary table of each hit.
if hits_found:
fields = l.rstrip().split()
if len(fields) > 0 and re.match("[0-9]", fields[0]):
try:
domains_i_value_list.append(float(fields[5]))
except ValueError:
domains_i_value_list.append(1.0)
return domains_list
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_protocols/similarity_searches_protocols/ncbi_blast.py | .py | 14,908 | 347 | # Copyright 2020 by Giacomo Janson. All rights reserved.
# This code is part of the PyMod package and governed by its license. Please
# see the LICENSE file that should have been included as part of this package
# or the main __init__.py file in the pymod3 folder.
"""
Performs a BLAST search by connecting to the NCBI server.
"""
import os
from urllib.error import URLError
from Bio.Blast import NCBIWWW, NCBIXML
from pymod_lib.pymod_os_specific import check_network_connection
from pymod_lib.pymod_protocols.similarity_searches_protocols._base_blast import Generic_BLAST_search, BLAST_base_options_window_qt
from pymod_lib.pymod_threading import Protocol_exec_dialog
from pymod_lib.pymod_exceptions import catch_protocol_exception
from pymod_lib.pymod_gui.shared_gui_components_qt import PyMod_radioselect_qt
###################################################################################################
# NCBI BLAST. #
###################################################################################################
class NCBI_BLAST_search(Generic_BLAST_search):
blast_version = "blast"
protocol_name = blast_version
ncbi_databases = [("Non Redundant (nr)", "nr"),
("PDB", "pdb"),
("RefSeq", "refseq_protein"),
("SwissProt", "swissprot"),
# ("Model Organisms", "landmark"),
("Metagenomics", "env_nr"),
("Patents", "pataa"),]
def check_blast_program(self):
if not check_network_connection("https://google.com", timeout=3):
title = "Connection Error"
message = ("An internet connection is not available, can not connect to the NCBI"
" server to run BLAST.")
self.pymod.main_window.show_error_message(title, message)
return False
return True
def get_blast_window_class_qt(self):
return BLAST_options_window_qt
def check_blast_input_parameters(self):
"""
Checks if users have provide a set of valid input parameters in order to perform a search.
"""
# Check all the other input fields.
try:
self.blast_options_window.check_general_input()
except Exception as general_input_error:
title = "Input Error"
message = str(general_input_error)
self.pymod.main_window.show_error_message(title, message)
return False
if not self.check_min_max_seqid_input():
return False
# Returns 'True' only if all input parameters are valid.
return True
def get_options_from_gui_specific(self):
self.get_options_from_gui_blast()
def get_db_from_gui_blast(self):
self.ncbiblast_database = self.get_ncbiblast_database()
def get_blast_record(self, result_handle):
return NCBIXML.read(result_handle)
@catch_protocol_exception
def run_blast_program(self):
return self.run_ncbiblast()
def run_ncbiblast(self):
"""
This function allows to contact the NCBI BLAST server using Biopython.
"""
# Actually connects to the server.
query_seq = str(self.blast_query_element.my_sequence.replace("-", ""))
args = {"query_seq": query_seq,
"ncbiblast_database": self.ncbiblast_database,
"hitlist_size": self.max_hsp_num,
"expect": self.evalue_cutoff}
if not self.pymod.use_protocol_threads:
self.launch_qblast(**args)
else:
label_text = "Connecting to the BLAST NCBI server. Please wait for the process to complete..."
p_dialog = Protocol_exec_dialog(app=self.pymod.main_window, pymod=self.pymod,
function=self.launch_qblast,
args=args,
title="Running NCBI BLAST",
label_text=label_text)
p_dialog.exec_()
# In this way the results window can be opened.
return True
def launch_qblast(self, query_seq, ncbiblast_database, hitlist_size, expect):
result_handle = NCBIWWW.qblast("blastp", # self.qblast, NCBIWWW.qblast
ncbiblast_database,
query_seq,
hitlist_size=hitlist_size,
expect=expect)
# Saves an XML file that contains the results and that will be used to display them on
# the results window.
save_file = open(os.path.join(self.output_directory, self.xml_blast_output_file_name), "w")
save_file.write(result_handle.read())
save_file.close()
def qblast(self, program, database, sequence,
auto_format=None, composition_based_statistics=None,
db_genetic_code=None, endpoints=None, entrez_query='(none)',
expect=10.0, filter=None, gapcosts=None, genetic_code=None,
hitlist_size=50, i_thresh=None, layout=None, lcase_mask=None,
matrix_name=None, nucl_penalty=None, nucl_reward=None,
other_advanced=None, perc_ident=None, phi_pattern=None,
query_file=None, query_believe_defline=None, query_from=None,
query_to=None, searchsp_eff=None, service=None, threshold=None,
ungapped_alignment=None, word_size=None,
alignments=500, alignment_view=None, descriptions=500,
entrez_links_new_window=None, expect_low=None, expect_high=None,
format_entrez_query=None, format_object=None, format_type='XML',
ncbi_gi=None, results_file=None, show_overview=None, megablast=None,
):
"""
Reimplementation of the 'NCBIWWW.qblast' method of some old Biopython versions, which does
not work anymore since the NCBI switched to https.
Copyright 1999 by Jeffrey Chang. All rights reserved.
Do a BLAST search using the QBLAST server at NCBI.
Supports all parameters of the qblast API for Put and Get.
Some useful parameters:
- program blastn, blastp, blastx, tblastn, or tblastx (lower case)
- database Which database to search against (e.g. "nr").
- sequence The sequence to search.
- ncbi_gi TRUE/FALSE whether to give 'gi' identifier.
- descriptions Number of descriptions to show. Def 500.
- alignments Number of alignments to show. Def 500.
- expect An expect value cutoff. Def 10.0.
- matrix_name Specify an alt. matrix (PAM30, PAM70, BLOSUM80, BLOSUM45).
- filter "none" turns off filtering. Default no filtering
- format_type "HTML", "Text", "ASN.1", or "XML". Def. "XML".
- entrez_query Entrez query to limit Blast search
- hitlist_size Number of hits to return. Default 50
- megablast TRUE/FALSE whether to use MEga BLAST algorithm (blastn only)
- service plain, psi, phi, rpsblast, megablast (lower case)
This function does no checking of the validity of the parameters
and passes the values to the server as is. More help is available at:
http://www.ncbi.nlm.nih.gov/BLAST/Doc/urlapi.html
"""
import time
import urllib.request, urllib.parse
from io import StringIO
assert program in ['blastn', 'blastp', 'blastx', 'tblastn', 'tblastx']
# Format the "Put" command, which sends search requests to qblast.
# Parameters taken from http://www.ncbi.nlm.nih.gov/BLAST/Doc/node5.html on 9 July 2007
# Additional parameters are taken from http://www.ncbi.nlm.nih.gov/BLAST/Doc/node9.html on 8 Oct 2010
# To perform a PSI-BLAST or PHI-BLAST search the service ("Put" and "Get" commands) must be specified
# (e.g. psi_blast = NCBIWWW.qblast("blastp", "refseq_protein", input_sequence, service="psi"))
parameters = [
('AUTO_FORMAT', auto_format),
('COMPOSITION_BASED_STATISTICS', composition_based_statistics),
('DATABASE', database),
('DB_GENETIC_CODE', db_genetic_code),
('ENDPOINTS', endpoints),
('ENTREZ_QUERY', entrez_query),
('EXPECT', expect),
('FILTER', filter),
('GAPCOSTS', gapcosts),
('GENETIC_CODE', genetic_code),
('HITLIST_SIZE', hitlist_size),
('I_THRESH', i_thresh),
('LAYOUT', layout),
('LCASE_MASK', lcase_mask),
('MEGABLAST', megablast),
('MATRIX_NAME', matrix_name),
('NUCL_PENALTY', nucl_penalty),
('NUCL_REWARD', nucl_reward),
('OTHER_ADVANCED', other_advanced),
('PERC_IDENT', perc_ident),
('PHI_PATTERN', phi_pattern),
('PROGRAM', program),
# ('PSSM',pssm), - It is possible to use PSI-BLAST via this API?
('QUERY', sequence),
('QUERY_FILE', query_file),
('QUERY_BELIEVE_DEFLINE', query_believe_defline),
('QUERY_FROM', query_from),
('QUERY_TO', query_to),
# ('RESULTS_FILE',...), - Can we use this parameter?
('SEARCHSP_EFF', searchsp_eff),
('SERVICE', service),
('THRESHOLD', threshold),
('UNGAPPED_ALIGNMENT', ungapped_alignment),
('WORD_SIZE', word_size),
('CMD', 'Put'),
]
query = [x for x in parameters if x[1] is not None]
message = urllib.parse.urlencode(query).encode('utf-8')
# Send off the initial query to qblast.
# Note the NCBI do not currently impose a rate limit here, other
# than the request not to make say 50 queries at once using multiple
# threads.
request = urllib.request.Request("https://blast.ncbi.nlm.nih.gov/Blast.cgi",
message,
{"User-Agent": "BiopythonClient"})
handle = urllib.request.urlopen(request)
# Format the "Get" command, which gets the formatted results from qblast
# Parameters taken from http://www.ncbi.nlm.nih.gov/BLAST/Doc/node6.html on 9 July 2007
rid, rtoe = NCBIWWW._parse_qblast_ref_page(handle)
parameters = [
('ALIGNMENTS', alignments),
('ALIGNMENT_VIEW', alignment_view),
('DESCRIPTIONS', descriptions),
('ENTREZ_LINKS_NEW_WINDOW', entrez_links_new_window),
('EXPECT_LOW', expect_low),
('EXPECT_HIGH', expect_high),
('FORMAT_ENTREZ_QUERY', format_entrez_query),
('FORMAT_OBJECT', format_object),
('FORMAT_TYPE', format_type),
('NCBI_GI', ncbi_gi),
('RID', rid),
('RESULTS_FILE', results_file),
('SERVICE', service),
('SHOW_OVERVIEW', show_overview),
('CMD', 'Get'),
]
query = [x for x in parameters if x[1] is not None]
message = urllib.parse.urlencode(query).encode('utf-8')
# Poll NCBI until the results are ready. Use a backoff delay from 2 - 120 second wait
delay = 2.0
max_delay = 120
previous = time.time()
# The NCBI recommends:
# - Do not contact the server more often than once every 10 seconds.
# - Do not poll for any single RID more often than once a minute.
# - Use the URL parameter email and tool, so that the NCBI can contact you if there is a problem.
# - Run scripts weekends or between 9 pm and 5 am Eastern time on weekdays if more than 50 searches will be submitted.
use_fixed = True
fixed_delay = None
starting_time = time.time()
while True:
if not use_fixed:
current = time.time()
wait = previous + delay - current
if wait > 0:
print("- Waiting from NCBI:", wait)
time.sleep(wait)
previous = current + wait
else:
previous = current
if delay + .5 * delay <= max_delay:
delay += .25 * delay
else:
delay = max_delay
else:
if fixed_delay is None:
fixed_delay = 10.0
else:
time.sleep(fixed_delay)
print("- Waiting from NCBI:", round(time.time() - starting_time, 3))
request = urllib.request.Request("https://blast.ncbi.nlm.nih.gov/Blast.cgi",
message,
{"User-Agent": "PyModClient"}) # "BiopythonClient"})
handle = urllib.request.urlopen(request)
results = handle.read().decode('utf-8')
# Can see an "\n\n" page while results are in progress,
# if so just wait a bit longer...
if results == "\n\n":
continue
# XML results don't have the Status tag when finished
if "Status=" not in results:
break
i = results.index("Status=")
j = results.index("\n", i)
status = results[i + len("Status="):j].strip()
if status.upper() == "READY":
break
return StringIO(results)
def get_ncbiblast_database(self):
text = self.blast_options_window.ncbiblast_database_rds.getvalue()
for i in self.ncbi_databases:
if i[0] == text:
return i[1]
###################################################################################################
# GUI. #
###################################################################################################
class BLAST_options_window_qt(BLAST_base_options_window_qt):
"""
Window for BLAST searches.
"""
# input_widget_width = 16
# geometry_string = "450x650"
def build_algorithm_standard_options_widgets(self):
db_list = [text for (text, val) in self.protocol.ncbi_databases]
self.ncbiblast_database_rds = PyMod_radioselect_qt(label_text="Database Selection",
buttons=db_list)
self.ncbiblast_database_rds.setvalue('PDB')
self.middle_formlayout.add_widget_to_align(self.ncbiblast_database_rds)
def build_algorithm_advanced_options_widgets(self):
pass
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_protocols/similarity_searches_protocols/_base_blast.py | .py | 43,167 | 1,005 | # Copyright 2020 by Giacomo Janson. All rights reserved.
# This code is part of the PyMod package and governed by its license. Please
# see the LICENSE file that should have been included as part of this package
# or the main __init__.py file in the pymod3 folder.
"""
Module with a base class for similarity searches protocols. It is used to build classes for every
similarity search protocol in PyMod, that is, (PSI-)BLAST protocols and phmmer/jackhmmer protocols.
"""
import os
from pymod_lib.pymod_os_specific import get_exe_file_name, clean_file_name
from pymod_lib.pymod_vars import algs_full_names_dict
from pymod_lib.pymod_protocols.base_protocols import PyMod_protocol
from pymod_lib.pymod_seq.seq_star_alignment import save_cstar_alignment
from pymol.Qt import QtWidgets, QtCore
from pymod_lib.pymod_gui.shared_gui_components_qt import (PyMod_protocol_window_qt,
PyMod_entryfield_qt,
small_font_style, highlight_color)
###############################################################################################
# BLAST ALGORITHMS. #
###############################################################################################
hmmer_protocols_names = ("phmmer", "jackhmmer", "hmmsearch")
results_header_options = {'background': 'black', 'fg': 'red', 'height': 1, 'pady': 10, 'font': "comic 12"}
results_row_options = {'background': 'black', 'fg': 'white', 'height': 1, 'highlightbackground': 'black'}
class Generic_BLAST_search(PyMod_protocol):
"""
Base class, which is used to build up classes for specific similarity searches programs.
"""
#################################################################
# Initialize the launching of BLAST programs. #
#################################################################
# These attributes will be defined in each subclass for implementing a different similarity
# search protocol.
blast_version = None
protocol_name = None
exe_filename = None
# Common attributes.
xml_blast_output_file_name = "blast_out.xml"
default_max_number_of_hits = 100
e_value_threshold_default = 10.0
def additional_initialization(self):
self.blast_version_full_name = algs_full_names_dict[self.blast_version]
def launch_from_gui(self):
# Check if a correct selection is provided.
selected_sequences = self.pymod.get_selected_sequences()
if len(selected_sequences) == 0:
title = "Selection Error"
message = "Please select a sequence to perform a %s search" % (self.blast_version_full_name)
self.pymod.main_window.show_error_message(title, message)
return None
if len(selected_sequences) > 1:
title = "Selection Error"
message = "Please select only one sequence to perform a %s search" % (self.blast_version_full_name)
self.pymod.main_window.show_error_message(title, message)
return None
if not self.check_blast_program():
return None
# Gets the selected sequence. The main index will be used later to build the cluster.
self.blast_query_element = selected_sequences[0]
# Opens the options window.
self.build_blast_window()
def check_blast_program(self):
"""
Default method to check for an executable and locally installed databases.
Called as one of the first things when performing a similarity search. Actually used in the
PSI-BLAST, local BLAST and phmmer protocols. May be overridden in child classes.
"""
# Checks for the tool's directory.
if not self.tool.tool_dir_exists():
self.tool.tool_dir_not_found()
return False
# Checks for the tool's executable file.
exe_filepaths = self.get_similariry_search_exe_path()
for exe_filepath in exe_filepaths:
if not os.path.isfile(exe_filepath):
exe_dirpath = self.tool["exe_dir_path"].get_value()
exe_filename = os.path.basename(exe_filepath)
title = "%s is Missing" % (self.blast_version_full_name)
message = ("The %s executable file ('%s') does not exists in the executables"
" directory specified in the PyMod Options Window ('%s')."
" If you want to use this function, please specify in the Options"
" Window an executables directory where a '%s' file is"
" found." % (self.blast_version_full_name, exe_filename, exe_dirpath, exe_filename))
self.pymod.main_window.show_error_message(title, message)
return False
# Checks if a database directory is defined in the PyMod options.
db_dirpath = self.tool["database_dir_path"].get_value()
if db_dirpath.replace(" ", "") == "":
title = "No Database Directory"
message = ("No databases directory is defined for %s. Please define"
" a database directory in the PyMod options window in order"
" to perform a %s search." % (self.blast_version_full_name, self.blast_version_full_name))
self.pymod.main_window.show_error_message(title, message)
return False
# Check if the database directory actually exits.
if not os.path.isdir(db_dirpath):
title = "Database Directory not Found"
message = ("The database directory '%s' does not exists. Please define"
" an existing database directory in the PyMod options window"
" in order to perform a %s search." % (db_dirpath, self.blast_version_full_name))
self.pymod.main_window.show_error_message(title, message)
return False
# Checks if any databases are present.
self.databases_directories_list = self.build_blast_db_list()
if len(self.databases_directories_list) == 0:
title = "No Databases"
message = ("No %s databases were found at path '%s'. Please install"
" some databases in order to perform a %s"
" search." % (self.blast_version_full_name, db_dirpath, self.blast_version_full_name))
self.pymod.main_window.show_error_message(title, message)
return False
return True
def get_similariry_search_exe_path(self, return_dict=False):
"""
Get the absolute filepaths of the executables files needed to perform the
similarity search.
"""
if self.protocol_name != "hmmsearch": # Returns only one executable filepath.
exe_filepath_list = [os.path.join(self.tool["exe_dir_path"].get_value(),
get_exe_file_name(self.exe_filename))]
exe_filepath_dict = {self.exe_filename: exe_filepath_list[0]}
else: # Returns two executables filepath.
exe_filepath_list = []
exe_filepath_dict = {}
for exe_filename in self.all_exe_filenames:
exe_filepath = os.path.join(self.tool["exe_dir_path"].get_value(),
get_exe_file_name(exe_filename))
exe_filepath_list.append(exe_filepath)
exe_filepath_dict[exe_filename] = exe_filepath
if return_dict:
return exe_filepath_dict
else:
return exe_filepath_list
#################################################################
# BLAST programs options window. #
#################################################################
def build_blast_window(self):
"""
Builds a window containing the widget necessary to define the options for BLAST and
PSI-BLAST searches.
"""
blast_window_class_qt = self.get_blast_window_class_qt()
self.blast_options_window = blast_window_class_qt(self.pymod.main_window, protocol=self,
title="%s Search Options" % (self.blast_version_full_name),
upper_frame_title="Here you can modify options for %s" % (self.blast_version_full_name),
submit_command=self.blast_window_state)
self.blast_options_window.show()
#################################################################
# Actually Run BLAST programs. #
#################################################################
def blast_window_state(self):
"""
This function is called when the 'SUBMIT' button in the BLAST options window is pressed.
"""
# Do not proceed if users have not provided a correct set of input parameters through
# the GUI.
if not self.check_blast_input_parameters():
return False
self.get_options_from_gui()
self.blast_options_window.destroy()
# Performs a similarity search with the appropriate program.
blast_status = self.run_blast_program()
# Displays the window with results.
if blast_status and self.check_blast_results():
self.show_blast_output_window()
# Removes temp files at the end of the whole process, both if hits were found or not.
else:
self.finish_blast_search()
def check_blast_results(self):
"""
Checks if at least one hsp was identified in the search and stores the results in
'self.search_record'.
"""
# Parse the output file built by the search program.
self.search_record = self.get_search_record()
# Obtains a list of HSPs objects from Biopython.
self.hsp_list = self.build_hsp_list()
# Filters the BLAST record according to the advanced options.
if self.blast_options_window.showing_advanced_widgets:
self.filter_results_with_advanced_options()
# Only take the top hits defined by the "max hits" parameter in the GUI.
self.hsp_list = self.hsp_list[:self.max_hsp_num]
# Exit the whole process if no hits were found.
if len(self.hsp_list) == 0:
self.pymod.main_window.show_warning_message("%s Message" % self.blast_version_full_name,
"No hits were found by %s." % self.blast_version_full_name)
return False
# Returns 'True' if some hits were found.
else:
return True
def check_min_max_seqid_input(self):
if self.blast_options_window.showing_advanced_widgets:
min_id = float(self.blast_options_window.min_id_enf.getvalue())
max_id = float(self.blast_options_window.max_id_enf.getvalue())
if min_id >= max_id:
title = "Input Error"
message = "The 'Min Id%%' value (%s) must be lower than the 'Max Id%%' one (%s)." % (min_id, max_id)
self.pymod.main_window.show_error_message(title, message)
return False
return True
def get_options_from_gui(self):
"""
Get the options and parameters from the options window.
"""
self.max_hsp_num = int(self.blast_options_window.max_hits_enf.getvalue())
if self.blast_query_element.is_child():
self.new_sequences_import_mode = self.blast_options_window.get_import_mode()
else:
self.new_sequences_import_mode = "build-new"
self.get_options_from_gui_specific()
def get_options_from_gui_specific(self):
"""
To be implemented in each child classes.
"""
pass
def get_options_from_gui_blast(self):
"""
Get from the GUI those options which are common to all BLAST protocols.
"""
self.get_db_from_gui_blast()
self.evalue_cutoff = self.blast_options_window.e_value_threshold_enf.getvalue()
if self.blast_options_window.showing_advanced_widgets:
self.min_id = self.blast_options_window.min_id_enf.getvalue()
self.max_id = self.blast_options_window.max_id_enf.getvalue()
self.min_coverage = self.blast_options_window.min_coverage_enf.getvalue()
def get_db_from_gui_blast(self):
"""
Gets the database value for BLAST protocols from the GUI.
"""
self.db_path = self.get_database_from_gui()
def get_search_record(self):
# An attribute where is going to be stored a Biopython "Blast" record class object.
result_handle = open(os.path.join(self.output_directory, self.xml_blast_output_file_name), "r")
# The 'get_blast_record' is overridden in child classes (each class represents a specific
# BLAST vesion).
search_record = self.get_blast_record(result_handle)
result_handle.close()
return search_record
def filter_results_with_advanced_options(self):
min_id = float(self.min_id)
max_id = float(self.max_id)
min_coverage = float(self.min_coverage)
for hsp in self.hsp_list[:]:
# if ((int(self.max_id) <= hsp.pymod_info["seqid"]*100 < int(self.min_id)) or
# hsp.pymod_info["query_span"]*100 < int(self.min_coverage)):
# self.hsp_list.remove(hsp)
remove_hsp = False
seqid = hsp.pymod_info["seqid"]*100
if seqid < min_id:
remove_hsp = True
if seqid > max_id:
remove_hsp = True
if hsp.pymod_info["query_span"]*100 < min_coverage:
remove_hsp = True
if remove_hsp:
self.hsp_list.remove(hsp)
def get_hsp_info(self, hsp, full_query_sequence = None):
"""
Gets a Biopython HSP object and computes additional information on it and returns it as a
dictionary.
"""
if self.protocol_name in hmmer_protocols_names:
offset = 1
else:
offset = 0
# Gets the query span.
if self.protocol_name != "hmmsearch":
qt = len(str(self.blast_query_element.my_sequence).replace("-",""))
else:
qt = self.profile_length
qs = hsp.query_start + offset
qe = len(str(self.get_hsp_query_seq(hsp)).replace("-", "")) + qs
query_span = float(qe - qs)/float(qt)
# Gets the id% of the hsp.
matches, identities = self.get_hsp_matches(hsp)
idp = float(identities)/matches
# Gets the subject span.
hs = self.get_subj_start(hsp) + offset
he = len(self.get_hsp_subj_seq(hsp).replace("-","")) + hs
# Returns the information.
additional_infor_dict = {"identities": identities, "seqid": idp,
"query_span": query_span, "matches": matches,
"query_start": qs, "query_end": qe,
"sbjct_start": hs, "sbjct_end": he}
return additional_infor_dict
def get_hsp_matches(self, hsp):
q = self.get_hsp_query_seq(hsp)
h = self.get_hsp_subj_seq(hsp)
matches_count = 0
identities_count = 0
for qi, hi in zip(q, h):
if qi != "-" and hi != "-":
matches_count += 1
if qi == hi:
identities_count += 1
return matches_count, identities_count
def get_blast_output_basename(self):
basename = (clean_file_name(self.blast_query_element.compact_header) + "_" +
self.blast_version_full_name + "_" +
"search_%s" % (self.pymod.blast_cluster_counter) )
return basename
def finish_blast_search(self):
output_filename = self.get_blast_output_basename() + ".xml"
try:
os.rename(os.path.join(self.output_directory, self.xml_blast_output_file_name),
os.path.join(self.output_directory, output_filename))
for f in os.listdir(self.output_directory):
if not os.path.splitext(f)[-1] == ".xml":
os.remove(os.path.join(self.output_directory, f))
except IOError:
pass
def quit_protocol(self):
self.finish_blast_search()
PyMod_protocol.quit_protocol(self)
#################################################################
# Show BLAST programs output. #
#################################################################
def show_blast_output_window(self):
"""
Displays the window with results from BLAST in a new window.
"""
self.blast_output_window = Similarity_searches_results_window_qt(parent=self.pymod.main_window,
protocol=self)
self.blast_output_window.show()
def build_hsp_list(self):
hsp_list = []
for alignment in self.search_record.alignments:
for hsp in alignment.hsps:
hsp._title = alignment.title
# Gets additional information on the hsp (such as its the id % and query span).
hsp.pymod_info = self.get_hsp_info(hsp)
hsp_list.append(hsp)
# Sort by evalue.
hsp_list = list(sorted(hsp_list, key=lambda h: h.expect))
return hsp_list
def get_subject_name(self, hsp):
full_title = hsp._title
if len(full_title) > 100:
return full_title[0:100] + "..."
else:
return full_title
def get_hsp_evalue(self, hsp):
return hsp.expect
def get_hsp_identities(self, hsp):
return hsp.identities
def get_subj_start(self, hsp):
return hsp.sbjct_start
#################################################################
# Import BLAST results in PyMod. #
#################################################################
def blast_results_state(self):
"""
Called when the 'SUBMIT' button is pressed on some BLAST results window.
"""
# For each hsp takes the state of its check-box.
self.my_blast_map = [int(chk.isChecked()) for chk in self.blast_output_window.sbjct_checkbuttons_list]
# If the user selected at least one HSP.
if 1 in self.my_blast_map:
self.build_hits_to_import_list()
# This will actually import the sequences inside Pymod.
self.import_results_in_pymod()
self.blast_output_window.destroy()
def build_hits_to_import_list(self):
"""
Builds a list containing those hits that were selected by the user in the BLAST results
window.
"""
# This will be used to build PyMod elements out of the subjects of the HSP identified by
# BLAST.
self.hsp_imported_from_blast = []
self.total_hsp_counter = 0 # Counts the total number of hsp.
self.total_fetched_hsp_counter = 0 # Counts the total number of fetched hsp.
for hsp in self.hsp_list:
fetch_hsp = False
if self.my_blast_map[self.total_hsp_counter] == 1:
# Appends the hits (subjects).
self.hsp_imported_from_blast.append({"hsp": hsp, "title": self.get_subject_name(hsp)})
self.total_fetched_hsp_counter += 1
self.total_hsp_counter+=1
def import_results_in_pymod(self):
"""
Builds a cluster with the query sequence as a mother and retrieved hits as children.
"""
# The list of elements whose sequences will be updated according to the star alignment.
elements_to_update = [self.blast_query_element]
hsp_elements = []
use_hmmer_pdb = self.protocol_name in hmmer_protocols_names and self.db_filename.startswith("pdbaa")
#------------------------------------------------------------
# Builds a new cluster with the query and all the new hits. -
#------------------------------------------------------------
if self.new_sequences_import_mode == "build-new":
# Gets the original index of the query element in its container.
query_container = self.blast_query_element.mother
query_original_index = self.pymod.get_pymod_element_index_in_container(self.blast_query_element)
# Creates PyMod elements for all the imported hits and add them to the cluster.
for h in self.hsp_imported_from_blast:
# Gives them the query mother_index, to make them its children.
cs = self.pymod.build_pymod_element_from_hsp(self.get_hsp_subj_seq(h["hsp"]),
self.get_hsp_element_title(h, use_hmmer_pdb))
self.pymod.add_element_to_pymod(cs)
elements_to_update.append(cs)
hsp_elements.append(cs)
# Builds the "BLAST search" cluster element.
new_blast_cluster = self.pymod.add_new_cluster_to_pymod(
cluster_type="blast-cluster",
query=self.blast_query_element,
child_elements=elements_to_update,
algorithm=self.blast_version_full_name,
update_stars=False)
# Move the new cluster to the same position of the original query element in PyMod main
# window.
keep_in_mother_cluster = False
if keep_in_mother_cluster:
if not query_container.is_root():
query_container.add_child(new_blast_cluster)
self.pymod.change_pymod_element_list_index(new_blast_cluster, query_original_index)
else:
if query_container.is_root():
self.pymod.change_pymod_element_list_index(new_blast_cluster, query_original_index)
else:
self.pymod.change_pymod_element_list_index(new_blast_cluster, self.pymod.get_pymod_element_index_in_container(query_container)+1)
sibling_elements = []
#----------------------------------------------------------------------------
# Expand the original cluster of the query by appending to it the new hits. -
#----------------------------------------------------------------------------
elif self.new_sequences_import_mode == "expand":
# The list of elements whose sequences will be updated according to the star alignment.
elements_to_update = []
# Begins with the query element.
elements_to_update.append(self.blast_query_element)
sibling_elements = self.blast_query_element.get_siblings(sequences_only=True)
elements_to_update.extend(sibling_elements)
new_blast_cluster = self.blast_query_element.mother
# Creates PyMod elements for all the imported hits and add them to the cluster.
for h in self.hsp_imported_from_blast:
# Gives them the query mother_index, to make them its children.
cs = self.pymod.build_pymod_element_from_hsp(self.get_hsp_subj_seq(h["hsp"]),
self.get_hsp_element_title(h, use_hmmer_pdb))
self.pymod.add_element_to_pymod(cs)
elements_to_update.append(cs)
hsp_elements.append(cs)
new_blast_cluster.add_child(cs)
# Sets the query elements as the lead of its cluster.
self.blast_query_element.set_as_query()
#------------------------------------------------------------------------
# Builds a center star alignment in which the query is the center star. -
#------------------------------------------------------------------------
aligned_pairs = []
seqs = []
all_ids = []
query_seq = self.blast_query_element.my_sequence.replace("-", "")
seqs_to_update_dict = {self.blast_query_element.get_unique_index_header(): self.blast_query_element}
for hsp_i, hsp in enumerate(self.hsp_imported_from_blast):
hsp_query_seq = self.get_hsp_query_seq(hsp["hsp"])
hsp_subj_seq = self.get_hsp_subj_seq(hsp["hsp"])
if self.protocol_name in hmmer_protocols_names:
offset = 1
else:
offset = 0
hsp_q_res_len = len(hsp_query_seq.replace("-", ""))
hsp_q_start_index = hsp["hsp"].query_start - 1 + offset
# Substitute the original query sequence with the portion found in the hsp alignment.
updated_query_seq = query_seq[:hsp_q_start_index] + hsp_query_seq + query_seq[hsp_q_start_index+hsp_q_res_len:]
# Add gap extensions to the subject N and C-term.
updated_subj_seq = len(query_seq[:hsp_q_start_index])*"-" + hsp_subj_seq + len(query_seq[hsp_q_start_index+hsp_q_res_len:])*"-"
if query_seq.replace("-", "") != updated_query_seq.replace("-", ""):
raise Exception("The query sequence returned by '%s' is not the same of the original one." % self.blast_version)
# Add the (query, subject) tuple to 'aligned_pairs'.
aligned_pairs.append((updated_query_seq, updated_subj_seq))
# Add the gapless sequences and unique ids to the 'seqs' and 'all_ids'.
if hsp_i == 0:
seqs.append(query_seq)
all_ids.append(self.blast_query_element.get_unique_index_header())
seqs.append(hsp_subj_seq.replace("-", ""))
all_ids.append(hsp_elements[hsp_i].get_unique_index_header())
seqs_to_update_dict[hsp_elements[hsp_i].get_unique_index_header()] = hsp_elements[hsp_i]
# Add sibling elements if necessary.
if self.new_sequences_import_mode == "expand":
for sibling in sibling_elements:
aligned_pairs.append((self.blast_query_element.my_sequence, sibling.my_sequence))
seqs.append(sibling.my_sequence.replace("-", ""))
all_ids.append(sibling.get_unique_index_header())
seqs_to_update_dict[sibling.get_unique_index_header()] = sibling
# Adds empty (None) elements to the 'aligned_pairs' lists. In this way, the subjects will
# be pairwise aligned in the 'save_cstar_alignment' method.
aligned_pairs.extend([None]*int((len(seqs)-1)*(len(seqs)-2)/2))
# Joins the alignments and get the updated Biopython records.
recs = save_cstar_alignment(seqs=seqs, all_ids=all_ids, pairwise_alis=aligned_pairs)
#------------
# Finishes. -
#------------
# Updates the PyMod sequences.
for r in recs:
seqs_to_update_dict[r.id].my_sequence = str(r.seq)
# Cleans and update the PyMod main window.
self.finish_blast_search()
self.pymod.main_window.gridder(clear_selection=True, update_clusters=True, update_menus=True, update_elements=True)
def get_hsp_subj_seq(self, hsp_obj):
return str(hsp_obj.sbjct)
def get_hsp_query_seq(self, hsp_obj):
return str(hsp_obj.query)
def get_hsp_element_title(self, hsp, use_hmmer_pdb=False):
hsp_header = hsp["title"]
if use_hmmer_pdb:
# Changes the name of the element header in a format similar to those of BLAST hits from
# the NCBI databases.
try:
pdb_fields = hsp["title"].split("_")
pdb_id = pdb_fields[0]
pdb_chain = pdb_fields[1]
hsp_header = "pdb|%s|%s" % (pdb_id, pdb_chain)
except:
pass
return hsp_header
###############################################################################################
# GUI for BLAST options. #
###############################################################################################
class BLAST_base_options_window_qt(PyMod_protocol_window_qt):
"""
Base class for windows used in the similarity searches protocols.
"""
input_widget_width = 10
# geometry_string = "450x550"
def build_protocol_middle_frame(self):
#------------------
# Simple options. -
#------------------
# Let users decide how to import new sequences when the query is a child element (that
# is, it is already present in a cluster).
if self.protocol.blast_query_element.is_child():
self.import_mode_vbox = QtWidgets.QVBoxLayout()
self.import_mode_label = QtWidgets.QLabel("Hit Import Mode")
self.import_mode_vbox.addWidget(self.import_mode_label)
self.import_mode_button_group = QtWidgets.QButtonGroup()
self.middle_formlayout.addRow(self.import_mode_vbox)
# Build new alignment.
new_alignment_radiobutton = QtWidgets.QRadioButton("Build a new alignment with the query and the new hit sequences")
new_alignment_radiobutton._value = "build-new"
new_alignment_radiobutton.setChecked(True)
self.import_mode_vbox.addWidget(new_alignment_radiobutton)
self.import_mode_button_group.addButton(new_alignment_radiobutton)
# Expand alignment.
expand_alignment_radiobutton = QtWidgets.QRadioButton("Expand the existing alignment by appending the new hit sequences")
# "Expand the already existing cluster by appending to it the new hit sequences"
expand_alignment_radiobutton._value = "expand"
self.import_mode_vbox.addWidget(expand_alignment_radiobutton)
self.import_mode_button_group.addButton(expand_alignment_radiobutton)
# Each algorithm will have its own standard widgets.
self.build_algorithm_standard_options_widgets()
# E-value selection.
if self.protocol.protocol_name in hmmer_protocols_names:
e_value_threshold_enf_text = "c-Evalue Threshold"
else:
e_value_threshold_enf_text = "E-value Threshold"
self.e_value_threshold_enf = PyMod_entryfield_qt(label_text=e_value_threshold_enf_text,
value=str(self.protocol.e_value_threshold_default),
validate={'validator': 'real',
'min': 0.0, 'max': 1000.0})
self.middle_formlayout.add_widget_to_align(self.e_value_threshold_enf, validate=True)
# Max hit number selection.
self.max_hits_enf = PyMod_entryfield_qt(label_text="Max Number of Hits",
value=str(self.protocol.default_max_number_of_hits),
validate={'validator': 'integer',
'min': 1, 'max': 5000})
self.middle_formlayout.add_widget_to_align(self.max_hits_enf, validate=True)
# -------------------
# Advanced options. -
# -------------------
self.show_advanced_button()
# Minimum id% on with query.
self.min_id_enf = PyMod_entryfield_qt(label_text="Min Id% Threshold",
value="0",
validate={'validator': 'integer',
'min': 0, 'max': 100})
self.middle_formlayout.add_widget_to_align(self.min_id_enf, advanced_option=True, validate=True)
# Maximum id% on with query.
self.max_id_enf = PyMod_entryfield_qt(label_text="Max Id% Threshold",
value="100",
validate={'validator': 'integer',
'min': 0, 'max': 100})
self.middle_formlayout.add_widget_to_align(self.max_id_enf, advanced_option=True, validate=True)
# Minimum coverage on the query.
self.min_coverage_enf = PyMod_entryfield_qt(label_text="Min Coverage% Threshold",
value="0",
validate={'validator': 'integer',
'min': 0, 'max': 100})
self.middle_formlayout.add_widget_to_align(self.min_coverage_enf, advanced_option=True, validate=True)
# Advanced options for a specific algorithm.
self.build_algorithm_advanced_options_widgets()
self.middle_formlayout.set_input_widgets_width("auto")
def get_import_mode(self):
for radiobutton in self.import_mode_button_group.buttons():
if radiobutton.isChecked():
return radiobutton._value
raise ValueError("No import mode was selected.")
# Override in child classes.
def build_algorithm_standard_options_widgets(self):
pass
def build_algorithm_advanced_options_widgets(self):
pass
class Similarity_searches_results_window_qt(QtWidgets.QMainWindow):
"""
Window for showing similarity searches results.
"""
is_pymod_window = True
def __init__(self, parent, protocol):
super(Similarity_searches_results_window_qt, self).__init__(parent)
self.protocol = protocol
#########################
# Configure the window. #
#########################
self.setWindowTitle(self._get_window_title())
# Sets the central widget.
self.central_widget = QtWidgets.QWidget()
self.setCentralWidget(self.central_widget)
# The window has a main vbox layout.
self.main_vbox = QtWidgets.QVBoxLayout()
################
# Upper frame. #
################
title_text = self._get_upper_frame_title()
self.upper_frame_title = QtWidgets.QLabel(title_text)
self.main_vbox.addWidget(self.upper_frame_title)
#################
# Middle frame. #
#################
# Scroll area which contains the widgets, set as the centralWidget.
self.middle_scroll = QtWidgets.QScrollArea()
self.main_vbox.addWidget(self.middle_scroll)
# Widget that contains the collection of Vertical Box.
self.middle_widget = QtWidgets.QWidget()
# Scroll area properties.
self.middle_scroll.setWidgetResizable(True)
self.middle_scroll.setWidget(self.middle_widget)
# QFormLayout in the middle frame.
self.middle_formlayout = QtWidgets.QFormLayout()
self.middle_widget.setLayout(self.middle_formlayout)
#-----------------
# Buttons frame. -
#-----------------
# Set the frame and its layout.
self.buttons_frame = QtWidgets.QFrame()
self.middle_formlayout.addRow(self.buttons_frame)
self.buttons_hbox = QtWidgets.QHBoxLayout()
self.buttons_frame.setLayout(self.buttons_hbox)
# Build the control buttons.
self.blast_select_all_button = QtWidgets.QPushButton(text="Select All")
self.blast_select_all_button.clicked.connect(self.blast_select_all)
self.blast_select_none_button = QtWidgets.QPushButton(text="Select None")
self.blast_select_none_button.clicked.connect(self.blast_select_none)
self.blast_select_n_button = QtWidgets.QPushButton(text="Select Top:")
self.blast_select_n_button.clicked.connect(self.blast_select_n)
for button in [self.blast_select_all_button, self.blast_select_none_button, self.blast_select_n_button]:
self.buttons_hbox.addWidget(button)
# Build the line-edit for selecting only top entries.
self.blast_select_n_enf = PyMod_entryfield_qt(label_text="", value="10",
validate={'validator': 'integer',
'min': 1, 'max': 5000})
self.blast_select_n_enf.entry.setFixedWidth(70)
self.buttons_hbox.addWidget(self.blast_select_n_enf.entry)
# Align to the left all these widgets.
self.buttons_hbox.setAlignment(QtCore.Qt.AlignLeft)
for button in [self.blast_select_all_button, self.blast_select_none_button, self.blast_select_n_button]:
button.setFixedWidth(button.sizeHint().width()+30)
#-----------------
# Results frame. -
#-----------------
# Set the frame and its layout.
self.results_frame = QtWidgets.QFrame()
self.middle_formlayout.addRow(self.results_frame)
self.results_grid = QtWidgets.QGridLayout()
self.results_frame.setLayout(self.results_grid)
# Calls a method which actually displays the similarity searches results.
self.display_blast_hits()
# Align the gridded widgets to the left.
self.results_grid.setAlignment(QtCore.Qt.AlignLeft)
self.results_grid.setHorizontalSpacing(30)
#################
# Bottom frame. #
#################
self.main_button = QtWidgets.QPushButton("Submit")
self.main_button.clicked.connect(lambda a=None: self.protocol.blast_results_state())
self.main_vbox.addWidget(self.main_button)
self.main_button.setFixedWidth(self.main_button.sizeHint().width())
# Sets the main vertical layout.
self.central_widget.setLayout(self.main_vbox)
self.main_vbox.setAlignment(self.main_button, QtCore.Qt.AlignCenter)
def _get_window_title(self):
return "%s Results" % self.protocol.blast_version_full_name
def _get_upper_frame_title(self):
title_text = ("%s Output for: %s\nFound %s sequences\nPlease Select the Sequences to"
" Import" % (self.protocol.blast_version_full_name,
self.protocol.blast_query_element.compact_header,
len(self.protocol.hsp_list)))
return title_text
def display_blast_hits(self):
"""
This is used to display in the BLAST results window information for each
hit and a checkbutton to select it for importing it inside PyMod.
"""
# Shows the headers of the columns.
headers_font_style = "%s; color: %s; font-weight: bold" % (small_font_style, highlight_color)
self.blast_seq_label = QtWidgets.QLabel("Name")
self.blast_seq_label.setStyleSheet(headers_font_style)
self.results_grid.addWidget(self.blast_seq_label, 0, 0)
if not self.protocol.blast_version in hmmer_protocols_names:
evalue_header_text = "E-Value"
else:
evalue_header_text = "E-Value (c-Evalue)"
self.blast_e_val_label = QtWidgets.QLabel(evalue_header_text)
self.blast_e_val_label.setStyleSheet(headers_font_style)
self.results_grid.addWidget(self.blast_e_val_label, 0, 1)
if self.protocol.protocol_name != "hmmsearch":
self.blast_iden_label = QtWidgets.QLabel("Identity")
self.blast_iden_label.setStyleSheet(headers_font_style)
self.results_grid.addWidget(self.blast_iden_label, 0, 2)
self.query_span_label = QtWidgets.QLabel("Query span")
self.query_span_label.setStyleSheet(headers_font_style)
self.results_grid.addWidget(self.query_span_label, 0, 3)
self.subject_span_label = QtWidgets.QLabel("Subject span")
self.subject_span_label.setStyleSheet(headers_font_style)
self.results_grid.addWidget(self.subject_span_label, 0, 4)
# Displays in the results window the hsps found in the output file of the
# similarity search program.
self.blast_output_row = 1
self.sbjct_checkbuttons_list = [] # List containing the checkbutton widgets.
for hsp in self.protocol.hsp_list:
# Hit name and checkbox.
subject_name = self.protocol.get_subject_name(hsp)
hsp_checkbox = QtWidgets.QCheckBox(subject_name)
hsp_checkbox.setStyleSheet(small_font_style)
self.sbjct_checkbuttons_list.append(hsp_checkbox)
self.results_grid.addWidget(hsp_checkbox, self.blast_output_row, 0)
# E-value info.
if not self.protocol.blast_version in hmmer_protocols_names:
evalue_label_text = "%.2e" % (self.protocol.get_hsp_evalue(hsp))
else:
evalue_tuple = self.protocol.get_hsp_evalue(hsp)
evalue_label_text = "%.1e (%.1e)" % (evalue_tuple[0], evalue_tuple[1])
# evalue_label_text = "%.1e" % (evalue_tuple[0])
evalue_label = QtWidgets.QLabel(evalue_label_text)
evalue_label.setStyleSheet(small_font_style)
self.results_grid.addWidget(evalue_label, self.blast_output_row, 1)
# HSP seqid info.
if self.protocol.protocol_name != "hmmsearch":
id_text = "%s/%s (%.1f%%)" % (hsp.pymod_info["identities"], int(hsp.pymod_info["matches"]), hsp.pymod_info["seqid"]*100)
identities_label = QtWidgets.QLabel(id_text)
identities_label.setStyleSheet(small_font_style)
self.results_grid.addWidget(identities_label, self.blast_output_row, 2)
# Query span info.
span_info_text = "%s-%s (%.1f%%)" % (hsp.pymod_info["query_start"], hsp.pymod_info["query_end"], hsp.pymod_info["query_span"]*100)
span_info_label = QtWidgets.QLabel(span_info_text)
span_info_label.setStyleSheet(small_font_style)
self.results_grid.addWidget(span_info_label, self.blast_output_row, 3)
# Subject span info.
hspan_info_text = "%s-%s" % (hsp.pymod_info["sbjct_start"], hsp.pymod_info["sbjct_end"])
hspan_info_label = QtWidgets.QLabel(hspan_info_text)
hspan_info_label.setStyleSheet(small_font_style)
self.results_grid.addWidget(hspan_info_label, self.blast_output_row, 4)
self.blast_output_row += 1
def blast_select_all(self):
for chk in self.sbjct_checkbuttons_list:
chk.setChecked(True)
def blast_select_none(self):
for chk in self.sbjct_checkbuttons_list:
chk.setChecked(False)
def blast_select_n(self):
try:
select_top = int(self.blast_select_n_enf.getvalue())
self.blast_select_none()
count = 0
for chk in self.sbjct_checkbuttons_list:
chk.setChecked(True)
count += 1
if count == select_top:
break
except ValueError: # Can not convert the input value in an integer.
pass
| Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_protocols/similarity_searches_protocols/__init__.py | .py | 0 | 0 | null | Python |
3D | pymodproject/pymod | pymod3/pymod_lib/pymod_protocols/similarity_searches_protocols/phmmer.py | .py | 10,213 | 255 | # Copyright 2020 by Maria Giulia Prado, Giacomo Janson. All rights reserved.
# This code is part of the PyMod package and governed by its license. Please
# see the LICENSE file that should have been included as part of this package
# or the main __init__.py file in the pymod3 folder.
"""
Module for performing phmmer searches in PyMod. It mainly builds up on the code used to perform BLAST
searches.
"""
import os
from Bio import SearchIO
from pymod_lib.pymod_protocols.similarity_searches_protocols._base_blast import Generic_BLAST_search, BLAST_base_options_window_qt
from pymod_lib.pymod_threading import Protocol_exec_dialog
from pymod_lib.pymod_exceptions import catch_protocol_exception
from pymod_lib.pymod_gui.shared_gui_components_qt import PyMod_radioselect_qt
################################################################################################
# PHMMER. #
################################################################################################
class PHMMER_search(Generic_BLAST_search):
blast_version = "phmmer"
protocol_name = blast_version
exe_filename = "phmmer"
e_value_threshold_default = 1.0
def additional_initialization(self):
Generic_BLAST_search.additional_initialization(self)
self.tool = self.pymod.hmmer_tool
def get_blast_window_class_qt(self):
return Phmmer_options_window_qt
def build_blast_db_list(self):
db_dirpath = self.pymod.hmmer_tool["database_dir_path"].get_value()
db_list = [filename for filename in os.listdir(db_dirpath) if filename.endswith(".fasta")]
return db_list
def check_blast_input_parameters(self):
# Check if a valid database for PSI-BLAST was provided.
db_full_path = self.get_database_from_gui()
if db_full_path == None:
title = "Input Error"
message = "Please choose a valid database."
self.pymod.main_window.show_error_message(title, message)
return False
# Check all the other input fields.
try:
self.blast_options_window.check_general_input()
except Exception as general_input_error:
title = "Input Error"
message = str(general_input_error)
self.pymod.main_window.show_error_message(title, message)
return False
if not self.check_min_max_seqid_input():
return False
# Returns 'True' only if all input parameters are valid.
return True
@catch_protocol_exception
def run_blast_program(self):
return self.run_hmmer()
def run_hmmer(self):
"""
Launches a standalone version of PHMMER installed locally.
"""
# Builds a temporary file with the sequence of the query needed.
query_file_name = "query"
if self.protocol_name != "hmmsearch": # Saves a sequence file with only the query.
self.pymod.build_sequence_file([self.blast_query_element], query_file_name, file_format="fasta",
remove_indels=True, new_directory=self.output_directory)
else: # Saves the entire query alignment.
self.pymod.build_sequence_file(self.blast_query_element.get_children(), query_file_name,
file_format="fasta", remove_indels=False,
new_directory=self.output_directory)
# Sets some parameters needed to run PHMMER.
if self.protocol_name != "hmmsearch": # Get only one filepath.
exe_filepath = self.get_similariry_search_exe_path()[0]
else: # Get all filepaths.
exe_filepath_dict = self.get_similariry_search_exe_path(return_dict=True)
out_filepath = os.path.join(self.output_directory, "%s_out.txt" % self.protocol_name)
self.result_filepath = out_filepath
query_filepath = os.path.join(self.output_directory, "query.fasta")
db_dirpath = self.pymod.hmmer_tool["database_dir_path"].get_value()
db_filepath = os.path.join(db_dirpath, self.db_filename)
args = {"query_filepath": query_filepath,
"out_filepath": out_filepath,
"db_filepath": db_filepath,
"report_evalue": self.report_evalue}
args.update(self.additional_params)
if self.protocol_name != "hmmsearch": # Adds only one exec filepath.
args["exe_filepath"] = exe_filepath
else: # Adds two exec filepaths.
args["exe_filepath"] = exe_filepath_dict[self.all_exe_filenames[1]]
args["hmmbuild_exe_filepath"] = exe_filepath_dict[self.all_exe_filenames[0]]
# Actually runs phmmer.
if not self.pymod.use_protocol_threads:
self.execute_hmmer_program(**args)
else:
label_text = "Running %s. Please wait for the process to complete..." % self.blast_version_full_name
p_dialog = Protocol_exec_dialog(app=self.pymod.main_window, pymod=self.pymod,
function=self.execute_hmmer_program,
args=args,
title="Running %s" % self.blast_version_full_name,
label_text=label_text)
p_dialog.exec_()
return True
def execute_hmmer_program(self, query_filepath, out_filepath, db_filepath, exe_filepath, report_evalue=10e-6):
"""
Execute the locally installed PHMMER. Used when running PHMMER through the 'PHMMER'.
"""
phmmer_command_ls = [exe_filepath, "-o", out_filepath, "--domE", report_evalue,
query_filepath, db_filepath]
self.pymod.new_execute_subprocess(phmmer_command_ls)
def get_options_from_gui_specific(self):
self.db_filename = self.get_database_from_gui()
self.report_evalue = self.blast_options_window.e_value_threshold_enf.getvalue()
if self.blast_options_window.showing_advanced_widgets:
self.min_id = self.blast_options_window.min_id_enf.getvalue()
self.max_id = self.blast_options_window.max_id_enf.getvalue()
self.min_coverage = self.blast_options_window.min_coverage_enf.getvalue()
self.additional_params = self.blast_options_window.get_additional_hmmer_parameters()
def get_database_from_gui(self):
return self.blast_options_window.get_phmmer_database()
def get_search_record(self):
# Parse HMMER's output.
with open(self.result_filepath, "r") as result_handle:
phmmer_query_result = SearchIO.read(result_handle, 'hmmer3-text')
# Gets the hmmsearch profile length.
if self.protocol_name == "hmmsearch":
self.profile_length = None
with open(self.result_filepath, "r") as result_handle:
for line in result_handle:
# The length of the profile is stored in a line of the output
# file starting with "Query:".
if line.startswith("Query:"):
try:
self.profile_length = int(line.split()[-1].split("=")[1].replace("]", ""))
except (IndexError, TypeError):
pass
if self.profile_length is None:
self.profile_length = len(self.blast_query_element.get_children()[0].my_sequence)
return phmmer_query_result
def get_hsp_query_seq(self, hsp_obj):
return str(hsp_obj.query.seq).upper().replace(".", "-")
def get_hsp_subj_seq(self, hsp_obj):
return str(hsp_obj.hit.seq).upper()
def get_hsp_evalue(self, hsp):
return hsp.evalue, hsp.evalue_cond
def get_subj_start(self, hsp):
return hsp.hit_start
def build_hsp_list(self):
hsp_list = []
for hsp in self.search_record.hsps:
hsp._title = hsp.hit.id
# Gets additional information on the hsp (such as its the id % and query span).
hsp.pymod_info = self.get_hsp_info(hsp)
hsp_list.append(hsp)
# Sort by evalue.
hsp_list = list(sorted(hsp_list, key=lambda h: h.evalue))
return hsp_list
def finish_blast_search(self):
output_filename = self.get_blast_output_basename() + ".txt"
try:
os.rename(self.result_filepath, os.path.join(self.output_directory, output_filename))
except IOError:
pass
###################################################################################################
# GUI. #
###################################################################################################
class Phmmer_options_window_qt(BLAST_base_options_window_qt):
"""
Window for PHMMER searches.
"""
def build_algorithm_standard_options_widgets(self):
self.hmmer_database_labels_dict = {}
# A list containing information about the databases present in PyMod hmmer database folder.
db_list = []
for db in self.protocol.databases_directories_list:
db_label = "".join(db.split(".")[0:-1])
db_list.append(db_label)
self.hmmer_database_labels_dict[db_label] = db
# Makes the user choose the folder where the hmmer database files are stored locally.
self.hmmer_database_rds = PyMod_radioselect_qt(label_text="Database Selection",
buttons=db_list)
self.middle_formlayout.add_widget_to_align(self.hmmer_database_rds)
self.build_additional_hmmer_widgets()
def build_additional_hmmer_widgets(self):
pass
def build_algorithm_advanced_options_widgets(self):
pass
def get_phmmer_database(self):
return self.hmmer_database_labels_dict.get(self.hmmer_database_rds.getvalue(), None)
def get_additional_hmmer_parameters(self):
return {}
| Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.