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_config_dir()[source]

Return the path to the configuration directory on this system.

get_data()[source]

Convenience getter method. Allows writing self.get_data() instead of self.data.get_value().

set_data(data=None, axes=None)[source]

Convenience setter method. Allows writing self.set_data(d) instead of self.data.set_value(d). Additionally allows setting new axes. If axes is None, 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.
load(filename)[source]

Alias to open.

open(filename)[source]

Open a file that’s readable by dataloading.

get_main_data()[source]

Return the 2d array that is currently displayed in the main plot.

get_cut_data()[source]

Return the 2d array that is currently displayed in the cut plot.

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_data_change()[source]

Update self.main_window.image_data and replot.

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.

calculate_integrated_intensity()[source]
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 the ImagePlot’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

get_lines

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

plot_cuts()

overlay_model(model)[source]

Display a model over the data. model should be function of two variables, namely the currently displayed x- and y-axes.

Parameters

model callable or Model;

See also

Model

remove_model()[source]

Remove the current model’s visible and invisible parts.

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.
print_to_console(message)[source]

Print a message to the embedded ipython console.

load_startup_data()[source]
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.

update_x_plot()[source]
update_y_plot()[source]
update_xy_plots()[source]

Update the x and y profile plots.

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.

rotate(alpha=0)[source]

Rotate the main image by the given angle alpha (in degrees).

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.
redraw_plots(image=None)[source]

Redraw plotted data to reflect changes in data or its colors.

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.

on_gamma_slider_move()[source]

When the user moves the gamma slider, update gamma.

on_vmax_slider_move()[source]

When the user moves the vmax slider, update vmax.

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.

set_vmax(vmax=1)[source]

Set the relative maximum of the colormap. I.e. the colors are mapped to the range min(data) - vmax*max(data).

cmap_changed()[source]

Recalculate the lookup table and redraw the plots such that the changes are immediately reflected.

