desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Restore the gradient specified in state. **Arguments:** state A dictionary with same structure as those returned by :func:`saveState <pyqtgraph.GradientEditorItem.saveState>` Keys must include: - \'mode\': hsv or rgb - \'ticks\': a list of tuples (pos, (r,g,b,a))'
def restoreState(self, state):
self.setColorMode(state['mode']) for t in list(self.ticks.keys()): self.removeTick(t, finish=False) for t in state['ticks']: c = QtGui.QColor(*t[1]) self.addTick(t[0], c, finish=False) self.updateGradient() self.sigGradientChangeFinished.emit(self)
'Set the curves to fill between. Arguments must be instances of PlotDataItem or PlotCurveItem. Added in version 0.9.9'
def setCurves(self, curve1, curve2):
if (self.curves is not None): for c in self.curves: try: c.sigPlotChanged.disconnect(self.curveChanged) except (TypeError, RuntimeError): pass curves = [curve1, curve2] for c in curves: if ((not isinstance(c, PlotDataItem)) and (not isi...
'Change the fill brush. Acceps the same arguments as pg.mkBrush()'
def setBrush(self, *args, **kwds):
QtGui.QGraphicsPathItem.setBrush(self, fn.mkBrush(*args, **kwds))
'**Arguments:** size Specifies the fixed size (width, height) of the legend. If this argument is omitted, the legend will autimatically resize to fit its contents. offset Specifies the offset position relative to the legend\'s parent. Positive values offset from the left or top; negative values offs...
def __init__(self, size=None, offset=None):
GraphicsWidget.__init__(self) GraphicsWidgetAnchor.__init__(self) self.setFlag(self.ItemIgnoresTransformations) self.layout = QtGui.QGraphicsGridLayout() self.setLayout(self.layout) self.items = [] self.size = size self.offset = offset if (size is not None): self.setGeometry(...
'Add a new entry to the legend. **Arguments:** item A PlotDataItem from which the line and point style of the item will be determined or an instance of ItemSample (or a subclass), allowing the item display to be customized. title The title to display for this item. Simple HTML allowed.'
def addItem(self, item, name):
label = LabelItem(name) if isinstance(item, ItemSample): sample = item else: sample = ItemSample(item) row = self.layout.rowCount() self.items.append((sample, label)) self.layout.addItem(sample, row, 0) self.layout.addItem(label, row, 1) self.updateSize()
'Removes one item from the legend. **Arguments:** title The title displayed for this item.'
def removeItem(self, name):
for (sample, label) in self.items: if (label.text == name): self.items.remove((sample, label)) self.layout.removeItem(sample) sample.close() self.layout.removeItem(label) label.close() self.updateSize()
'See :func:`setImage <pyqtgraph.ImageItem.setImage>` for all allowed initialization arguments.'
def __init__(self, image=None, **kargs):
GraphicsObject.__init__(self) self.menu = None self.image = None self.qimage = None self.paintMode = None self.levels = None self.lut = None self.autoDownsample = False self.axisOrder = getConfigOption('imageAxisOrder') self._effectiveLut = None self.drawKernel = None sel...
'Change the composition mode of the item (see QPainter::CompositionMode in the Qt documentation). This is useful when overlaying multiple ImageItems. **Most common arguments:** QtGui.QPainter.CompositionMode_SourceOver Default; image replaces the background if it is opaque. Otherwise, it uses the alpha channel to b...
def setCompositionMode(self, mode):
self.paintMode = mode self.update()
'Set image scaling levels. Can be one of: * [blackLevel, whiteLevel] * [[minRed, maxRed], [minGreen, maxGreen], [minBlue, maxBlue]] Only the first format is compatible with lookup tables. See :func:`makeARGB <pyqtgraph.makeARGB>` for more details on how levels are applied.'
def setLevels(self, levels, update=True):
if (levels is not None): levels = np.asarray(levels) if (not fn.eq(levels, self.levels)): self.levels = levels self._effectiveLut = None if update: self.updateImage()
'Set the lookup table (numpy array) to use for this image. (see :func:`makeARGB <pyqtgraph.makeARGB>` for more information on how this is used). Optionally, lut can be a callable that accepts the current image as an argument and returns the lookup table to use. Ordinarily, this table is supplied by a :class:`HistogramL...
def setLookupTable(self, lut, update=True):
if (lut is not self.lut): self.lut = lut self._effectiveLut = None if update: self.updateImage()
'Set the automatic downsampling mode for this ImageItem. Added in version 0.9.9'
def setAutoDownsample(self, ads):
self.autoDownsample = ads self.qimage = None self.update()
'Scale and translate the image to fit within rect (must be a QRect or QRectF).'
def setRect(self, rect):
self.resetTransform() self.translate(rect.left(), rect.top()) self.scale((rect.width() / self.width()), (rect.height() / self.height()))
'Update the image displayed by this item. For more information on how the image is processed before displaying, see :func:`makeARGB <pyqtgraph.makeARGB>` **Arguments:** image (numpy array) Specifies the image data. May be 2D (width, height) or 3D (width, height, RGBa). The array dtype must be integer or fl...
def setImage(self, image=None, autoLevels=None, **kargs):
profile = debug.Profiler() gotNewData = False if (image is None): if (self.image is None): return else: gotNewData = True shapeChanged = ((self.image is None) or (image.shape != self.image.shape)) image = image.view(np.ndarray) if ((self.image is None)...
'Return the transform that maps from this image\'s input array to its local coordinate system. This transform corrects for the transposition that occurs when image data is interpreted in row-major order.'
def dataTransform(self):
tr = QtGui.QTransform() if (self.axisOrder == 'row-major'): tr.scale(1, (-1)) tr.rotate((-90)) return tr
'Return the transform that maps from this image\'s local coordinate system to its input array. See dataTransform() for more information.'
def inverseDataTransform(self):
tr = QtGui.QTransform() if (self.axisOrder == 'row-major'): tr.scale(1, (-1)) tr.rotate((-90)) return tr
'Estimate the min/max values of the image data by subsampling.'
def quickMinMax(self, targetSize=1000000.0):
data = self.image while (data.size > targetSize): ax = np.argmax(data.shape) sl = ([slice(None)] * data.ndim) sl[ax] = slice(None, None, 2) data = data[sl] return (nanmin(data), nanmax(data))
'Save this image to file. Note that this saves the visible image (after scale/color changes), not the original data.'
def save(self, fileName, *args):
if (self.qimage is None): self.render() self.qimage.save(fileName, *args)
'Returns x and y arrays containing the histogram values for the current image. For an explanation of the return format, see numpy.histogram(). The *step* argument causes pixels to be skipped when computing the histogram to save time. If *step* is \'auto\', then a step is chosen such that the analyzed data has dimension...
def getHistogram(self, bins='auto', step='auto', targetImageSize=200, targetHistogramSize=500, **kwds):
if (self.image is None): return (None, None) if (step == 'auto'): step = (int(np.ceil((self.image.shape[0] / targetImageSize))), int(np.ceil((self.image.shape[1] / targetImageSize)))) if np.isscalar(step): step = (step, step) stepData = self.image[::step[0], ::step[1]] if (bi...
'Set whether the item ignores transformations and draws directly to screen pixels. If True, the item will not inherit any scale or rotation transformations from its parent items, but its position will be transformed as usual. (see GraphicsItem::ItemIgnoresTransformations in the Qt documentation)'
def setPxMode(self, b):
self.setFlag(self.ItemIgnoresTransformations, b)
'return scene-size of a single pixel in the image'
def pixelSize(self):
br = self.sceneBoundingRect() if (self.image is None): return (1, 1) return ((br.width() / self.width()), (br.height() / self.height()))
'**Arguments:** xvals A list of x values (in data coordinates) at which to draw ticks. yrange A list of [low, high] limits for the tick. 0 is the bottom of the view, 1 is the top. [0.8, 1] would draw ticks in the top fifth of the view. pen The pen to use for drawing ticks. Default is grey...
def __init__(self, xvals=None, yrange=None, pen=None):
if (yrange is None): yrange = [0, 1] if (xvals is None): xvals = [] UIGraphicsItem.__init__(self) if (pen is None): pen = (200, 200, 200) self.path = QtGui.QGraphicsPathItem() self.ticks = [] self.xvals = [] self.yrange = [0, 1] self.setPen(pen) self.setYR...
'Set the pen to use for drawing ticks. Can be specified as any arguments valid for :func:`mkPen<pyqtgraph.mkPen>`'
def setPen(self, *args, **kwargs):
self.pen = fn.mkPen(*args, **kwargs)
'Set the x values for the ticks. **Arguments:** vals A list of x values (in data/plot coordinates) at which to draw ticks.'
def setXVals(self, vals):
self.xvals = vals self.rebuildTicks()
'Set the y range [low, high] that the ticks are drawn on. 0 is the bottom of the view, 1 is the top.'
def setYRange(self, vals):
self.yrange = vals self.rebuildTicks()
'Create a new LinearRegionItem. **Arguments:** values A list of the positions of the lines in the region. These are not limits; limits can be set by specifying bounds. orientation Options are LinearRegionItem.Vertical or LinearRegionItem.Horizontal. If not specified it will be vertical. brush Def...
def __init__(self, values=[0, 1], orientation=None, brush=None, movable=True, bounds=None):
UIGraphicsItem.__init__(self) if (orientation is None): orientation = LinearRegionItem.Vertical self.orientation = orientation self.bounds = QtCore.QRectF() self.blockLineSignal = False self.moving = False self.mouseHovering = False if (orientation == LinearRegionItem.Horizontal)...
'Return the values at the edges of the region.'
def getRegion(self):
r = [self.lines[0].value(), self.lines[1].value()] return (min(r), max(r))
'Set the values for the edges of the region. **Arguments:** rgn A list or tuple of the lower and upper values.'
def setRegion(self, rgn):
if ((self.lines[0].value() == rgn[0]) and (self.lines[1].value() == rgn[1])): return self.blockLineSignal = True self.lines[0].setValue(rgn[0]) self.blockLineSignal = False self.lines[1].setValue(rgn[1]) self.lineMoved() self.lineMoveFinished()
'Set the brush that fills the region. Can have any arguments that are valid for :func:`mkBrush <pyqtgraph.mkBrush>`.'
def setBrush(self, *br, **kargs):
self.brush = fn.mkBrush(*br, **kargs) self.currentBrush = self.brush
'Optional [min, max] bounding values for the region. To have no bounds on the region use [None, None]. Does not affect the current position of the region unless it is outside the new bounds. See :func:`setRegion <pyqtgraph.LinearRegionItem.setRegion>` to set the position of the region.'
def setBounds(self, bounds):
for l in self.lines: l.setBounds(bounds)
'Set lines to be movable by the user, or not. If lines are movable, they will also accept HoverEvents.'
def setMovable(self, m):
for l in self.lines: l.setMovable(m) self.movable = m self.setAcceptHoverEvents(m)
'Create a new isocurve item. **Arguments:** data A 2-dimensional ndarray. Can be initialized as None, and set later using :func:`setData <pyqtgraph.IsocurveItem.setData>` level The cutoff value at which to draw the isocurve. pen The color of the curve item. Can be anything valid for :fu...
def __init__(self, data=None, level=0, pen='w', axisOrder=None):
GraphicsObject.__init__(self) self.level = level self.data = None self.path = None self.axisOrder = (getConfigOption('imageAxisOrder') if (axisOrder is None) else axisOrder) self.setPen(pen) self.setData(data, level)
'Set the data/image to draw isocurves for. **Arguments:** data A 2-dimensional ndarray. level The cutoff value at which to draw the curve. If level is not specified, the previously set level is used.'
def setData(self, data, level=None):
if (level is None): level = self.level self.level = level self.data = data self.path = None self.prepareGeometryChange() self.update()
'Set the level at which the isocurve is drawn.'
def setLevel(self, level):
self.level = level self.path = None self.prepareGeometryChange() self.update()
'Set the pen used to draw the isocurve. Arguments can be any that are valid for :func:`mkPen <pyqtgraph.mkPen>`'
def setPen(self, *args, **kwargs):
self.pen = fn.mkPen(*args, **kwargs) self.update()
'Set the brush used to draw the isocurve. Arguments can be any that are valid for :func:`mkBrush <pyqtgraph.mkBrush>`'
def setBrush(self, *args, **kwargs):
self.brush = fn.mkBrush(*args, **kwargs) self.update()
'All keyword arguments are passed to setData().'
def __init__(self, **opts):
GraphicsObject.__init__(self) self.opts = dict(x=None, y=None, height=None, width=None, top=None, bottom=None, left=None, right=None, beam=None, pen=None) self.setData(**opts)
'Update the data in the item. All arguments are optional. Valid keyword options are: x, y, height, width, top, bottom, left, right, beam, pen * x and y must be numpy arrays specifying the coordinates of data points. * height, width, top, bottom, left, right, and beam may be numpy arrays, single values, or None to disab...
def setData(self, **opts):
self.opts.update(opts) self.path = None self.update() self.prepareGeometryChange() self.informViewBoundsChanged()
'**Arguments:** bounds QRectF with coordinates relative to view box. The default is QRectF(0,0,1,1), which means the item will have the same bounds as the view.'
def __init__(self, bounds=None, parent=None):
GraphicsObject.__init__(self, parent) self.setFlag(self.ItemSendsScenePositionChanges) if (bounds is None): self._bounds = QtCore.QRectF(0, 0, 1, 1) else: self._bounds = bounds self._boundingRect = None self._updateView()
'Called by ViewBox for determining the auto-range bounds. By default, UIGraphicsItems are excluded from autoRange.'
def dataBounds(self, axis, frac=1.0, orthoRange=None):
return None
'Called when the view widget/viewbox is resized/rescaled'
def viewRangeChanged(self):
self.setNewBounds() self.update()
'Update the item\'s bounding rect to match the viewport'
def setNewBounds(self):
self._boundingRect = None self.prepareGeometryChange()
'Return the shape of this item after expanding by 2 pixels'
def mouseShape(self):
shape = self.shape() ds = self.mapToDevice(shape) stroker = QtGui.QPainterPathStroker() stroker.setWidh(2) ds2 = stroker.createStroke(ds).united(ds) return self.mapFromDevice(ds2)
'Forwards all arguments to :func:`setData <pyqtgraph.PlotCurveItem.setData>`. Some extra arguments are accepted as well: **Arguments:** parent The parent GraphicsObject (optional) clickable If True, the item will emit sigClicked when it is clicked on. Defaults to False.'
def __init__(self, *args, **kargs):
GraphicsObject.__init__(self, kargs.get('parent', None)) self.clear() self.metaData = {} self.opts = {'pen': fn.mkPen('w'), 'shadowPen': None, 'fillLevel': None, 'brush': None, 'stepMode': False, 'name': None, 'antialias': getConfigOption('antialias'), 'connect': 'all', 'mouseWidth': 8} self.setClic...
'Sets whether the item responds to mouse clicks. The *width* argument specifies the width in pixels orthogonal to the curve that will respond to a mouse click.'
def setClickable(self, s, width=None):
self.clickable = s if (width is not None): self.opts['mouseWidth'] = width self._mouseShape = None self._boundingRect = None
'Set the pen used to draw the curve.'
def setPen(self, *args, **kargs):
self.opts['pen'] = fn.mkPen(*args, **kargs) self.invalidateBounds() self.update()
'Set the shadow pen used to draw behind tyhe primary pen. This pen must have a larger width than the primary pen to be visible.'
def setShadowPen(self, *args, **kargs):
self.opts['shadowPen'] = fn.mkPen(*args, **kargs) self.invalidateBounds() self.update()
'Set the brush used when filling the area under the curve'
def setBrush(self, *args, **kargs):
self.opts['brush'] = fn.mkBrush(*args, **kargs) self.invalidateBounds() self.update()
'Set the level filled to when filling under the curve'
def setFillLevel(self, level):
self.opts['fillLevel'] = level self.fillPath = None self.invalidateBounds() self.update()
'**Arguments:** x, y (numpy arrays) Data to show pen Pen to use when drawing. Any single argument accepted by :func:`mkPen <pyqtgraph.mkPen>` is allowed. shadowPen Pen for drawing behind the primary pen. Usually this is used to emphasize the curve by providing a high-contrast border. Any si...
def setData(self, *args, **kargs):
self.updateData(*args, **kargs)
'Return a QPainterPath representing the clickable shape of the curve'
def mouseShape(self):
if (self._mouseShape is None): view = self.getViewBox() if (view is None): return QtGui.QPainterPath() stroker = QtGui.QPainterPathStroker() path = self.getPath() path = self.mapToItem(view, path) stroker.setWidth(self.opts['mouseWidth']) mousePath...
'Defines labels to appear next to the color scale. Accepts a dict of {text: value} pairs'
def setLabels(self, l):
self.labels = l self.update()
'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 par...
def __init__(self, parent=None, name='ImageView', view=None, imageItem=None, *args):
QtGui.QWidget.__init__(self, parent, *args) self.levelMax = 4096 self.levelMin = 0 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.ignoreTimeLine = False if (v...
'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 third axis in a 3D image. For video, this array should contain the ti...
def setImage(self, img, autoRange=True, autoLevels=True, levels=None, axes=None, xvals=None, pos=None, scale=None, transform=None, autoHistogramRange=True):
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])): rais...
'Begin automatically stepping frames forward at the given rate (in fps). This can also be accessed by pressing the spacebar.'
def play(self, rate):
self.playRate = rate if (rate == 0): self.playTimer.stop() return self.lastPlayTime = ptime.time() if (not self.playTimer.isActive()): self.playTimer.start(16)
'Set the min/max intensity levels automatically to match the image data.'
def autoLevels(self):
self.setLevels(self.levelMin, self.levelMax)
'Set the min/max (bright and dark) levels.'
def setLevels(self, min, max):
self.ui.histogram.setLevels(min, max)
'Auto scale and pan the view around the image such that the image fills the view.'
def autoRange(self):
image = self.getProcessedImage() self.view.autoRange()
'Returns the image data after it has been processed by any normalization options in use. This method also sets the attributes self.levelMin and self.levelMax to indicate the range of data in the image.'
def getProcessedImage(self):
if (self.imageDisp is None): image = self.normalize(self.image) self.imageDisp = image (self.levelMin, self.levelMax) = list(map(float, self.quickMinMax(self.imageDisp))) return self.imageDisp
'Closes the widget nicely, making sure to clear the graphics scene and release memory.'
def close(self):
self.ui.roiPlot.close() self.ui.graphicsView.close() self.scene.clear() del self.image del self.imageDisp super(ImageView, self).close() self.setParent(None)
'Set the currently displayed frame index.'
def setCurrentIndex(self, ind):
self.currentIndex = np.clip(ind, 0, (self.getProcessedImage().shape[self.axes['t']] - 1)) self.updateImage() self.ignoreTimeLine = True self.timeLine.setValue(self.tVals[self.currentIndex]) self.ignoreTimeLine = False
'Move video frame ahead n frames (may be negative)'
def jumpFrames(self, n):
if (self.axes['t'] is not None): self.setCurrentIndex((self.currentIndex + n))
'Estimate the min/max values of *data* by subsampling.'
def quickMinMax(self, data):
while (data.size > 1000000.0): ax = np.argmax(data.shape) sl = ([slice(None)] * data.ndim) sl[ax] = slice(None, None, 2) data = data[sl] return (nanmin(data), nanmax(data))
'Process *image* using the normalization options configured in the control panel. This can be repurposed to process any data through the same filter.'
def normalize(self, image):
if self.ui.normOffRadio.isChecked(): return image div = self.ui.normDivideRadio.isChecked() norm = image.view(np.ndarray).copy() if div: norm = norm.astype(np.float32) if (self.ui.normTimeRangeCheck.isChecked() and (image.ndim == 3)): (sind, start) = self.timeIndex(self.normR...
'Return the ViewBox (or other compatible object) which displays the ImageItem'
def getView(self):
return self.view
'Return the ImageItem for this ImageView.'
def getImageItem(self):
return self.imageItem
'Return the ROI PlotWidget for this ImageView'
def getRoiPlot(self):
return self.ui.roiPlot
'Return the HistogramLUTWidget for this ImageView'
def getHistogramWidget(self):
return self.ui.histogram
'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.'
def export(self, fileName):
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 % (ba...
'Set the color map. **Arguments** colormap (A ColorMap() instance) The ColorMap to use for coloring images.'
def setColorMap(self, colormap):
self.ui.histogram.gradient.setColorMap(colormap)
'Set one of the gradients defined in :class:`GradientEditorItem <pyqtgraph.graphicsItems.GradientEditorItem>`. Currently available gradients are:'
@addGradientListToDocstring() def setPredefinedGradient(self, name):
self.ui.histogram.gradient.loadPreset(name)
'**Arguments:** namespace dictionary containing the initial variables present in the default namespace historyFile optional file for storing command history text initial text to display in the console window editor optional string for invoking code editor (called when stack trace entries a...
def __init__(self, parent=None, namespace=None, historyFile=None, text=None, editor=None):
QtGui.QWidget.__init__(self, parent) if (namespace is None): namespace = {} namespace['__console__'] = self self.localNamespace = namespace self.editor = editor self.multiline = None self.inCmd = False self.ui = template.Ui_Form() self.ui.setupUi(self) self.output = self....
'Return the list of previously-invoked command strings (or None).'
def loadHistory(self):
if (self.historyFile is not None): return pickle.load(open(self.historyFile, 'rb'))
'Store the list of previously-invoked command strings.'
def saveHistory(self, history):
if (self.historyFile is not None): pickle.dump(open(self.historyFile, 'wb'), history)
'Display the current exception and stack.'
def displayException(self):
tb = traceback.format_exc() lines = [] indent = 4 prefix = '' for l in tb.split('\n'): lines.append((((' ' * indent) + prefix) + l)) self.write('\n'.join(lines)) self.exceptionHandler(*sys.exc_info())
'If True, the console will catch all unhandled exceptions and display the stack trace. Each exception caught clears the last.'
def catchAllExceptions(self, catch=True):
self.ui.catchAllExceptionsBtn.setChecked(catch) if catch: self.ui.catchNextExceptionBtn.setChecked(False) self.enableExceptionHandling() self.ui.exceptionBtn.setChecked(True) else: self.disableExceptionHandling()
'If True, the console will catch the next unhandled exception and display the stack trace.'
def catchNextException(self, catch=True):
self.ui.catchNextExceptionBtn.setChecked(catch) if catch: self.ui.catchAllExceptionsBtn.setChecked(False) self.enableExceptionHandling() self.ui.exceptionBtn.setChecked(True) else: self.disableExceptionHandling()
'Initialize WidgetGroup, adding specified widgets into this group. widgetList can be: - a list of widget specifications (widget, [name], [scale]) - a dict of name: widget pairs - any QObject, and all compatible child widgets will be added recursively. The \'scale\' parameter for each widget allows QSpinBox to display a...
def __init__(self, widgetList=None):
QtCore.QObject.__init__(self) self.widgetList = weakref.WeakKeyDictionary() self.scales = weakref.WeakKeyDictionary() self.cache = {} self.uncachedWidgets = weakref.WeakKeyDictionary() if isinstance(widgetList, QtCore.QObject): self.autoAdd(widgetList) elif isinstance(widgetList, lis...
'Return true if we should automatically search the children of this object for more.'
def checkForChildren(self, obj):
iface = self.interface(obj) return ((len(iface) > 3) and iface[3])
'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.'
def test(self, im1, im2, message):
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, im...
'Extends QMatrix4x4.map() to allow mapping (3, ...) arrays of coordinates'
def map(self, obj):
if (isinstance(obj, np.ndarray) and (obj.ndim >= 2) and (obj.shape[0] in (2, 3))): return fn.transformCoordinates(self, obj) else: return QtGui.QMatrix4x4.map(self, obj)
'Set the input values of the flowchart. This will automatically propagate the new values throughout the flowchart, (possibly) causing the output to change.'
def setInput(self, **args):
self.inputWasSet = True self.inputNode.setOutput(**args)
'Return a dict of the values on the Flowchart\'s output terminals.'
def output(self):
return self.outputNode.inputValues()
'If the terminal belongs to the external Node, return the corresponding internal terminal'
def internalTerminal(self, term):
if (term.node() is self): if term.isInput(): return self.inputNode[term.name()] else: return self.outputNode[term.name()] else: return term
'Connect two terminals together within this flowchart.'
def connectTerminals(self, term1, term2):
term1 = self.internalTerminal(term1) term2 = self.internalTerminal(term2) term1.connectTo(term2)
'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.'
def process(self, **args):
data = {} order = self.processOrder() for (n, t) in self.inputNode.outputs().items(): if (n in args): data[t] = args[n] ret = {} for (c, arg) in order: if (c == 'p'): node = arg if (node is self.inputNode): continue outs...
'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'
def processOrder(self):
deps = {} tdeps = {} for (name, node) in self._nodes.items(): deps[node] = node.dependentNodes() for t in node.outputs().values(): tdeps[t] = t.dependentNodes() order = fn.toposort(deps) ops = [('p', n) for n in order] dels = [] for (t, nodes) in tdeps.items(): ...
'Triggered when a node\'s output values have changed. (NOT called during process()) Propagates new data forward through network.'
def nodeOutputChanged(self, startNode):
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()) order = fn.toposort(deps, nodes=[startNode...
'Return the graphicsItem which displays the internals of this flowchart. (graphicsItem() still returns the external-view item)'
def chartGraphicsItem(self):
return self.viewBox
'**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 specificat...
def __init__(self, name, terminals=None, allowAddInput=False, allowAddOutput=False, allowRemove=True):
QtCore.QObject.__init__(self) self._name = name self._bypass = False self.bypassButton = None self._graphicsItem = None self.terminals = OrderedDict() self._inputs = OrderedDict() self._outputs = OrderedDict() self._allowAddInput = allowAddInput self._allowAddOutput = allowAddOut...
'Return an unused terminal name'
def nextTerminalName(self, name):
name2 = name i = 1 while (name2 in self.terminals): name2 = ('%s.%d' % (name, i)) i += 1 return name2
'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\', ...)'
def addInput(self, name='Input', **args):
return self.addTerminal(name, io='in', **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\', ...)'
def addOutput(self, name='Output', **args):
return self.addTerminal(name, io='out', **args)
'Remove the specified terminal from this Node. May specify either the terminal\'s name or the terminal itself. Causes sigTerminalRemoved to be emitted.'
def removeTerminal(self, term):
if isinstance(term, Terminal): name = term.name() else: name = term term = self.terminals[name] 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.graphicsIte...
'Called after a terminal has been renamed Causes sigTerminalRenamed to be emitted.'
def terminalRenamed(self, term, oldName):
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)
'Add a new terminal to this Node with the given name. Extra keyword arguments are passed to Terminal.__init__. Causes sigTerminalAdded to be emitted.'
def addTerminal(self, name, **opts):
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) re...
'Return dict of all input terminals. Warning: do not modify.'
def inputs(self):
return self._inputs
'Return dict of all output terminals. Warning: do not modify.'
def outputs(self):
return self._outputs
'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\' ...
def process(self, **kargs):
return {}
'Return the GraphicsItem for this node. Subclasses may re-implement this method to customize their appearance in the flowchart.'
def graphicsItem(self):
if (self._graphicsItem is None): self._graphicsItem = NodeGraphicsItem(self) return self._graphicsItem
'Return the terminal with the given name'
def __getattr__(self, attr):
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]