Kymo

lumicks.pylake.kymo.Kymo

class Kymo(name, file, start, stop, metadata, position_offset=0, calibration=None)

A Kymograph exported from Bluelake

Parameters:
  • name (str) – Kymograph name

  • file (lumicks.pylake.File) – Parent file. Contains the channel data.

  • start (int) – Start point in the relevant info wave.

  • stop (int) – End point in the relevant info wave.

  • metadata (ScanMetaData) – Metadata for this Kymo.

  • position_offset (float) – Coordinate position offset with respect to the original raw data.

  • calibration (PositionCalibration) – Class defining calibration from microns to desired position units.

__getitem__(item)

All indexing is in timestamp units (ns)

calibrate_to_kbp(length_kbp)

Calibrate from microns to other units.

Parameters:

length (float) – length of the kymo in kilobase pairs

crop_and_calibrate(channel='rgb', tether_length_kbp=None, **kwargs)

Open a widget to interactively edit the image stack.

Actions:

left-click and drag – Define the cropped ROI.

Parameters:
  • channel ('rgb', 'red', 'green', 'blue', None; optional) – Channel to plot for RGB images (None defaults to ‘rgb’) Not used for grayscale images

  • tether_length_kbp (float) – Length of the tether in the cropped region in kilobase pairs. If provided, the kymo returned from the image property will be automatically calibrated to this tether length.

  • **kwargs – Forwarded to Kymo.plot().

Examples

from lumicks import pylake
import matplotlib.pyplot as plt

# Loading a kymograph.
h5_file = pylake.File("example.h5")
_, kymo = h5_file.kymos.popitem()
widget = kymo.crop_and_calibrate("green", 48.502)
plt.show()

# Select cropping ROI by left-click drag

# Grab the updated image stack
new_kymo = widget.kymo
crop_beads(bead_diameter, algorithm, *, channel='green', extra_cropping=0, **kwargs)

Estimates the edges of stationary beads and returns a copy of the kymograph cropped to these limits.

Warning

This is early access alpha functionality. While usable, this has not yet been tested in a large number of different scenarios. The API can still be subject to change without any prior deprecation notice! If you use this functionality keep a close eye on the changelog for any changes that may affect your analysis.

Parameters:
  • bead_diameter (float) – Rough estimate for the bead size (microns).

  • algorithm ('brightness', 'template') – Which algorithm to use. See Kymo.estimate_bead_edges() for more information.

  • channel ('red', 'green', 'blue', optional) – Channel to use for bead detection.

  • extra_cropping (float, optional) – How much to move the returned edge inwards from the detected bead edge in microns.

  • **kwargs – Forwarded to Kymo.estimate_bead_edges().

crop_by_distance(lower, upper)

Crop the kymo by position.

Crops the kymograph down to lower <= x < upper.

Parameters:
  • lower (float) – Lower bound in physical units.

  • upper (float) – Upper bound in physical units.

downsampled_by(time_factor=1, position_factor=1, reduce=<function sum>)

Return a copy of this Kymograph which is downsampled by time_factor in time and position_factor in space.

Parameters:
  • time_factor (int) – The number of pixels that will be averaged in time (default: 1).

  • position_factor (int) – The number of pixels that will be averaged in space (default: 1).

  • reduce (callable) – The numpy function which is going to reduce multiple pixels into one. The default is np.sum.

estimate_bead_edges(bead_diameter, algorithm, *, channel='green', extra_cropping=0, plot=False, threshold_percentile=70, allow_movement=False, downsample_num_frames=5)

Determine approximate positional coordinates of the bead edges. Only intended for stationary beads.

Warning

This is early access alpha functionality. While usable, this has not yet been tested in a large number of different scenarios. The API can still be subject to change without any prior deprecation notice! If you use this functionality keep a close eye on the changelog for any changes that may affect your analysis.

There are two algorithms to determine bead edges:

  • “brightness”: brightness based bead edge detection

  • “template”: template correlation-based bead edge detection

  • Brightness: brightness based bead edge detection. Searches for bead edges by summing along the temporal direction and removing small features. The result is smoothed and peaks are detected. Bead edges are found by checking where the fluorescence drops below a threshold.

  • Template: template correlation-based bead edge detection. Downsamples the kymograph to a specific number of frames (specified with the optional parameter downsample_num_frames). For each frame, we traverse the scan line pixel by pixel, extracting a template at each pixel. This template is then correlated with the next frame. This process is repeated until all frames have been processed and a 2D matrix is acquired. This matrix is then summed over the temporal axis obtaining a similarity score over time. This score can be interpreted as a measure for how long a template taken at that particular location is present. The outer maxima of this curve provide the bead centers.

