API reference

The core functionality of trackpy is grouped into three separate steps:

  1. Locating features in an image

  2. Refining feature coordinates to obtain subpixel precision

  3. Identifying features through time, linking them into trajectories.

Convenience functions for feature finding, refinement, and linking are readily available:

trackpy.locate(raw_image, diameter[, ...])

Locate Gaussian-like blobs of some approximate size in an image.

trackpy.batch(frames, diameter[, output, ...])

Locate Gaussian-like blobs of some approximate size in a set of images.

trackpy.link(f, search_range[, pos_columns, ...])

Link a DataFrame of coordinates into trajectories.

For more control on your tracking “pipeline”, the following core functions are provided:

Feature finding

trackpy.grey_dilation(image, separation[, ...])

Find local maxima whose brightness is above a given percentile.

trackpy.find_link(reader, search_range, ...)

Find and link features, using image data to re-find lost features.

Coordinate refinement

trackpy.refine_com(raw_image, image, radius, ...)

Find the center of mass of a bright feature starting from an estimate.

trackpy.refine_leastsq(f, reader, diameter)

Refines overlapping feature coordinates by least-squares fitting to radial model functions.

Linking

trackpy.link(f, search_range[, pos_columns, ...])

Link a DataFrame of coordinates into trajectories.

trackpy.link_iter(coords_iter, search_range)

Link an iterable of per-frame coordinates into trajectories.

trackpy.link_df_iter(f_iter, search_range[, ...])

Link an iterable of DataFrames into trajectories.

trackpy.link_partial(f, search_range, link_range)

Patch the trajectories in a DataFrame by linking only a range of frames

trackpy.reconnect_traj_patch(f, link_range, ...)

Reconnect the trajectory inside a range of frames to the trajectories outside the range.

link() and link_df_iter() run the same underlying code. link() operates on a single DataFrame containing data for an entire movie. link_df_iter() streams through larger data sets, in the form of one DataFrame for each video frame. link_iter() streams through a series of numpy ndarrays. link_partial() can patch a region of trajectories in an already linked dataset.

See the tutorial on large data sets for more.

Static Analysis

trackpy.static.proximity(features[, pos_columns])

Find the distance to each feature's nearest neighbor.

trackpy.static.pair_correlation_2d(feat, cutoff)

Calculate the pair correlation function in 2 dimensions.

trackpy.static.pair_correlation_3d(feat, cutoff)

Calculate the pair correlation function in 3 dimensions.

trackpy.static.cluster(f, separation[, ...])

Cluster features from one or several frames.

Motion Analysis

trackpy.motion.msd(traj, mpp, fps[, ...])

Compute the mean displacement and mean squared displacement of one trajectory over a range of time intervals.

trackpy.motion.imsd(traj, mpp, fps[, ...])

Compute the mean squared displacement of each particle.

trackpy.motion.emsd(traj, mpp, fps[, ...])

Compute the ensemble mean squared displacements of many particles.

trackpy.motion.compute_drift(traj[, ...])

Return the ensemble drift, xy(t).

trackpy.motion.subtract_drift(traj[, drift, ...])

Return a copy of particle trajectories with the overall drift subtracted out.

trackpy.motion.vanhove(pos, lagtime[, mpp, ...])

Compute the van Hove correlation (histogram of displacements).

trackpy.motion.relate_frames(t, frame1, frame2)

Find the displacement vector of all particles between two frames.

trackpy.motion.velocity_corr(t, frame1, frame2)

Compute the velocity correlation between every pair of particles' displacements.

trackpy.motion.direction_corr(t, frame1, frame2)

Compute the cosine between every pair of particles' displacements.

trackpy.motion.is_typical(msds, frame[, ...])

Identify which paritcles' MSDs are in the central quantile.

trackpy.motion.diagonal_size(single_trajectory)

Measure the diagonal size of a trajectory.

trackpy.motion.theta_entropy(pos[, bins, plot])

