data_slicer package¶
The following is an auto-generated overview over the full package structure. You should be able to find some help about every module, class and function contained in the data_slicer package.
PIT and MainWindow (the data_slicer.pit module)¶
These classes are what you will be mostly interacting with when using PIT.
Of most interest should be data_slicer.pit.PITDataHandler
and
data_slicer.pit.MainWindow
as these two are accessible from PIT’s
ipython console as pit
and mw
.
PIT is a widget that combines slices from different sides with intensity distribution curves and other convenient features.
-
class
data_slicer.pit.
EmbedIPython
(**kwarg)[source]¶ Bases:
qtconsole.rich_jupyter_widget.RichJupyterWidget
Some voodoo to get an ipython console in a Qt application.
-
class
data_slicer.pit.
PITDataHandler
(main_window)[source]¶ Bases:
object
Object that keeps track of a set of 3D data and allows manipulations on it. In a Model-View-Controller framework this could be seen as the Model, while
MainWindow
would be the View part.-
get_data
()[source]¶ Convenience getter method. Allows writing
self.get_data()
instead ofself.data.get_value()
.
-
set_data
(data=None, axes=None)[source]¶ Convenience setter method. Allows writing
self.set_data(d)
instead ofself.data.set_value(d)
. Additionally allows setting new axes. If axes isNone
, the axes are reset to pixels.
-
prepare_data
(data, axes=[None, None, None])[source]¶ Load the specified data and prepare the corresponding z range. Then display the newly loaded data.
Parameters
data 3d array; the data to display axes len(3) list or array of 1d-arrays or None; the units along the x, y and z axes respectively. If any of those is None, pixels are used.
-
open
(filename)[source]¶ Open a file that’s readable by
dataloading
.
-
get_hprofile
()[source]¶ Return an array containing the y values displayed in the horizontal profile plot (mw.y_plot).
-
get_vprofile
()[source]¶ Return an array containing the x values displayed in the vertical profile plot (mw.x_plot).
-
get_iprofile
()[source]¶ Return an array containing the y values displayed in the integrated intensity profile plot (mw.integrated_plot).
-
update_z_range
()[source]¶ When new data is loaded or the axes are rolled, the limits and allowed values along the z dimension change.
-
reset_data
()[source]¶ Put all data and metadata into its original state, as if it was just loaded from file.
-
prepare_axes
()[source]¶ Create a list containing the three original x-, y- and z-axes and replace None with the amount of pixels along the given axis.
-
on_z_dim_change
()[source]¶ Called when either completely new data is loaded or the dimension from which we look at the data changed (e.g. through
roll_axes
). Update the z range and the integrated intensity plot.
-
update_image_data
()[source]¶ Get the right (possibly integrated) slice out of self.data, apply postprocessings and store it in self.image_data. Skip this if the z value happens to be out of range, which can happen if the image data changes and the z scale hasn’t been updated yet.
-
roll_axes
(i=1)[source]¶ Change the way we look at the data cube. While initially we see an Y vs. X slice in the main plot, roll it to Z vs. Y. A second call would roll it to X vs. Z and, finally, a third call brings us back to the original situation.
Parameters
i int; Number of dimensions to roll.
-
lineplot
(plot='main', dim=0, ax=None, n=10, offset=0.2, lw=0.5, color='k', label_fmt='{:.2f}', n_ticks=5, **getlines_kwargs)[source]¶ Create a matplotlib figure with n lines extracted out of one of the visible plots. The lines are normalized to their global maximum and shifted from each other by offset. See
get_lines
for more options on the extraction of the lines. This wraps theImagePlot
’s lineplot method.Parameters
plot str; either “main” or “cut”, specifies from which plot to extract the lines. dim int; either 0 or 1, specifies in which direction to take the lines. ax matplotlib.axes.Axes; the axes in which to plot. If None, create a new figure with a fresh axes. n int; number of lines to extract. offset float; spacing between neighboring lines. lw float; linewidth of the plotted lines. color any color argument understood by matplotlib; color of the plotted lines. label_fmt str; a format string for the ticklabels. n_ticks int; number of ticks to print. getlines_kwargs other kwargs are passed to get_lines
Returns
lines2ds list of Line2D objects; the drawn lines. xticks list of float; locations of the 0 intensity value of each line. xtickvalues list of float; if momenta were supplied, corresponding xtick values in units of momenta. Otherwise this is just a copy of xticks. xticklabels list of str; xtickvalues formatted according to label_fmt. See also
-
plot_all_slices
(dim=2, integrate=0, zs=None, labels='default', max_ppf=16, max_nfigs=2, **kwargs)[source]¶ Wrapper for
plot_cuts
. Plot all (or only the ones specified by zs) slices along dimension dim on separate suplots onto matplotlib figures.Parameters
dim int; one of (0,1,2). Dimension along which to take the cuts. integrate int or ‘full’; number of slices to integrate around each extracted cut. If ‘full’, take the maximum number possible, depending on zs and whether the number of cuts is reduced due to otherwise exceeding max_nfigs. zs 1D np.array; selection of indices along dimension dim. Only the given indices will be plotted. labels 1D array/list of length z. Optional labels to assign to the different cuts. By default the values of the respective axis are used. Set to None to suppress labels. max_ppf int; maximum number of plots per figure. max_nfigs int; maximum number of figures that are created. If more would be necessary to display all plots, a warning is issued and only every N’th plot is created, where N is chosen such that the whole ‘range’ of plots is represented on the figures. kwargs dict; keyword arguments passed on to pcolormesh
. Additionally, the kwarg gamma for power-law color mapping is accepted.See also
-
-
class
data_slicer.pit.
MainWindow
(data=None, background='default')[source]¶ Bases:
PyQt5.QtWidgets.QMainWindow
The main window of PIT. Defines the basic GUI layouts and acts as the controller, keeping track of the data and handling the communication between the different GUI elements.
-
title
= 'Python Image Tool'¶
-
size
= (1200, 800)¶
-
load_plugin
(plugin_name)[source]¶ Load a user supplied plugin and connect the plugin’s main class with PIT. The plugin should be a python module which is placed in the pythonpath or in the plugins directory.
Parameters
plugin_name str; name of the plugin module as it appears in the plugins directory.
-
brain
()[source]¶ Load the example dataset from an MRI brain scan.
This example data is taken from the OpenNeuro database. Openneuro Accession Number: ds000108 Authored by: Wager, T.D., Davidson, M.L., Hughes, B.L., Lindquist, M.A., Ochsner, K.N. (2008). Prefrontal-subcortical pathways mediating successful emotion regulation. Neuron, 59(6):1037-50. doi:
10.1016/j.neuron.2008.09.006
-
update_main_plot
(**image_kwargs)[source]¶ Change self.main_plot*`s currently displayed :class:`image_item <data_slicer.imageplot.ImagePlot.image_item>` to the slice of *self.data_handler.data corresponding to the current value of self.z.
-
set_axes
()[source]¶ Set the x- and y-scales of the plots. The
ImagePlot
object takes care of keeping the scales as they are, once they are set.
-
set_cmap
(cmap_name)[source]¶ Set the colormap to cmap where cmap is one of the names registered in
<data_slicer.cmaps>
which includes all matplotlib and custom cmaps.
-
transpose
()[source]¶ Transpose the main_plot, i.e. swap out its x- and y-axes. This wraps the main_plot’s
transpose
method.
-
keyPressEvent
(event)[source]¶ Define all responses to keyboard presses. Currently defined:
key action r Flip orientation of cutline. Also useful to bring it back to visibility.
-
set_image
(image=None, *args, **kwargs)[source]¶ Wraps the underlying ImagePlot3d’s set_image method. See
set_image()
. image can be None i.e. in order to just update the plot with a new colormap.
-
update_cut
()[source]¶ Take a cut of self.data_handler.data along self.cutline. This is used to update only the cut plot without affecting the main plot.
-
on_cutline_initialized
()[source]¶ Need to reconnect the signal to the cut_plot. And directly update the cut_plot.
-
set_alpha
(alpha)[source]¶ Set the alpha value of the currently used cmap. alpha can be a single float or an array of length
len(self.cmap.color)
.
-
set_gamma
(gamma=1)[source]¶ Set the exponent for the power-law norm that maps the colors to values. I.e. the values where the colours are defined are mapped like
y=x**gamma
.
-
Other modules¶
The following modules constitute the base of pit and other tools provided by data_slicer.
data_slicer.cmaps module¶
Convert some of the nicer matplotlib and kustom colormaps to pyqtgraph colormaps.
-
class
data_slicer.cmaps.
ds_cmap
(pos, color, mapping=1, mode=None, linearize=False, name='')[source]¶ Bases:
pyqtgraph.colormap.ColorMap
Simple subclass of
pyqtgraph.ColorMap
. Adds vmax, powerlaw normalization and a convenience function to change alpha.Changed in version 1.0.1: Made this an empty shell for fixing a bug with a change in colormaps in :module:`pyqtgraph`.
-
class
data_slicer.cmaps.
ds_cmap_legacy
(pos, color, gamma=1, **kwargs)[source]¶ Bases:
pyqtgraph.colormap.ColorMap
Simple subclass of
pyqtgraph.ColorMap
. Adds vmax, powerlaw normalization and a convenience function to change alpha.Changed in version 1.0.1: Renamed this to ds_cmap_legacy in order to fix a bug due to a change in colormaps in :module:`pyqtgraph`.
-
apply_transformations
()[source]¶ Recalculate the positions where the colormapping is defined by applying (in sequence) alpha, then a linear map to the range [0, vmax] and finally the powerlaw scaling:
pos' = pos**gamma
.
-
set_gamma
(gamma=1)[source]¶ Set the exponent for the power-law norm that maps the colors to values. I.e. the values where the colours are defined are mapped like
y=x**gamma
.
-
-
data_slicer.cmaps.
convert_matplotlib_to_pyqtgraph
(matplotlib_cmap, alpha=1)[source]¶ Take a matplotlib colormap and convert it to a pyqtgraph ColorMap.
Parameters
matplotlib_cmap either a str representing the name of a matplotlib colormap or a <matplotlib.colors.LinearSegmentedColormap>
or<matplotlib.colors.ListedColormap>
instance.alpha float or array of same length as there are defined colors in the matplotlib cmap; the alpha (transparency) value to be assigned to the whole cmap. matplotlib cmaps default to 1. Returns
pyqtgraph_cmap pyqtgraph.ColorMap
-
data_slicer.cmaps.
convert_ds_to_matplotlib
(data_slicer_cmap, cmap_name='converted_cmap')[source]¶ Create a matplotlib colormap from a
ds_cmap
instance.Parameters
data_slicer_cmap ds_cmap
cmap_name str; optional name for the created cmap. Returns
matplotlib_cmap <matplotlib.colors.LinearSegmentedColormap>
-
data_slicer.cmaps.
load_custom_cmap
(filename)[source]¶ Create a
ds_cmap
instance from data stored in a file with three columns, red, green and blue - either in integer form from 0-255 or as floats from 0.0 to 1.0 (ignores fourth alpha column). The suffix can be left out in the file name. Also, an _r can be appended to the colormap name to indicate that the inverse of a cmap is requested (e.g. my_cmap_r will give the reverse of my_cmap).
-
data_slicer.cmaps.
load_cmap
(cmap_name)[source]¶ Return a ds_cmap object for the colormap specified by cmap_name. cmap_name can be either
- one of the matplotlib colormap names
2. one of the colormap names supplied by the data slicer package. At the time of this writing, these are rainbow_light, neutrons and kocean. This list is not regularly updated. Check the .cmap files in the data/ directory of the installation (loacation depends on your system) to find out all options.
3. any file found in the cmaps/ subdirectory of your config directory (check documentation).
data_slicer.cutline module¶
-
class
data_slicer.cutline.
CustomizableLineSegmentROI
(*args, **kwargs)[source]¶ Bases:
pyqtgraph.graphicsItems.ROI.LineSegmentROI
Subclass of
LineSegmentROI
. Implements a few features that were missing from the parent class, namely customizable hover pen.
-
class
data_slicer.cutline.
CustomizableHandle
(*args, **kwargs)[source]¶ Bases:
pyqtgraph.graphicsItems.ROI.Handle
Same concept as
CustomizableLineSegmentROI <data_slicer.cutline.CustomizableLineSegmentROI
>. Subclass to allow customization of hover pen.Note
This class is unused because that would require setting these handles as the handles for CustomizableLineSegmentROI. Too much work for a relatively unimportant feature.
-
class
data_slicer.cutline.
Cutline
(plot_widget=None, orientation='horizontal', handles=(None, None), **kwargs)[source]¶ Bases:
PyQt5.QtCore.QObject
Wrapper class allowing easy adding and removing of
pyqtgraph.LineSegmentROI
to apyqtgraph.PlotWidget
. It both has-a LineSegmentROI and has-a PlotWidget and handles interactions between the two.Needs to inherit from
pyqtgraph.qt.QtCore.QObject
in order to have signals.Signals
sig_region_changed wraps the underlying LineSegmentROI
’s sigRegionChange. Emitted whenever the ROI is moved or changed.sig_initialized emitted when a new LineSegmentROI
has been created and assigned as thisCutline
’s roi.-
sig_initialized
¶
-
add_to_plot
(plot_widget)[source]¶ Add this cutline to a
PlotWidget
. This is effectively implemented by setting thisCutline
’s plot attribute to the given plot_widget.
-
set_handle_style
(radius=8, color=(200, 255, 200), width=2)[source]¶ Set the size and pen of the handles.
-
calculate_endpoints
()[source]¶ Get sensible initial values for the endpoints of the
LineSegmentROI
from thepyqtrgaph.PlotWidget
’s current view range. Depending on the state of self.orientation these endpoints correspond either to a vertical or horizontal line centered at the center of the plot and spanning exactly the whole plot range.Returns a tuple of len(2) lists: (lower_left, top_right) corresponding to the two endpoints.
-
data_slicer.dataloading module¶
Tools for putting different data formats into suitable numpy arrays.
-
class
data_slicer.dataloading.
Dataloader
(*args, **kwargs)[source]¶ Bases:
object
Base dataloader class (interface) from which others inherit some methods (specifically the
__repr__()
function).-
name
= 'Base'¶
-
load_data
(*args, **kwargs)[source]¶ Method stub to be overwritten by subclasses. Return data in the form of an argparse.Namespace object D with the following structure:
D.data np.array containing the data. D.axes list of length len(D.data.shape). Contains a 1d np.array representing each axis (or None)
-
-
class
data_slicer.dataloading.
Dataloader_Pickle
(*args, **kwargs)[source]¶ Bases:
data_slicer.dataloading.Dataloader
Confer documentation of
load_data()
.-
name
= 'Pickle'¶
-
-
class
data_slicer.dataloading.
Dataloader_3dtxt
(*args, **kwargs)[source]¶ Bases:
data_slicer.dataloading.Dataloader
Confer documentation of
load_data()
.-
name
= '3d txt'¶
-
load_data
(filename)[source]¶ Load data of shape (nx, ny, nz) that is stored in a .txt file in the format:
#Z Y X I(X, Y, Z) z0 y0 x0 I(0, 0, 0) z1 y0 x0 I(0, 0, 1) z2 y0 x0 I(0, 0, 2) z3 y0 x0 I(0, 0, 3) ... z(nz-1) y0 x0 I(0, 0, nz-1) z(nz) y0 x0 I(0, 0, nz) z0 y1 x0 I(0, 1, 0) z1 y1 x0 I(0, 1, 1) z2 y1 x0 I(0, 1, 2) ... z(nz-1) y1 x0 I(0, 1, nz-1) z(nz) y1 x0 I(0, 1, nz) ... ... z0 y(ny) x0 I(0, ny, 0) z1 y(ny) x0 I(0, ny, 1) ... z(nz) y(ny) x0 I(0, ny, nz) z0 y0 x1 I(1, 0, 0) z1 y0 x1 I(1, 0, 1) ... ... z(nz) y(ny) x(nx) I(nz, ny, nx)
-
-
data_slicer.dataloading.
load_data
(filename, exclude=None, suppress_warnings=False)[source]¶ Try to load some dataset ‘filename’ by iterating through all_dls and appliyng the respective dataloader’s load_data method. If it works: great. If not, try with the next dataloader. Collects and prints all raised exceptions in case that no dataloader succeeded.
-
data_slicer.dataloading.
three_d_to_txt
(outfilename, data, axes=[None, None, None], force=False)[source]¶ Create a txt file that can be read by
Dataloader_txt
.Parameters
outfilename str; filename and/or path to the file to write into. data np.array; 3d array of the data. axes list; [xaxis, yaxis, zaxis]. Any of these can be None, in which case incremental integers will be used. force boolean; Whether or not to overwrite an existing file. If False and a file of outfilename exists, an Exception is raised.
-
data_slicer.dataloading.
dump
(D, filename, force=False)[source]¶ Wrapper for
pickle.dump()
. Does not overwrite if a file of the given name already exists, unless force is True.Parameters
D python object to be stored. filename str; name of the output file to create. force boolean; if True, overwrite existing files.
data_slicer.dsviewbox module¶
Subclass of ViewBox with custom menu items.
-
class
data_slicer.dsviewbox.
DSViewBoxMenu
(*args, **kwargs)[source]¶ Bases:
pyqtgraph.graphicsItems.ViewBox.ViewBoxMenu.ViewBoxMenu
Subclass of ViewBoxMenu with custom menu items.
-
class
data_slicer.dsviewbox.
DSViewBox
(imageplot, *args, **kwargs)[source]¶ Bases:
pyqtgraph.graphicsItems.ViewBox.ViewBox.ViewBox
Subclass of ViewBox with custom menu items, as defined in
DSViewBoxMenu
.
data_slicer.imageplot module¶
matplotlib pcolormesh equivalent in pyqtgraph (more or less)
-
class
data_slicer.imageplot.
MPLExportDialog
(imageplot, *args, **kwargs)[source]¶ Bases:
PyQt5.QtWidgets.QDialog
A dialog that provides a GUI to
mpl_export()
.-
figwidth
= 5¶
-
figheight
= 5¶
-
-
class
data_slicer.imageplot.
Crosshair
(pos=(0, 0))[source]¶ Bases:
object
Crosshair made up of two InfiniteLines.
-
set_color
(linecolor=(255, 255, 0, 255), hover_color=(195, 155, 0, 255))[source]¶ Set the color and hover color of both InfiniteLines that make up the crosshair. The arguments can be any pyqtgraph compatible color specifiers.
-
move_to
(pos)[source]¶ Parameters
pos 2-tuple; x and y coordinates of the desired location of the crosshair in data coordinates.
-
update_position_h
()[source]¶ Callback for the . Whenever the value of this TracedVariable is updated (possibly from outside this Crosshair object), put the crosshair to the appropriate position.
-
on_dragged_h
()[source]¶ Callback for dragging of InfiniteLines. Their visual position should be reflected in the TracedVariables self.hpos and self.vpos.
-
-
class
data_slicer.imageplot.
ImagePlot
(image=None, parent=None, background='default', name=None, **kwargs)[source]¶ Bases:
pyqtgraph.widgets.PlotWidget.PlotWidget
A PlotWidget which mostly contains a single 2D image (intensity distribution) or a 3D array (distribution of RGB values) as well as all the nice pyqtgraph axes panning/rescaling/zooming functionality.
In addition, this allows one to use custom axes scales as opposed to being limited to pixel coordinates.
Signals
sig_image_changed emitted whenever the image is updated sig_axes_changed emitted when the axes are updated sig_clicked emitted when user clicks inside the imageplot -
sig_image_changed
¶
-
sig_axes_changed
¶
-
sig_clicked
¶
-
show_cursor
(show=True)[source]¶ Toggle whether or not to show a crosshair cursor that tracks the mouse movement.
-
on_mouse_move
(pos)[source]¶ Slot for mouse movement over the plot. Calculate the mouse position in data coordinates and move the crosshair_cursor there.
Parameters
pos QPointF object; x and y position of the mouse as returned by .
-
mousePressEvent
(event)[source]¶ Figure out where the click happened in data coordinates and make the position available through the signal .
-
remove_image
()[source]¶ Removes the current image using the parent’s
removeItem pyqtgraph.PlotWidget.removeItem()
function.
-
set_image
(image, emit=True, *args, **kwargs)[source]¶ Expects either np.arrays or pg.ImageItems as input and sets them correctly to this PlotWidget’s Image with addItem. Also makes sure there is only one Image by deleting the previous image.
Parameters
image np.ndarray or pyqtgraph.ImageItem instance; the image to be displayed. emit bool; whether or not to emit (kw)args positional and keyword arguments that are passed on to pyqtgraph.ImageItem
-
set_xscale
(xscale, update=False)[source]¶ Set the xscale of the plot. xscale is an array of the length
len(self.image_item.shape[0])
.
-
set_yscale
(yscale, update=False)[source]¶ Set the yscale of the plot. yscale is an array of the length
len(self.image_item.image.shape[1])
.
-
release_viewrange
()[source]¶ Undo the effects of
fix_viewrange
-
mpl_export
(*args, figsize=(5, 5), title='', xlabel='', ylabel='', dpi=300)[source]¶ Export the content of this plot to a png image using matplotlib. The resulting image will have a white background and black ticklabes and should therefore be more readable than pyqtgraph’s native plot export options.
Parameters
figsize tuple of float; (height, width) of figure in inches title str; figure title xlabel str; x axis label ylabel str; y axis label dpi int; png resolution in pixels per inch args positional arguments are absorbed and discarded (necessary to connect this method to signal handling)
-
lineplot
(ax, dim=0, n=10, offset=0.2, lw=0.5, color='k', label_fmt='{:.2f}', n_ticks=5, **getlines_kwargs)[source]¶ Create a matplotlib plot with n lines extracted out of one of the visible plots. The lines are normalized to their global maximum and shifted from each other by offset. See
get_lines
for more options on the extraction of the lines.Parameters
plot str; either “main” or “cut”, specifies from which plot to extract the lines. dim int; either 0 or 1, specifies in which direction to take the lines. ax matplotlib.axes.Axes; the axes in which to plot. n int; number of lines to extract. offset float; spacing between neighboring lines. lw float; linewidth of the plotted lines. color any color argument understood by matplotlib; color of the plotted lines. label_fmt str; a format string for the ticklabels. n_ticks int; number of ticks to print. getlines_kwargs other kwargs are passed to get_lines
Returns
lines2ds list of Line2D objects; the drawn lines. xticks list of float; locations of the 0 intensity value of each line. xtickvalues list of float; if momenta were supplied, corresponding xtick values in units of momenta. Otherwise this is just a copy of xticks. xticklabels list of str; xtickvalues formatted according to label_fmt.
-
-
class
data_slicer.imageplot.
CrosshairImagePlot
(*args, **kwargs)[source]¶ Bases:
data_slicer.imageplot.ImagePlot
An imageplot with a draggable crosshair.
-
class
data_slicer.imageplot.
CursorPlot
(parent=None, background='default', name=None, orientation='vertical', slider_width=1, **kwargs)[source]¶ Bases:
pyqtgraph.widgets.PlotWidget.PlotWidget
Implements a simple, draggable scalebar represented by a line (
pyqtgraph.InfiniteLine) on an axis (:class:`pyqtgraph.PlotWidget). The current position of the slider is tracked with the :class:`TracedVariable
self.pos and its width with the TracedVariable self.slider_width.-
hover_color
= (195, 155, 0, 255)¶
-
get_data
()[source]¶ Get the currently displayed data as a tuple of arrays, one containing the x values and the other the y values.
Returns
x array containing the x values. y array containing the y values.
-
register_traced_variable
(traced_variable)[source]¶ Set self.pos to the given TracedVariable instance and connect the relevant slots to the signals. This can be used to share a TracedVariable among widgets.
-
on_position_change
()[source]¶ Callback for the . Set the value of the TracedVariable instance self.pos to the current slider position.
-
on_allowed_values_change
()[source]¶ Callback for the . With a change of the allowed values in the TracedVariable, we should update our bounds accordingly. The number of allowed values can also give us a hint for a reasonable maximal width for the slider.
-
set_position
()[source]¶ Callback for the . Whenever the value of this TracedVariable is updated (possibly from outside this Scalebar object), put the slider to the appropriate position.
-
set_bounds
(lower, upper)[source]¶ Set both, the displayed area of the axis as well as the the range in which the slider (InfiniteLine) can be dragged to the interval [lower, upper].
-
set_secondary_axis
(min_val=None, max_val=None)[source]¶ Create (or replace) a second x-axis on the top which ranges from min_val to max_val. This is the right axis in case of the horizontal orientation.
-
set_slider_pen
(color=None, width=None, hover_color=None)[source]¶ Define the color and thickness of the slider (InfiniteLine object
pyqtgraph.InfiniteLine
) and store these attribute in self.slider_width and self.cursor_color).
-
increase_width
(step=1)[source]¶ Increase (or decrease) self.slider_width by step units of odd numbers (such that the line always has a well defined center at the value it is positioned at).
-
-
class
data_slicer.imageplot.
Scalebar
(*args, **kwargs)[source]¶ Bases:
data_slicer.imageplot.CursorPlot
Simple subclass of
CursorPlot
that is intended to simulate a scalebar. This is achieved by providing simply a long, flat plot without any data and no y axis, but the same draggable slider as in CursorPlot.Attributes
textItems list of (t, (rx, ry)) tuples; t is a pyqtgraph.TextItem
instance and rx, ry are floats in the range [0, 1] indicating the relative positioning of the textitems inside the Scalebar.-
set_size
(width, height)[source]¶ Set this widgets size by setting minimum and maximum sizes simultaneously to the same value.
-
add_text
(text, relpos=(0.5, 0.5), anchor=(0.5, 0.5))[source]¶ Add text to the scalebar.
Parameters
text string; the text to be displayed. pos tuple; (x, y) position of the text relative to the scalebar. anchor tuple; (x, y) position of the text object’s anchor.
-
data_slicer.model module¶
-
exception
data_slicer.model.
ModelError
[source]¶ Bases:
Exception
Base class for
Model
related errors.
-
exception
data_slicer.model.
UndefinedModelError
[source]¶ Bases:
data_slicer.model.ModelError
Error raised when an operation would require the model attribute of :class: Model <data_slicer.model.Model> but it is not found.
-
exception
data_slicer.model.
UndefinedAxisError
[source]¶ Bases:
data_slicer.model.ModelError
Error raised when an operation would require all the axes in the axes attribute of :class: Model <data_slicer.model.Model> but at least one of them is not found.
-
class
data_slicer.model.
Model
(model=None)[source]¶ Bases:
object
General object that allows calculating a model over some input axes. It also provides functionalities to extract different slices from the calculated data.
-
MIN_AXIS_LENGTH
= 100¶
-
set_model
(model)[source]¶ Specify the function that represents the model. This should be a function with the call signature:
model(axis1, axis2, ..., axisN, kwarg1=kwarg1_default, ..., kwargN=kwargN_default, **kwargs)
I.e. all the positional arguments (axis1 to axisN) correspond to the required input variables. The keyword arguments (kwarg1 to kwargN) as well as further unspecified kwargs can be used for the model parameters.
Information about the number of arguments is obtained through introspection.
Parameters
model callable; a python function representing the model.
-
set_axes
(axes)[source]¶ Set all axes (inputs for the model). The axes supplied here can either be 1 dimensional array-like objects representing the actual values at which the model should be evaluated or simply the start and stop values for the range in which the model will be evaluated. If the length of any axis is smaller than Model.MIN_AXIS_LENGTH or if just start and stop values are given, linearly space values between start and stop will be given.
Parameters
axes list of len(self.n_args); an error will be thrown if the number of supplied axes does not match what is necessary for self.model. See also
set_axis
to set just one specific axis.
-
set_axis
(axis, dim=0)[source]¶ Set the axis (input to the model) at position dim. See documentation of
set_axes
for more details.Parameters
axis 1d array-like; the values at which the model should be evaluated along this dimension. If the length is smaller than Model.MIN_AXIS_LENGTH, linearly spaced values between the first and last value in axis will be created. See also
set_axes
to set all axes at once.
-
calculate_model_data
(axes=None, **kwargs)[source]¶ Evaluate the given model function
model
at every point in the hypervolume defined by the axes. This means that every possible combination of coordinates of all axes is created, and the model evaluated at every such point.Parameters
axes if specified, this is passed on to set_axes
. Otherwise the previously set axes will be used.kwargs all keyword arguments are passed to the model function.
-
make_slice
(dim, index, integrate=0, silent=False)[source]¶ Return a slice out of the model data. If the data has not yet been calculated, try to do it first. This wraps
make_slice
. Confer respective documentation for information on the arguments.
-
get_isocurve
(level, pen={'color': 'r', 'width': 2}, **kwargs)[source]¶ Warning
Only possible for 2D models (i.e. self.n_args==2).
Return an isocurve (
IsocurveItem
of the model data at the selected level.This uses pyqtgraph’s icocurve function, which is based on the marching squares algorithm.
Parameters
level float; value at which the isocurve is generated. pen arguments for the visual properties of the isocurve. Can be anything which is valid for mkPen
.Returns
isocurveItem IsocurveItem
-
data_slicer.plugin module¶
data_slicer.set_up_logging module¶
This file is intended to be imported by scripts that want to output logging info of all the components they use.
data_slicer.utilities module¶
-
class
data_slicer.utilities.
TracedVariable
(value=None, name=None)[source]¶ Bases:
PyQt5.QtCore.QObject
A pyqt implementaion of tkinter’s/Tcl’s traced variables using Qt’s signaling mechanism. Basically this is just a wrapper around any python object which ensures that pyQt signals are emitted whenever the object is accessed or changed.
In order to use pyqt’s signals, this has to be a subclass of
QObject
.Attributes
_value the python object represented by this TracedVariable instance. Should never be accessed directly but only through the getter and setter methods. sig_value_changed Signal
; the signal that is emitted wheneverself._value
is changed.sig_value_read Signal
; the signal that is emitted wheneverself._value
is read.sig_allowed_values_changed Signal
; the signal that is emitted wheneverself.allowed_values
are set or unset.allowed_values array
; a sorted list of all values that self._value can assume. If set, all tries to set the value will automatically set it to the closest allowed one.-
sig_value_changed
¶
-
sig_value_read
¶
-
sig_allowed_values_changed
¶
-
get_value
()[source]¶ Emit sig_value_changed and return the internal self._value.
Warning
the signal is emitted here before the caller actually receives the return value. This could lead to unexpected behaviour.
-
set_allowed_values
(values=None)[source]¶ Define a set/range/list of values that are allowed for this Variable. Once set, all future calls to set_value will automatically try to pick the most reasonable of the allowed values to assign.
Parameters
values iterable; The complete list of allowed (numerical) values. This is converted to a sorted np.array internally. If values is None, all restrictions on allowed values will be lifted and all values are allowed.
-
-
data_slicer.utilities.
indexof
(value, array)[source]¶ Return the first index of the value in the array closest to the given value.
Example:
>>> a = np.array([1, 0, 0, 2, 1]) >>> indexof(0, a) 1 >>> indexof(0.9, a) 0
-
data_slicer.utilities.
pop_kwarg
(name, kwargs, default=1)[source]¶ Check if a keyword name appears in the dictionary kwargs. If yes, remove it from the dictionary, returning its value. If no, return the value specified by default.
-
data_slicer.utilities.
make_slice_3d
(data, d, i, integrate=0, silent=False)[source]¶ Deprecated: Warning
Use
make_slice
instead. (though this ~might~ be slightly faster for 3d datasets)Create a slice out of the 3d data (l x m x n) along dimension d (0,1,2) at index i. Optionally integrate around i.
Parameters
data array-like; data of the shape (x, y, z) d int, d in (0, 1, 2); dimension along which to slice i int, 0 <= i < data.size[d]; The index at which to create the slice integrate int, 0 <= integrate < |i - n|
; the number of slices above and below slice i over which to integratesilent bool; toggle warning messages Returns
res np.array; Slice at index with dimensions shape[:d] + shape[d+1:]
where shape = (x, y, z).
-
data_slicer.utilities.
make_slice
(data, dim, index, integrate=0, silent=False)[source]¶ Take a slice out of an N dimensional dataset data at index along dimension dim. Optionally integrate by +- integrate channels around index. If data has shape:
(n0, n1, ..., n(dim-1), n(dim), n(dim+1), ..., n(N-1))
the result will be of dimension N-1 and have shape:
(n0, n1, ..., n(dim-1), n(dim+1), ..., n(N-1))
or in other words:
shape(result) = shape(data)[:dim] + shape(data)[dim+1:]
.
Parameters
data array-like; N dimensional dataset. dim int, 0 <= d < N; dimension along which to slice. index int, 0 <= index < data.size[d]; The index at which to create the slice. integrate int, 0 <= integrate < |index|
; the number of slices above and below slice index over which to integrate. A warning is issued if the integration range would exceed the data (can be turned off with silent).silent bool; toggle warning messages. Returns
res np.array; slice at index alond dim with dimensions shape[:d] + shape[d+1:].
-
data_slicer.utilities.
roll_array
(a, i)[source]¶ Cycle the arrangement of the dimensions in an N dimensional array. For example, change an X-Y-Z arrangement to Y-Z-X.
Parameters
a array of N dimensions, i.e. len(a.shape) = N. i int; number of dimensions to roll Returns
res array of N dimensions where the axes have been rearranged as follows:
before: `shape(a) = (d[0], d[1], ..., d[N])` after: `shape(res) = (d[(0+i)%N], d[(1+i)%N], ..., d[(N+i)%N])`
-
data_slicer.utilities.
get_lines
(data, n, dim=0, i0=0, i1=-1, offset=0.2, integrate='max', **kwargs)[source]¶ Extract n evenly spaced rows/columns from data along dimension dim between indices i0 and i1. The extracted lines are normalized and offset such that they can be nicely plotted close by each other - as is done, for example in
lineplot
.Parameters
data 2d np.array; the data from which to extract lines. n int; the number of lines to extract. dim int; either 0 or 1, specifying the dimension along which to extract lines. i0 int; starting index in data along dim. i1 int; ending index in data along dim. offset float; how much to vertically translate each successive line. integrate int or other; specifies how many channels around each line index should be integrated over. If anything but a small enough integer is given, defaults to the maximally available integration range. kwargs any other passed keyword arguments are discarded. Returns
lines list of 1d np.arrays; the extracted lines. indices list of int; the indices at which the lines were extracted.
-
data_slicer.utilities.
plot_cuts
(data, dim=0, integrate=0, zs=None, labels=None, max_ppf=16, max_nfigs=4, **kwargs)[source]¶ Plot all (or only the ones specified by zs) cuts along dimension dim on separate subplots onto matplotlib figures.
Parameters
data 3D np.array with shape (z,y,x); the data cube. dim int; one of (0,1,2). Dimension along which to take the cuts. integrate int or ‘full’; number of slices to integrate around each extracted cut. If ‘full’, take the maximum number possible, depending whether the number of cuts is reduced due to otherwise exceeding max_nfigs. ‘full’ does not work if zs are given. zs 1D np.array; selection of indices along dimension dim. Only the given indices will be plotted. labels 1D array/list of length z. Optional labels to assign to the different cuts max_ppf int; maximum number of plots per figure. max_nfigs int; maximum number of figures that are created. If more would be necessary to display all plots, a warning is issued and only every N’th plot is created, where N is chosen such that the whole ‘range’ of plots is represented on the figures. kwargs dict; keyword arguments passed on to pcolormesh
. Additionally, the kwarg gamma for power-law color mapping is accepted.
-
data_slicer.utilities.
get_contours
(data, x=None, y=None, levels=0)[source]¶ Use matplotlib`s contour function to get contour lines where the 2 dimensional dataset data intersects levels.
Parameters
data 2d-array; shape (nx, ny) x array-like; can be a linear array of shape (nx) or a meshgrid of shape (nx, ny) y array-like; can be a linear array of shape (ny) or a meshgrid of shape (nx, ny) levels float or list of float; the levels at which to extract the contour lines. Due to a matplotlib limitation, these numbers have to be in ascending order. Returns
contours list of 2d-arrays; each array of shape (2, N) contains the x and y coordinates of a contour line.
data_slicer.widgets module¶
This file contains classes that represent pyqtgraph widgets which can be used and combined in Qt applications.
-
class
data_slicer.widgets.
ColorSliders
(*args, **kwargs)[source]¶ Bases:
PyQt5.QtWidgets.QWidget
A simple widget providing a gamma and vmax slider.
Signals
gamma_changed emitted when the value of gamma changes vmax_changed emitted when the value of vmax changes -
sig_gamma_changed
¶
-
sig_vmax_changed
¶
-
-
class
data_slicer.widgets.
ThreeDWidget
(*args, data=None, **kwargs)[source]¶ Bases:
PyQt5.QtWidgets.QWidget
A widget that contains a
GLViewWidget
that allows displaying 2D colormeshes in a three dimensional scene. This class mostly functions as a base class for more refined variations.-
set_coordinate_axes
(on=True)[source]¶ Turn the visibility of the coordinate axes on or off.
Parameters
on bool or one of (‘on’, 1); if not True or any of the values stated, turn the axes off. Otherwise turn them on.
-
set_data
(data)[source]¶ Set this widget’s data in a
TracedVariable
instance to allow direct updates whenever the data changes.Parameters
data np.array of shape (x, y, z); the data cube to be displayed.
-
get_slice
(d, i, integrate=0, silent=True)[source]¶ Wrap
make_slice
to create slices out of this widget’s self.data. Confer respective documentation for details.
-
-
class
data_slicer.widgets.
ThreeDSliceWidget
(*args, **kwargs)[source]¶ Bases:
data_slicer.widgets.ThreeDWidget
A
ThreeDWidget
that can slice along x, y and z.
-
class
data_slicer.widgets.
FreeSliceWidget
(*args, data=None, **kwargs)[source]¶ Bases:
data_slicer.widgets.ThreeDWidget
A
ThreeDWidget
which represents its xy plane in an additional 2D panel. In this “selector” panel, there’s aCutline
with which arbitrary slices can be generated, which will in turn be shown in the 3D GLView.-
align
()[source]¶ Layout:
0 1 2 3 4 5 6 7 +---+---+---+---+---+---+---+---+ | | | 0 + | + | | | 1 + Selector | GLView + | | | 2 + | + | | | 3 + | +---+---+ + | | | xy | | 4 +---+---+---+---+---+---+---+---+
-
get_cutline_cut
()[source]¶ Wrapper for
get_array_region()
.
-