data_slicer.pit.start_main_window()[source]

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`.

set_alpha(*args, **kwargs)[source]
set_gamma(*args, **kwargs)[source]
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.

set_alpha(alpha)[source]

Set the value of alpha for the whole colormap to alpha where alpha can be a float or an array of length len(self.color).

set_vmax(vmax=1)[source]

Set the relative (to the maximum of the data) maximum of the colorscale.

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

  1. 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.cmaps.load_user_cmaps(cmaps)[source]

Append user supplied colormaps to the dictionary cmaps.

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.

set_hover_pen(*args, **kwargs)[source]

Set the pen used for drawing this widget when it is in the hovered state. Accepts function arguments to :func: mkPen pyqtgraph.mkPen

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.

set_hover_pen(*args, **kwargs)[source]

Set the pen used for drawing this widget when it is in the hovered state. Accepts function arguments to :func:` pyqtgraph.mkPen`

hoverEvent(ev)[source]

This just copies the code of the parent class with the difference of a variable hover pen.

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 a pyqtgraph.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 this Cutline’s roi.
sig_initialized
add_to_plot(plot_widget)[source]

Add this cutline to a PlotWidget. This is effectively implemented by setting this Cutline’s plot attribute to the given plot_widget.

initialize(orientation=None)[source]

Emits .

set_handle_style(radius=8, color=(200, 255, 200), width=2)[source]

Set the size and pen of the handles.

recenter()[source]

Put the ROI in the center of the current plot.

calculate_endpoints()[source]

Get sensible initial values for the endpoints of the LineSegmentROI from the pyqtrgaph.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.

flip_orientation()[source]

Change the cutline’s orientation from vertical to horitontal or vice-versa and re-initialize it in the new orientation.

get_array_region(*args, **kwargs)[source]

Wrapper for the underlying ROI’s getArrayRegion().

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'
print_m(*messages)[source]

Print message to console, adding the dataloader name.

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'
load_data(filename)[source]

Load data that has been saved using python’s pickle module. The data is assumed to be either just a naked array, a dictionary containing the keys data and axes or an argparse.Namespace instance, containing these same keys.

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.dataloading.load_pickle(filename)[source]

Shorthand for loading python objects stored in pickle files.

Parameters

filename str; name of file to load.

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
align()[source]

Create and apply the dialog’s layout.

plot_preview()[source]

Update the plot in the preview window with the currently selected options.

class data_slicer.imageplot.Crosshair(pos=(0, 0))[source]

Bases: object

Crosshair made up of two InfiniteLines.

add_to(widget)[source]

Add this crosshair to a Qt widget.

remove_from(widget)[source]

Remove this crosshair from a pyqtgraph widget.

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.

set_movable(movable=True)[source]

Set whether or not this crosshair can be dragged by the mouse.

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.

update_position_v()[source]

Confer update_position_h.

on_dragged_h()[source]

Callback for dragging of InfiniteLines. Their visual position should be reflected in the TracedVariables self.hpos and self.vpos.

on_dragged_v()[source]

Callback for dragging of InfiniteLines. Their visual position should be reflected in the TracedVariables self.hpos and self.vpos.

set_bounds(xmin, xmax, ymin, ymax)[source]

Set the area in which the infinitelines can be dragged.

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.

toggle_cursor()[source]

Change the visibility of the crosshair cursor.

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.

Emits

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]).

transpose()[source]

Transpose the image, i.e. swap the x- and y-axes.

set_xlabel(label)[source]

Shorthand for setting this plot’s x axis label.

set_ylabel(label)[source]

Shorthand for setting this plot’s y axis label.

get_limits()[source]

Return [[x_min, x_max], [y_min, y_max]].

fix_viewrange()[source]

Prevent zooming out by fixing the limits of the ViewBox.

release_viewrange()[source]

Undo the effects of fix_viewrange

rotate(alpha=0)[source]

Rotate the image_item by the given angle alpha (in degrees).

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.

update_allowed_values()[source]

Update the allowed values silently. This assumes that the displayed image is in pixel coordinates and sets the allowed values to the available pixels.

set_bounds(xmin, xmax, ymin, ymax)[source]

Set both, the displayed area of the axis as well as the the range in which the crosshair can be dragged to the intervals [xmin, xmax] and [ymin, ymax].

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.
orientate()[source]

Define all aspects that are dependent on the orientation.

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).

increase_pos(step=1)[source]

Increase (or decrease) self.pos by a reasonable amount. I.e. move step steps along the list of allowed values.

keyPressEvent(event)[source]

Define responses to keyboard interactions.

wheelEvent(event)[source]

Override of the Qt wheelEvent method. Fired on mousewheel scrolling inside the widget.

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.

keyPressEvent(event)[source]

Override some behaviour of the superclass.

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.
set_relative_position(textItem, relpos)[source]

Figure out this Scalebar’s current size (in data units) and reposition its textItems accordingly.

on_allowed_values_changed()[source]

Keep TextItems in correct relative position.

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.

get_axes_dims()[source]

Return the length of all axes that are defined.

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
get_values_around(value, eps)[source]

Warning

unfinished

data_slicer.plugin module

class data_slicer.plugin.Plugin(main_window, data_handler)[source]

Bases: object

Base class for plugins. Other plugins should inherit this.

name = 'no plugin name assigned'
shortname = None
help()[source]

Print a list of available functions and a help message to standard output.

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 whenever self._value is changed.
sig_value_read Signal; the signal that is emitted whenever self._value is read.
sig_allowed_values_changed Signal; the signal that is emitted whenever self.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
set_value(value=None)[source]

Emit sig_value_changed and set the internal self._value.

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.

on_change(callback)[source]

Convenience wrapper for Signal’s ‘connect’.

on_read(callback)[source]

Convenience wrapper for Signal’s ‘connect’.

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.

Emits

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.
find_closest_allowed(value)[source]

Return the value of the element in self.allowed_values (if set) that is closest to value.

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 integrate
silent 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
align()[source]
on_gamma_slider_move()[source]

When the user moves the gamma slider, update gamma.

on_vmax_slider_move()[source]

When the user moves the vmax slider, update vmax.

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.

align()[source]

Put all sub-widgets and elements into the layout.

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.

get_xy_slice(i, integrate=0)[source]

Shorthand to get an xy slice, i.e. d=2.

make_texture(cut)[source]

Wrapper for makeRGBA.

initialize_xy()[source]

Create the xy plane.

update_xy()[source]

Update both texture and position of the xy plane.

set_cmap(cmap)[source]

Change the used colormap to a ds_cmap instance.

class data_slicer.widgets.ThreeDSliceWidget(*args, **kwargs)[source]

Bases: data_slicer.widgets.ThreeDWidget

A ThreeDWidget that can slice along x, y and z.

align()[source]

Put all sub-widgets and elements into the layout as follows:

   0     1     2  
+-----+-----+-----+
|                 | 0
+                 +  
|                 | 1
+     GLView      +
|                 | 2
+                 +  
|                 | 3
+-----+-----+-----+
| xy  | yz  | zx  | 4
+-----+-----+-----+

5 units in height
3 units in width
initialize_yz()[source]

Create the yz plane.

get_yz_slice(i, integrate=0)[source]

Shorthand to get an yz slice, i.e. d=0.

initialize_zx()[source]

Create the zx plane.

get_zx_slice(i, integrate=0)[source]

Shorthand to get an yz slice, i.e. d=1.

update_yz()[source]

Update both texture and position of the yz plane.

update_zx()[source]

Update both texture and position of the zx plane.

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 a Cutline 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().

update_cut()[source]

Update the texture and position of the cutline cut in the GLGraphicsView.

update_selector()[source]

When the slider position changes, update the image displayed in the selector to represent the correct cut.