The silx.gui.hdf5 package provides HDF5 widgets. This package is structured as follows.
PlotWidget and PlotWindow provides the user API. PlotWidget is a Qt widget (actually a QMainWindow) displaying a 1D, 2D plot area. It provides different interaction modes. PlotWindow is a Qt widget (actually a QMainWindow) which adds a set of toolbar buttons and associated functionalities to PlotWidget. The toolbar QActions are implemented in PlotActions.
Plot, PlotEvents and PlotInteraction implement the plotting API regardless of the rendering backend and regardless of its integration in Qt. The plotting API in defined in Plot. The different interaction modes (zoom, drawing, pan) are implemented in PlotInteraction. Each interaction mode is implemented with a state machine structure (implemented in Interaction). The different events emitted by Plot and by the interaction modes are created with helper functions defined in PlotEvents.
The PlotWindow uses additional widgets:
The widgets also use the following miscellaneous modules:
BackendBase defines the API any plot backend should provide in BackendBase. BackendMatplotlib implements a matplotlib backend. It is splitted in two classes:
For PlotWidget and Plot modules, see their respective documentations: PlotWidget, Plot.
The following modules are the modules used internally by the plot package.
Base class for Plot backends.
It documents the Plot backend API.
This API is a simplified version of PyMca PlotBackend API.
Class defining the API a backend of the Plot should provide.
Add a 1D curve given by x an y to the graph.
Parameters: |
|
---|---|
Returns: | The handle used by the backend to univocally access the curve |
Add an image to the plot.
Parameters: |
|
---|---|
Returns: | The handle used by the backend to univocally access the image |
Add an item (i.e. a shape) to the plot.
Parameters: |
|
---|---|
Returns: | The handle used by the backend to univocally access the item |
Add a point, vertical line or horizontal line marker to the plot.
Parameters: |
|
---|---|
Returns: | Handle used by the backend to univocally access the marker |
Remove an existing item from the plot.
Parameters: | item – A backend specific item handle returned by a add* method |
---|
Set the cursor shape.
To override in interactive backends.
Parameters: | cursor (str) – Name of the cursor shape or None |
---|
Toggle the display of a crosshair cursor and set its attributes.
To override in interactive backends.
Parameters: |
|
---|
Get a list of items at a pixel position.
Parameters: |
|
---|---|
Returns: | All picked items from back to front. One dict per item, with ‘kind’ key in ‘curve’, ‘marker’, ‘image’; ‘legend’ key, the item legend. and for curves, ‘xdata’ and ‘ydata’ keys storing picked position on the curve. |
Return type: | list of dict |
Set/Reset the color of a curve to show that it is active.
Parameters: |
|
---|
Trigger a Plot.replot().
Default implementation triggers a synchronous replot if plot is dirty. This method should be overridden by the embedding widget in order to provide an asynchronous call to replot in order to optimize the number replot operations.
Save the graph to a file (or a StringIO)
Parameters: |
|
---|
Set the main title of the plot.
Parameters: | title (str) – Title associated to the plot |
---|
Set the X axis label.
Parameters: | label (str) – label associated to the plot bottom X axis |
---|
Set the left Y axis label.
Parameters: |
|
---|
Reset the displayed area of the plot.
Autoscale any axis that is in autoscale mode. Keep current limits on axes not in autoscale mode
Extra margins can be added around the data inside the plot area. Margins are given as one ratio of the data range per limit of the data (xMin, xMax, yMin and yMax limits). For log scale, extra margins are applied in log10 of the data.
Parameters: | dataMargins (A 4-tuple of float as (xMin, xMax, yMin, yMax).) – Ratios of margins to add around the data inside the plot area for each side |
---|
Set the limits of the X and Y axes at once.
Parameters: |
|
---|
Get the graph X (bottom) limits.
Returns: | Minimum and maximum values of the X axis |
---|
Set the limits of X axis.
Parameters: |
|
---|
Get the graph Y (left) limits.
Parameters: | axis (str) – The axis for which to get the limits: left or right |
---|---|
Returns: | Minimum and maximum values of the Y axis |
Set the limits of the Y axis.
Parameters: |
|
---|
Set the X axis scale between linear and log.
Parameters: | flag (bool) – If True, the bottom axis will use a log scale |
---|
Set the Y axis scale between linear and log.
Parameters: | flag (bool) – If True, the left axis will use a log scale |
---|
Invert the Y axis.
Parameters: | flag (bool) – If True, put the vertical axis origin on the top |
---|
Set whether to keep data aspect ratio or not.
Parameters: | flag (Boolean, default True) – True to respect data aspect ratio |
---|
Set grid.
Parameters: | which – None to disable grid, ‘major’ for major grid, ‘both’ for major and minor grid |
---|
Get a list of strings with the supported colormap names.
The list should at least contain and start by: [‘gray’, ‘reversed gray’, ‘temperature’, ‘red’, ‘green’, ‘blue’]
Convert a position in data space to a position in pixels in the widget.
Parameters: |
|
---|---|
Returns: | The corresponding position in pixels or None if the data position is not in the displayed area. |
Return type: | A tuple of 2 floats: (xPixel, yPixel) or None. |
Convert a position in pixels in the widget to a position in the data space.
Parameters: |
|
---|---|
Returns: | The corresponding position in data space or None if the pixel position is not in the plot area. |
Return type: | A tuple of 2 floats: (xData, yData) or None. |
Matplotlib Plot backend.
Base class for Matplotlib backend without a FigureCanvas.
For interactive on screen plot, see BackendMatplotlibQt.
See BackendBase.BackendBase for public API documentation.
A QDialog widget to set-up the colormap.
It uses a description of colormaps as dict compatible with Plot.
To run the following sample code, a QApplication must be initialized.
Create the colormap dialog and set the colormap description and data range:
>>> from silx.gui.plot.ColormapDialog import ColormapDialog
>>> dialog = ColormapDialog()
>>> dialog.setColormap(name='red', normalization='log',
... autoscale=False, vmin=1., vmax=2.)
>>> dialog.setDataRange(1., 100.) # This scale the width of the plot area
>>> dialog.show()
Get the colormap description (compatible with Plot) from the dialog:
>>> cmap = dialog.getColormap()
>>> cmap['name']
'red'
It is also possible to display an histogram of the image in the dialog. This updates the data range with the range of the bins.
>>> import numpy
>>> image = numpy.random.normal(size=512 * 512).reshape(512, -1)
>>> hist, bin_edges = numpy.histogram(image, bins=10)
>>> dialog.setHistogram(hist, bin_edges)
The updates of the colormap description are also available through the signal: ColormapDialog.sigColormapChanged.
A QDialog widget to set the colormap.
Parameters: |
|
---|
Signal triggered when the colormap is changed.
It provides a dict describing the colormap to the slot. This dict can be used with Plot.
Returns the counts and bin edges of the displayed histogram.
Returns: | (hist, bin_edges) |
---|---|
Return type: | 2-tuple of numpy arrays |
Set the histogram to display.
This update the data range with the bounds of the bins. See setDataRange().
Parameters: |
|
---|
Returns the data range used for the histogram area.
Returns: | (dataMin, dataMax) or None if no data range is set |
---|---|
Return type: | 2-tuple of float |
Set the range of data to use for the range of the histogram area.
Parameters: |
|
---|
Return the colormap description as a dict.
See Plot for documentation on the colormap dict.
Set the colormap description
If some arguments are not provided, the current values are used.
Parameters: |
|
---|
Color conversion function and dictionary.
Convert color code ‘#RRGGBB’ and ‘#RRGGBBAA’ to (R, G, B, A)
It also convert RGB(A) values from uint8 to float in [0, 1]
Parameters: |
|
---|---|
Returns: | RGBA colors as floats in [0., 1.] |
Return type: | tuple |
Widget to handle regions of interest on curves displayed in a PlotWindow.
This widget is meant to work with PlotWindow.
Widget displaying a table of ROI information.
Parameters: | parent – See QWidget |
---|---|
Paran str name: | The title of this widget |
Signal of ROIs modifications.
Modification information if given as a dict with an ‘event’ key providing the type of events.
Type of events:
Load ROI widget information from a file storing a dict of ROI.
Parameters: | filename (str) – The file from which to load ROI |
---|
Table widget displaying ROI information.
See QTableWidget for constructor arguments.
Signal of ROI table modifications.
QDockWidget with a CurvesROIWidget connected to a PlotWindow.
It makes the link between the CurvesROIWidget and the PlotWindow.
Parameters: |
|
---|
This module provides an implementation of state machines for interaction.
Sample code of a state machine with two states (‘idle’ and ‘active’) with transitions on left button press/release:
from silx.gui.plot.Interaction import *
class SampleStateMachine(StateMachine):
class Idle(State):
def onPress(self, x, y, btn):
if btn == LEFT_BTN:
self.goto('active')
class Active(State):
def enter(self):
print('Enabled') # Handle enter active state here
def leave(self):
print('Disabled') # Handle leave active state here
def onRelease(self, x, y, btn):
if btn == LEFT_BTN:
self.goto('idle')
def __init__(self):
# State machine has 2 states
states = {
'idle': SampleStateMachine.Idle,
'active': SampleStateMachine.Active
}
super(TwoStates, self).__init__(states, 'idle')
# idle is the initial state
stateMachine = SampleStateMachine()
# Triggers a transition to the Active state:
stateMachine.handleEvent('press', 0, 0, LEFT_BTN)
# Triggers a transition to the Idle state:
stateMachine.handleEvent('release', 0, 0, LEFT_BTN)
See ClickOrDrag for another example of a state machine.
See Renaud Blanch, Michel Beaudouin-Lafon. Programming Rich Interactions using the Hierarchical State Machine Toolkit. In Proceedings of AVI 2006. p 51-58. for a discussion of using (hierarchical) state machines for interaction.
Base class for the states of a state machine.
This class is meant to be subclassed.
The state machine this state belongs to.
Useful to access data or methods that are shared across states.
Performs a transition to a new state.
Extra arguments are passed to the enter() method of the new state.
Parameters: | state (str) – The name of the state to go to. |
---|
State machine controller.
This is the entry point of a state machine. It is in charge of dispatching received event and handling the current active state.
Process an event with the state machine.
This method looks up for an event handler in the current state and then in the StateMachine instance. Handler are looked up as ‘onEventName’ method. If a handler is found, it is called with the provided extra arguments, and this method returns the return value of the handler. If no handler is found, this method returns None.
Parameters: | eventName (str) – Name of the event to handle |
---|---|
Returns: | The return value of the handler or None |
Left mouse button.
Right mouse button.
Middle mouse button.
State machine for left and right click and left drag interaction.
It is intended to be used through subclassing by overriding click(), beginDrag(), drag() and endDrag().
Widget displaying curves legends and allowing to operate on curves.
This widget is meant to work with PlotWindow.
List of values resulting in no symbol being displayed for a curve
Conversion from matplotlib-like linestyle to Qt
List of style values resulting in no line being displayed for a curve
Object displaying a curve linestyle and symbol.
Data model of curve legends.
It holds the information of the curve:
Object displaying a single item (i.e., a row) in the list.
Widget displaying a list of curve legends, line style and symbol.
Signal emitting a dict when an action is triggered by the user.
Contextual menu associated to items in a LegendListView.
Signal emitting a dict upon contextual menu actions.
Dialog box to input the name of a curve.
QDockWidget with a LegendSelector connected to a PlotWindow.
It makes the link between the LegendListView widget and the PlotWindow.
Parameters: |
|
---|
The PlotWindow this widget is attached to.
Widget providing a set of tools to draw masks on a PlotWidget.
This widget is meant to work with silx.gui.plot.PlotWidget.
A mask field with update operations.
Coords follows (row, column) convention and are in mask array coords.
This is meant for internal use by MaskToolsWidget.
Signal emitted when the mask has changed
Signal emitted when undo becomes possible/impossible
Signal emitted when redo becomes possible/impossible
Maximum number of operation stored in history list for undo
Get the current mask as a 2D array.
Parameters: | copy (bool) – True (default) to get a copy of the mask. If False, the returned array MUST not be modified. |
---|---|
Returns: | The array of the mask with dimension of the ‘active’ image. If there is no active image, an empty array is returned. |
Return type: | 2D numpy.ndarray of uint8 |
Set the mask to a new array.
Parameters: |
|
---|
Save current mask in a file
Parameters: |
|
---|---|
Returns: | True if save succeeded, False otherwise |
Set all values of the given mask level to 0.
Parameters: | level (int) – Value of the mask to set to 0. |
---|
Reset the mask to zero and change its shape
Parameters: | shape (2-tuple of int) – Shape of the new mask or None to have an empty mask |
---|
Invert mask of the given mask level.
0 values become level and level values become 0.
Parameters: | level (int) – The level to invert. |
---|
Mask/Unmask a rectangle of the given mask level.
Parameters: |
|
---|
Mask/Unmask a polygon of the given mask level.
Parameters: |
|
---|
Mask/Unmask points with given coordinates.
Parameters: |
|
---|
Mask/Unmask area from boolean mask.
Parameters: |
|
---|
Mask/Unmask a disk of the given mask level.
Parameters: |
|
---|
Mask/Unmask a line of the given mask level.
Parameters: |
|
---|
Widget with tools for drawing mask on an image in a PlotWidget.
Get the current mask as a 2D array.
Parameters: | copy (bool) – True (default) to get a copy of the mask. If False, the returned array MUST not be modified. |
---|---|
Returns: | The array of the mask with dimension of the ‘active’ image. If there is no active image, an empty array is returned. |
Return type: | 2D numpy.ndarray of uint8 |
Set the mask to a new array.
Parameters: |
|
---|---|
Returns: | None if failed, shape of mask as 2-tuple if successful. The mask can be cropped or padded to fit active image, the returned shape is that of the active image. |
Set the mode of multiple masks support.
Available modes:
Parameters: | mode (str) – The mode to use |
---|
The PlotWindow this widget is attached to.
Set the direction of the layout of the widget
Parameters: | direction – QBoxLayout direction |
---|
Load a mask from an image file.
Parameters: | filename (str) – File name from which to load the mask |
---|---|
Returns: | False on failure, True on success or a resized message when loading succeeded but shape of the image and the mask are different. |
Return type: | bool or str |
Save current mask in a file
Parameters: |
|
---|---|
Returns: | True if save succeeded, False otherwise |
Returns the color of the current selected level.
Return type: | A tuple or a python array |
---|
Reset the mask color at the given level to be defaultColors
Parameters: | level – the index of the mask for which we want to reset the color. If none we will reset color for all masks. |
---|
MaskToolsDockWidget embedded in a QDockWidget.
For integration in a PlotWindow.
Parameters: |
|
---|---|
Paran str name: | The title of this widget |
Get the current mask as a 2D array.
Parameters: | copy (bool) – True (default) to get a copy of the mask. If False, the returned array MUST not be modified. |
---|---|
Returns: | The array of the mask with dimension of the ‘active’ image. If there is no active image, an empty array is returned. |
Return type: | 2D numpy.ndarray of uint8 |
Set the mask to a new array.
Parameters: |
|
---|---|
Returns: | None if failed, shape of mask as 2-tuple if successful. The mask can be cropped or padded to fit active image, the returned shape is that of the active image. |
Matplotlib computationally modest image class.
Computationally modest image class.
Customization of https://github.com/ChrisBeaumont/ModestImage to allow extent support.
ModestImage is an extension of the Matplotlib AxesImage class better suited for the interactive display of larger images. Before drawing, ModestImage resamples the data array based on the screen resolution and view window. This has very little affect on the appearance of the image, but can substantially cut down on computation since calculations of unresolved or clipped pixels are skipped.
The interface of ModestImage is the same as AxesImage. However, it does not currently support setting the ‘extent’ property. There may also be weird coordinate warping operations for images that I’m not aware of. Don’t expect those to work either.
Matplotlib’s new colormaps
Functions to prepare events to be sent to Plot callback.
See Plot documentation for content of events
See Plot documentation for content of events
See Plot documentation for content of events
See Plot documentation for content of events
See Plot documentation for content of events
Implementation of the interaction for the Plot.
Pan plot content and zoom on wheel state machine.
Zoom-in/out state machine.
Zoom-in on selected area, zoom-out on right click, and zoom on mouse wheel.
Base class for drawing selection areas.
Drawing selection polygon area state machine.
Base class for drawing selection based on 2 input points.
Drawing rectangle selection area state machine.
Drawing line selection area state machine.
Base class for drawing selection area based on one input point.
Drawing a horizontal line selection area state machine.
Drawing a vertical line selection area state machine.
Base class for drawing free lines with tools such as pencil.
Manages focus across multiple event handlers
On press an event handler can acquire focus. By default it looses focus when all buttons are released.
Combine Zoom and ItemInteraction state machine.
Proxy to currently use state machine for interaction.
This allows to switch interactive mode.
Parameters: | plot – The Plot to apply interaction to |
---|
True to enable zoom on wheel, False otherwise.
Returns the current interactive mode as a dict.
The returned dict contains at least the key ‘mode’. Mode can be: ‘draw’, ‘pan’, ‘select’, ‘zoom’. It can also contains extra keys (e.g., ‘color’) specific to a mode as provided to setInteractiveMode().
Switch the interactive mode.
Parameters: |
|
---|
Set of widgets to associate with a :class:’PlotWidget’.
QWidget displaying coords converted from data coords of the mouse.
Provide this widget with a list of couple:
To run the following sample code, a QApplication must be initialized. First, create a PlotWindow and add a QToolBar where to place the PositionInfo widget.
>>> from silx.gui.plot import PlotWindow
>>> from silx.gui import qt
>>> plot = PlotWindow() # Create a PlotWindow to add the widget to
>>> toolBar = qt.QToolBar() # Create a toolbar to place the widget in
>>> plot.addToolBar(qt.Qt.BottomToolBarArea, toolBar) # Add it to plot
Then, create the PositionInfo widget and add it to the toolbar. The PositionInfo widget is created with a list of converters, here to display polar coordinates of the mouse position.
>>> import numpy
>>> from silx.gui.plot.PlotTools import PositionInfo
>>> position = PositionInfo(plot=plot, converters=[
... ('Radius', lambda x, y: numpy.sqrt(x*x + y*y)),
... ('Angle', lambda x, y: numpy.degrees(numpy.arctan2(y, x)))])
>>> toolBar.addWidget(position) # Add the widget to the toolbar
<...>
>>> plot.show() # To display the PlotWindow with the position widget
Parameters: |
|
---|
Toggle snapping use position to active curve.
The PlotWindow this widget is attached to.
QToolBar displaying and controlling the limits of a PlotWidget.
Parameters: |
|
---|
QToolBar providing profile tools operating on a PlotWindow.
Attributes:
To run the following sample code, a QApplication must be initialized. First, create a PlotWindow and add a ProfileToolBar.
>>> from silx.gui.plot import PlotWindow
>>> from silx.gui.plot.PlotTools import ProfileToolBar
>>> from silx.gui import qt
>>> plot = PlotWindow() # Create a PlotWindow
>>> toolBar = ProfileToolBar(plot=plot) # Create a profile toolbar
>>> plot.addToolBar(toolBar) # Add it to plot
>>> plot.show() # To display the PlotWindow with the profile toolbar
Parameters: |
|
---|
Miscellaneous utility functions
Returns updated limits by extending them with margins.
Parameters: | margins (A 4-tuple of floats as (xMinMargin, xMaxMargin, yMinMargin, yMaxMargin)) – The ratio of the margins to add or None for no margins. |
---|---|
Returns: | The updated limits |
Return type: | tuple of 4 or 6 floats: Either (xMin, xMax, yMin, yMax) or (xMin, xMax, yMin, yMax, y2Min, y2Max) if y2Min and y2Max are provided. |
Scale a 1D range given a scale factor and an center point.
Keeps the values in a smaller range than float32.
Parameters: |
|
---|---|
Returns: | The zoomed range. |
Return type: | tuple of 2 floats: (min, max) |
Zoom in/out plot given a scale and a center point.
Parameters: |
|
---|
Returns a new range with applied panning.
Moves the range according to panFactor. If isLog10 is True, converts to log10 before moving.
Parameters: |
|
---|---|
Returns: | New min and max value with pan applied. |
Return type: | 2-tuple of float. |