Plot the distribution of directions and return its Shannon entropy.

trackpy.motion.min_rolling_theta_entropy(pos)

Compute the minimum Shannon entropy in any window.

trackpy.filtering.filter_stubs(tracks[, ...])

Filter out trajectories with few points.

trackpy.filtering.filter_clusters(tracks[, ...])

Filter out trajectories with a mean particle size above a given quantile.

Prediction Framework

Trackpy extends the Crocker–Grier algoritm using a prediction framework, described in the prediction tutorial.

trackpy.predict.NullPredict()

Predict that particles will not move.

trackpy.predict.ChannelPredict(bin_size[, ...])

Predict a particle's position based on its spanwise coordinate in a channel.

trackpy.predict.DriftPredict([...])

Predict a particle's position based on the mean velocity of all particles.

trackpy.predict.NearestVelocityPredict([...])

Predict a particle's position based on the most recent nearby velocity.

trackpy.predict.predictor(predict_func)

Decorator to vectorize a predictor function for a single particle.

trackpy.predict.instrumented([limit])

Decorate a predictor class and allow it to record inputs and outputs.

Plotting Tools

Trackpy includes functions for plotting the data in ways that are commonly useful. If you don’t find what you need here, you can plot the data any way you like using matplotlib, seaborn, or any other plotting library.

trackpy.annotate(centroids, image[, ...])

Mark identified features with white circles.

trackpy.scatter(centroids[, mpp, cmap, ax, ...])

Scatter plot of all particles.

trackpy.plot_traj(traj[, colorby, mpp, ...])

Plot traces of trajectories for each particle.

trackpy.annotate3d(centroids, image, **kwargs)

Annotates a 3D image and returns a scrollable stack for display in IPython.

trackpy.scatter3d(*args, **kwargs)

The 3D equivalent of scatter.

trackpy.plot_traj3d(*args, **kwargs)

The 3D equivalent of plot_traj.

trackpy.plot_displacements(t, frame1, frame2)

Plot arrows showing particles displacements between two frames.

trackpy.subpx_bias(f[, pos_columns])

Histogram the fractional part of the x and y position.

trackpy.plot_density_profile(f, binsize[, ...])

Plot a histogram showing the density profile in one direction.

These two are almost too simple to justify their existence – just a convenient shorthand for a common plotting task.

trackpy.mass_ecc(f[, ax])

Plot each particle's mass versus eccentricity.

trackpy.mass_size(f[, ax])

Plot each particle's mass versus size.

Image Conversion

By default, locate() applies a bandpass and a percentile-based threshold to the image(s) before finding features. You can turn off this functionality using preprocess=False, percentile=0.) In many cases, the default bandpass, which guesses good length scales from the diameter parameter, “just works.” But if you want to executre these steps manually, you can.

trackpy.find.percentile_threshold(image, ...)

Find grayscale threshold based on distribution in image.

trackpy.preprocessing.bandpass(image, ...[, ...])

Remove noise and background variation.

trackpy.preprocessing.lowpass(image[, ...])

Remove noise by convolving with a Gaussian.

trackpy.preprocessing.scale_to_gamut(image, ...)

trackpy.preprocessing.invert_image(raw_image)

This function has been made lazy.

trackpy.preprocessing.convert_to_int(image)

Convert the image to integer and normalize if applicable.

Framewise Data Storage & Retrieval Interface

Trackpy implements a generic interface that could be used to store and retrieve particle tracking data in any file format. We hope that it can make it easier for researchers who use different file formats to exchange data. Any in-house format could be accessed using the same simple interface in trackpy.

At present, the interface is implemented only for HDF5 files. There are several different implementations, each with different performance optimizations. PandasHDFStoreBig is a good general-purpose choice.

trackpy.PandasHDFStore(filename[, mode, ...])

An interface to an HDF5 file with framewise access, using pandas.

trackpy.PandasHDFStoreBig(filename[, mode, ...])

Like PandasHDFStore, but keeps a cache of frame numbers.