Parameters:
  • bead_diameter (float) – Rough estimate for the bead size (microns).

  • algorithm ('brightness', 'template') – Which algorithm to use.

  • channel ('red', 'green', 'blue', optional) – Channel to use for bead detection.

  • extra_cropping (float, optional) – How much to move the returned edge inwards from the detected bead edge in microns.

  • plot (optional[bool]) – Plot result

  • threshold_percentile (optional[int]) – Percentile to drop down to before accepting that we have left the bead area. Higher values will make the bounds go closer to the bead edge but risk the algorithm failing or having high background (default: 70).

  • allow_movement (optional[bool]) – Allow movement of the template between frames. Only relevant for algorithm="template". When this is enabled, the maximum correlation along the spatial axis is selected between frames. This allows the template to move which can lead to better detection for cases where the beads may be moving slightly (default: False).

  • downsample_num_frames (optional[int]) – Number of time frames to downsample to (must be larger than 3). Only relevant for algorithm="template". Default: 5.

Returns:

bead_edges – List of the two edge positions in microns.

Return type:

list[float]

Raises:

RuntimeError – When the algorithm fails to locate two edges during the bead finding stage.

export_tiff(filename, *, dtype=<class 'numpy.float32'>, clip=False)

Save the RGB photon counts to a TIFF image

Parameters:
  • filename (str | os.PathLike) – The name of the TIFF file where the image will be saved.

  • dtype (np.dtype) – The data type of a single color channel in the resulting image.

  • clip (bool) – If enabled, the photon count data will be clipped to fit into the desired dtype. This option is disabled by default: an error will be raise if the data does not fit.

flip()

Flip the kymograph along the positional axis

classmethod from_dataset(h5py_dset, file)

Construct a confocal class from dataset.

Parameters:
  • h5py_dset (h5py.Dataset) – The original HDF5 dataset containing confocal scan information

  • file (lumicks.pylake.File) – The parent file. Used to loop up channel data

get_image(channel='rgb') ndarray

Get image data for the full stack as an ndarray.

Parameters:

channel ({'red', 'green', 'blue', 'rgb'}) – The color channel of the requested data.

line_timestamp_ranges(*, include_dead_time=False)

Get start and stop timestamp of each line in the kymo.

Note: The stop timestamp for each line is defined as the first sample past the end of the relevant data such that the timestamps can be used for slicing directly.

Parameters:

include_dead_time (bool) – Include dead time at the end of each frame (default: False).

plot(channel='rgb', *, adjustment=<lumicks.pylake.adjustments.ColorAdjustment object>, axes=None, image_handle=None, show_title=True, show_axes=True, scale_bar=None, **kwargs)

Plot a kymo for the requested color channel(s).

Parameters:
  • channel ({"red", "green", "blue", "rgb"}, optional) – Color channel to plot.

  • adjustment (lk.ColorAdjustment) – Color adjustments to apply to the output image.

  • axes (matplotlib.axes.Axes, optional) – If supplied, the axes instance in which to plot.

  • image_handle (matplotlib.image.AxesImage or None) – Optional image handle which is used to update plots with new data rather than reconstruct them (better for performance).

  • show_title (bool, optional) – Controls display of auto-generated plot title

  • show_axes (bool, optional) – Setting show_axes to False hides the axes.

  • scale_bar (lk.ScaleBar, optional) – Scale bar to add to the figure.

  • **kwargs – Forwarded to matplotlib.pyplot.imshow(). These arguments are ignored if image_handle is provided.

Returns:

The image handle representing the plotted image.

Return type:

matplotlib.image.AxesImage

plot_with_force(force_channel, color_channel, aspect_ratio=0.25, reduce=<function mean>, kymo_args=None, adjustment=<lumicks.pylake.adjustments.ColorAdjustment object>, **kwargs)

Plot kymo with force channel downsampled over scan lines

Note that high frequency channel data must be available for this function to work.

