µSPY API Reference#

Module dataobject#

Basic data containers.

Class Loadable#

class Loadable#

Base class for loadable objects. Contains methods for serializing and deserializing.

dump(fname, thin=False, use_pickle=True)#

Dumps the object into a JSON/pickle file.

dumps(_thin=False, use_pickle=True)#

Dumps the object with pickle and returns it as a bytestring

classmethod load(fname)#

Returns an object retrieved from a JSON/pickle file.

save(fname)#

Save the DataObject to a file depending on the filename extension.

Class DataObject#

class DataObject(self, source: Any)#

Base class for data objects like images, lines, points, …

Parameters:

source (Any) – The source from which the object is created

copy()#

Return a deep copy.

property data#

Mutable data container dictionary.

get_field_string(field, fmt=None)#

Get a string that contains the value and its unit.

is_compatible(other)#

[summary]

Parameters:

other (DataObject) – [description]

Returns:

[description]

Return type:

bool

property meta#

Mutable metadata dictionary.

parse(source)#

Read in data. Should set the _source attribute.

property source#

The original object from which this instance was created (e.g., filename).

property unit#

Dictionary with unit strings for meta values.

Class DataObjectStack#

class DataObjectStack(source, virtual=False)#

Contains multiple DataObjects. E.g., for an image stack.

copy(virtual=None)#

Returns a deepcopy.

property elements#

Contents.

extend(other)#

Add new DataObjects to the end of the stack.

property sources#

Sources.

property virtual#

If a data stack is virtual, it does only load the data on demand.

Class Image#

class Image(self, source: Any)#

Base class for all spatial 2D data.

filter(method='gaussian', **kwargs)#

Apply 2D Filter to image

Applies a 2D Filter to the image, specified by the method argument. Valid methods are “gaussian”, “blur”, “median” and “kernel”. Depending on the selected method different kwargs can be passed.

Parameters:
  • method (str, optional) – Applied filter type. Either “gaussian”, “blur”, “median” or “kernel”, by default “gaussian”.

  • kwargs (Depending on the passed method) –

  • Methods (possible kwargs are specified below) –

  • gaussian (-) –

    • sizeint or tuple, by default (3, 3)

      size of the applied kernel

    • sigma: int, by default -1

      width of the applied gaussian. When negative, sigma is calculated from kernel

  • blur (-) –

    • size: int or tuple, by default (3,3)

      size of applied kernel

  • media (-) –

    • size: int, by default 3

      size of kernel

  • kernel (-) –

    • kernel: np.ndarray, by default None

      kernel to be applied to the image

Returns:

Returns image with applied filter.

Return type:

Image

Raises:

ValueError – If specified method is not valid.

is_compatible(other)#

[summary]

Parameters:

other (DataObject) – [description]

Returns:

[description]

Return type:

bool

property mask#

Set a mask onto the image. TODO

parse(source)#

Read in data. Should set the _source attribute.

save(fname, **kwargs)#

Save the DataObject to a file depending on the filename extension.

Class ImageStack#

class ImageStack(source, virtual=False)#

DataObjectStack for Images which provides a default parsing mechanism for common image formats like png or tiff.

average(avg)#

Averages over consecutive images in a stack.

Parameters:

avg (int) – Number of consecutive image that will be averaged. The total number of images must be dividable by avg.

Returns:

Stack with averaged images. The metadata of the first element in every averaged slice of images is preserved.

Return type:

ImageStack

Raises:

ValueError – If number of images in stack is not dividable by avg

Examples

>>> stack = ImageStack("testdata/test_stack_IV_RuO2_normed_aligned_80-140.tif")[0:60]
>>> len(stack)
60
>>> avg_stack = stack.average(4)
>>> len(avg_stack)
15
save(fname)#

Save the DataObject to a file depending on the filename extension.

Class Line#

class Line(self, source: Any)#

Base class for all 1D data.

Parameters:

source (Union[str, np.ndarray]) – When a str: path to .csv file with x y data as columns. Delimiter is guessed from the file When np.ndarray: 2d numpy array containing the x and y values either als rows or cols

x, y

Numpy arrays containing the x and y data of the line

Type:

np.ndarray

ydim, xdmin

Dimension of the x and y values, e.g. time, energy …

Type:

str

Examples

Initialization from .csv file

example.csv:
U in V,  I in A
0.0,     0.0
1.0,     2.0
>>> line = Line("example.csv")
>>> line.x, line.y
array([0.0, 1.0]), array([0.0, 2.0])