trackpy.PandasHDFStoreSingleNode(filename[, ...])

An interface to an HDF5 file with framewise access, using pandas, that is faster for cross-frame queries.

trackpy.FramewiseData()

Abstract base class defining a data container with framewise access.

That last class cannot be used directly; it is meant to be subclassed to support other formats. See Writing Your Own Interface in the streaming tutorial for more.

Logging

Trackpy issues log messages. This functionality is mainly used to report the progress of lengthy jobs, but it may be used in the future to report details of feature-finding and linking for debugging purposes.

When trackpy is imported, it automatically calls handle_logging(), which sets the logging level and attaches a logging handler that plays nicely with IPython notebooks. You can override this by calling ignore_logging() and configuring the logger however you like.

trackpy.quiet([suppress])

Suppress trackpy information log messages.

trackpy.handle_logging()

Send INFO-level log messages to stdout.

trackpy.ignore_logging()

Reset to factory default logging configuration; remove trackpy's handler.

Utility functions

trackpy.minmass_v03_change(raw_image, ...[, ...])

Convert minmass value from v0.2.4 to v0.3.

trackpy.minmass_v04_change(raw_image, ...[, ...])

Convert minmass value from v0.3 to v0.4.

trackpy.utils.fit_powerlaw(data[, plot])

Fit a powerlaw by doing a linear regression in log space.

Diagnostic functions

trackpy.diag.performance_report()

Display summary of which optional speedups are installed/enabled

trackpy.diag.dependencies()

Give the version of each of the dependencies -- useful for bug reports.

Low-Level API (Advanced)

Switching Between Numba and Pure Python

Trackpy implements the most intensive (read: slowest) parts of the core feature-finding and linking algorithm in pure Python (with numpy) and also in numba, which accelerates Python code. Numba can offer a major performance boost, but it is still relatively new, and it can be challenging to use. If numba is available, trackpy will use the numba implementation by default; otherwise, it will use pure Python. The following functions allow sophisticated users to manually switch between numba and pure-Python modes. This may be used, for example, to measure the performance of these two implementations on your data.

trackpy.enable_numba()

Use numba-accelerated variants of core functions.

trackpy.disable_numba()

Do not use numba-accelerated functions, even if numba is available.

Low-Level Linking API

All of the linking functions in trackpy provide the same level of control over the linking algorithm itself. For almost all users, the functions above will be sufficient. But link_df() and link_df_iter() above do assume that the data is stored in a pandas DataFrame. For users who want to use some other iterable data structure, the functions below provide direct access to the linking code.

trackpy.link_iter(coords_iter, search_range)

Link an iterable of per-frame coordinates into trajectories.

trackpy.link(f, search_range[, pos_columns, ...])

Link a DataFrame of coordinates into trajectories.

And the following classes can be subclassed to implement a customized linking procedure.

trackpy.SubnetOversizeException

An Exception to be raised when the sub-nets are too big to be efficiently linked.

Masks

These functions may also be useful for rolling your own algorithms:

trackpy.masks.binary_mask(radius, ndim)

Elliptical mask in a rectangular array

trackpy.masks.r_squared_mask(radius, ndim)

Mask with values r^2 inside radius and 0 outside

trackpy.masks.x_squared_masks(radius, ndim)

Returns ndim masks with values x^2 inside radius and 0 outside

trackpy.masks.cosmask(radius)

Sin of theta_mask

trackpy.masks.sinmask(radius)

Sin of theta_mask

trackpy.masks.theta_mask(radius)

Mask of values giving angular position relative to center.

trackpy.masks.gaussian_kernel(sigma[, truncate])

1D discretized gaussian

trackpy.masks.mask_image(pos, image, radius)

Masks an image so that pixels farther than radius to all given feature positions become 0.

trackpy.masks.slice_image(pos, image, radius)

Slice a box around a group of features from an image.

Full API reference

A full overview of all modules and functions can be found below:

trackpy