Parameters:
  • force_channel (str) – name of force channel to downsample and plot (e.g. ‘1x’)

  • color_channel (str) – color channel of kymo to plot (‘red’, ‘green’, ‘blue’, ‘rgb’)

  • aspect_ratio (float) – aspect ratio of the axes (i.e. ratio of y-unit to x-unit)

  • reduce (callable) – The numpy function which is going to reduce multiple samples into one. Forwarded to Slice.downsampled_over()

  • kymo_args (Optional[dict]) – Forwarded to matplotlib.pyplot.imshow()

  • adjustment (lk.ColorAdjustment) – Color adjustments to apply to the output image.

  • **kwargs – Forwarded to Slice.plot().

plot_with_position_histogram(color_channel, pixels_per_bin=1, hist_ratio=0.25, adjustment=<lumicks.pylake.adjustments.ColorAdjustment object>, **kwargs)

Plot kymo with histogram along position axis

Parameters:
  • color_channel (str) – color channel of kymo to plot (‘red’, ‘green’, ‘blue’, ‘rgb’).

  • pixels_per_bin (int) – number of pixels along position axis to bin together.

  • hist_ratio (float) – width of the histogram with respect to the kymo image.

  • adjustment (lk.ColorAdjustment) – Color adjustments to apply to the output image.

  • **kwargs – Forwarded to histogram bar plot.

plot_with_time_histogram(color_channel, pixels_per_bin=1, hist_ratio=0.25, adjustment=<lumicks.pylake.adjustments.ColorAdjustment object>, **kwargs)

Plot kymo with histogram along time axis

Parameters:
  • color_channel (str) – color channel of kymo to plot (‘red’, ‘green’, ‘blue’, ‘rgb’).

  • pixels_per_bin (int) – number of pixels along time axis to bin together.

  • hist_ratio (float) – height of the histogram with respect to the kymo image.

  • adjustment (lk.ColorAdjustment) – Color adjustments to apply to the output image.

  • **kwargs – Forwarded to histogram bar plot.

property center_point_um

Returns a dictionary of the x/y/z center coordinates of the scan (w.r.t. brightfield field of view)

property contiguous

Are the pixels integrated over a contiguous period of time

If this flag is false then pixels have been integrated over disjoint sections of time. This can be the case when a kymograph has been downsampled over time.

property duration

Duration of the kymograph in seconds. This value is equivalent to the number of scan lines times the line time in seconds. It does not take into account incomplete scan lines or mirror fly-in/out time.

property fast_axis

The axis that was scanned (“X” or “Y”)

property line_time_seconds

Line time in seconds

Raises:

RuntimeError – If line time is not defined because the kymograph only has a single line.

property motion_blur_constant: float

Motion blur as defined by the shutter function.

The normalized shutter function is defined as \(c(t)\), where \(c(t)\) represents whether the shutter is open or closed. \(c(t)\) is normalized w.r.t. area. For no motion blur, \(c(t) = \delta(t_\mathrm{exposure})\), whereas for a constantly open shutter it is defined as \(c(t) = 1 / \Delta t\).

The motion blur constant is defined as:

\[R = \frac{1}{\Delta t} \int_{0}^{\Delta t}S(t) \left(1 - S(t)\right)dt\]

with

\[S(t) = \int_{0}^{t} c(t') dt'\]

When there is no motion blur, we obtain: R = 0, whereas a continuously open shutter over the exposure time results in R = 1/6. Note that when estimating both localization uncertainty and the diffusion constant, the motion blur factor has no effect on the estimate of the diffusion constant itself, but it does affect the calculated uncertainties. In the case of a provided localization uncertainty, it does impact the estimate of the diffusion constant.

Raises:

NotImplementedError – if the motion blur is not defined for this kymograph.

property pixel_time_seconds

Pixel dwell time in seconds

property pixels_per_line

Number of pixels in each line

property pixelsize

Returns a List of axes dimensions in calibrated units. The length of the list corresponds to the number of scan axes.

property pixelsize_um

Returns a List of axes dimensions in um. The length of the list corresponds to the number of scan axes.

property shape

Shape of the reconstructed Kymo image

property size_um

Returns a List of scan sizes in um along axes. The length of the list corresponds to the number of scan axes.

property timestamps: ndarray

Timestamps for each image pixel.

The returned array has the same shape as the color_image arrays. Timestamps are defined at the mean of the timestamps.