When reading from a .csv file the column header is interpreted as xdim and ydim. If the header has the form A in B, A is the dimension and B is the corresponding unit.

>>> line.xdim, line.ydim
U, I

The x and y values are also accessible over their corresponding dimension:

>>> line.U
array([0.0, 1.0])

Initialization from numpy array

>>> line = Line(np.array([[0.0, 1.0], [0.0, 2.0]]))
>>> line.x
array([0.0, 1.0])
>>> line.xdim, line.ydim
x, y
property area#

Area under the line integrated by simpson rule

property dataframe#

Pandas Dataframe of the lines x,y data

derivative()#

Returns the derivative of a cubic spline evaluated at the x values of the line

integral()#

Returns the integrated values of a cubic spline evaluated at the x values of the line

interpolate(x_data=None, order='cubic', **kwargs)#

Interpolates the x,y data of the Line with a spline of order ‘order’

Parameters:
  • x_data (Number, list of numbers or 1d numpy array or None) – x_values at which the interpolation will be evaluated

  • order (str or int) – When a string must be either “linear”, “quad” or “cubic”. When an int must be 1 <= order <= 5

  • kwargs – Additional keyword arguments are passed through to scipy.interpolate.InterpolatedUnivariateSpline

Returns:

  • if x_data was not None – numpy array containing interpolated Numbers

  • if x_data was None – the interpolation function itself

is_compatible(other)#

[summary]

Parameters:

other (DataObject) – [description]

Returns:

[description]

Return type:

bool

property length#

Length of the x and y data.

parse(source)#

Read in data. Should set the _source attribute.

save(fname)#

Saves the line as .csv

Parameters:

fname (str) – Filename of the file to save. If it ends with .csv a csv file of the dataframe representation of the line is saved Otherwise the parent(dataobject) save method is called.

Return type:

None

smooth(kernel)#

Recieves a kernel and convolves the values of the line

Parameters:

kernel (np.ndarray, int) – Kernel that will be convolved with the line data. If int an equaly distributed kernel of size kernel will be applied.

Returns:

smoothed line

Return type:

Line

Examples

Rolling average over three data points of line. Note that sum(kernel) should be 1.

>>> kernel = np.array([1,1,1])/3
>>> smoothed = line.smooth(kernel)

Above code is equivalent to:

>>> smoothed = line.smooth(3)

The weights do not have to be the same. To put more weigh on the current point than on adjecent points:

>>> kernel = np.array([1,2,1])/4
>>> smoothed = line.smooth(kernel)

Class IntensityLine#

class IntensityLine(stack, roi_, xaxis)#

A Class to extract Intensities from an ImageStack

Unlike Line from which it inherits it takes an ImagseStack, a ROI and a String representing the dimension along which the itensities in the stack should be extracted, e.g. time, energy … For each image the the mean value of intensites inside the ROI is extracted as y-values together with the dimensional value of the image (time, energy, …) as the lines x-axes.

Parameters:
  • stack (ImageStack) – ImageStack from which the intensities will be extracted

  • roi (roi.ROI) – ROI from within the intensities will be extracted in each image,

  • xaxis (str) – a string indicates the axis of the dimension along the intensites shall be extracted, e.g. time, energy …

parse(source)#

Applies a ROI to an Imagestack and extracts mean of ROI from each image

Parameters:

source (tuple[ImageStack, roi.ROI, str]) –

Must be a Tuple of

  1. an ImageStack from which the intensities will be extracted,

  2. a ROI from within the intensities will be extracted in each image,

  3. a string indicates the axis of the dimension along the intensites shall be extracted, e.g. time, energy …

Returns:

a dict containing the x,y-values of the line, the stack, the ROI, the x- and y-dimensions and the unit of the x axis extracted from the images. The y-dimension is “intensity” by default with unit “a.u.”

Return type:

dict

Class StitchedLine#

class StitchedLine(stacks, rois, xaxis)#

Class for combining IntensityLines from multiple ImageStacks.

Works like IntensityLine, but accepts multiple ImageStacks and the same amount of ROIs. Every stack is mapped to a ROI (in the order that they are given, e.g. first stack to first ROI) and the intensity profile is extracted. If the x-values of the extracted Lines are overlapping, the Lines are scaled to matched each other. The stacks may be sorted by their first xaxis value before extraction.

x, y

x and y values of stitched lines

Type:

np.ndarray

lines#

list of single IntensityLines that are used for stitching

Type:

list[IntensityLine]

xdim, ydim

string representing the dimension of the x and y values, default for y is “intensity”

Type:

str

Parameters:
  • stacks (Sequence[ImageStack] or ImageStack) – ImageStacks, which will be used for Line extraction

  • rois (Sequence[roi.ROI] or roi.ROI) – ROIs used for Line extraction. Must be of the same length as stacks. If stacks is a single stack, ROI has to be a single ROI

  • xaxis – a string indicates the axis of the dimension along the intensites shall be extracted, e.g. time, energy …

Raises:

ValueError – When len(stacks) != len(rois)

parse(source)#

Extract IntensityLines from Stacks and handle their stitching.

Parameters:

source (Sequence[Sequence, Sequence, str]) –

List or tuple containing

  1. A list or tuple of ImageStacks

  2. A list or tuple of ROIs with the same length as the tuple of ImageStacks

  3. A str representing the xaxis along which the intensity is extracted

Returns:

dict containing all metadata and data, including rois and stacks

Return type:

dict[str, Any]

Raises:

ValueError – When len(stacks) != len(rois)

Module leem.base#

Basic classes for Elmitec LEEM “.dat”-file parsing and data visualization.

Class LEEMImg#

class LEEMImg(self, source: Any)#

LEEM image that exposes metadata as attributes. Default attributes are: - image: numpy array containing the image - energy (in eV), temperature (in °C), fov (in µm), timestamp (in s)

find_warp_matrix(template, algorithm='ecc', **kwargs)#

Calculates a warp matrix between the image and a template.

The algorithm applied is specified by the algorithm argument, which is ecc by default. currently only ecc is implemented

Parameters:
  • template (Image) – Template image against which is aligned

  • algorithm (str, optional) – algorithm used for registration, by default “ecc”

  • **kwargs – Additional keyword arguments are passed through to the registration function. Can specifiy further options like convergence criteria or transformations

Returns:

3x3 matrix containing the alignment parameters

Return type:

np.ndarray

Raises:

ValueError – Raised when not implemented alogrithm is called.

See also

do_ecc_align

get_field_string(field, fmt=None)#

Get a string that contains the value and its unit. Some LEEM-specific fields have different default formats than the pure DataObject method.

normalize(mcp=None, dark_counts=0, inplace=False)#

Normalization of LEEM Images

Parameters:
  • mcp (Image, optional) – [description], by default None

  • dark_counts (Union[int, float, Image], optional) – [description], by default 100

  • inplace (bool, optional) – [description], by default False

Returns:

[description]

Return type:

LEEMImg

parse(source)#

Read in data. Should set the _source attribute.

Class LEEMStack#

class LEEMStack(*args, time_origin=None, **kwargs)#
align(inplace=False, mask=True, template=None, sanity=True, **kwargs)#

Image registration of the stack

The images of the stack are registered subsequently by calling Image.find_warp_matrix() for each image and finally warping them using Image.warp(). After inital registration the results are checked for sanity by checking if some translation shifts are more than 3 standard deviations away from the mean shift. If so, the values are interpolated from a spline, over the whole stack. The same is true if the initial alignment fails.

Parameters:
  • inplace (bool, default False) – If ‘True’ the stack itself will be registered If ‘False’ a copy of the stack will be registered

  • mask (bool, np.ndarray or None, default True) –

    Mask that will be used during registration

    • If ‘True’ a circular mask with a radius=0.9*Image.width is used as mask

    • If ‘False’ or ‘None’ no mask is used during registration

    • If np.ndarray the array must be of dtype=np.uint8 and contain the mask that should be applied

  • **kwargs – Additional keyword arguments are passed through to Image.find_warp_matrix

Returns:

LEEMStack with aligned images. The stack itself is returned when ‘inplace’ = True

Return type:

LEEMStack

See also

find_warp_matrix, LEEMImg.warp

normalize(mcp=None, inplace=False, **kwargs)#

Normalization of images in stack

The images in the stack are normalized by appling Image.normalize(mcp) to each image

Parameters:
  • mcp (Image, str or None) – Image or filename of image if str. If ‘None’ the mcp attribute of the images will be used

  • inplace (bool, default False) – If ‘True’ the stack itself will be normalized If ‘False’ a copy of the stack will be normalized

  • **kwargs – Additional keyword arguments are passed through to Image.normalize

Note

Consider passing ‘dark_counts’ as a keyword argument, to specify non-default dark counts of the images

Returns:

LEEMStack with registered images. The stack itself is returned when ‘inplace’=True

Return type:

LEEMStack

Class IVCurve#

class IVCurve(*args, **kwargs)#

Convenience Class for generating LEEM IV-Curves.

It is called and behaves exactly like StitchedLine but is called with xaxis = “energy” by default.