playnano.analysis.modules.x_means_clustering module

Analysis module that groups detected features with X-means.

X-means finds the number of clusters itself: it repeatedly runs k-means and splits clusters while splitting improves the Bayesian information criterion (BIC). Based on:

Pelleg, D. and Moore, A. W. (2000). X-means: Extending K-means with Efficient Estimation of the Number of Clusters. Proceedings of the 17th International Conference on Machine Learning, 727-734.

class playnano.analysis.modules.x_means_clustering.XMeansClusteringModule[source]

Bases: AnalysisModule

Group detected features from all frames with X-means, which picks the number.

Pipeline name: "x_means_clustering". It needs the output of feature_detection from an earlier step.

Each detected feature becomes one point. By default its coordinates are the feature’s centroid, (row, col) in pixels, with the frame time in seconds added as a third coordinate. With normalise (the default), each coordinate is rescaled to the range 0 to 1 before clustering.

Starting with min_k clusters, each round runs k-means, then tries to split each cluster of 2 or more points in two. A cluster is split if the two halves, each of at least 2 points, have a higher combined BIC than the cluster by more than bic_threshold. The next round runs k-means again, from scratch, with the new number of clusters. This stops when no cluster splits or splitting would give more than max_k clusters. The random seed of each k-means run is fixed, so results are repeatable.

Examples

Two particles over 4 frames, one moving to the right:

>>> import numpy as np
>>> from playnano.afm_stack import AFMImageStack
>>> from playnano.analysis.modules.feature_detection import (
...     FeatureDetectionModule,
... )
>>> data = np.zeros((4, 64, 64))
>>> for t in range(4):
...     data[t, 10:16, 10 + t : 16 + t] = 3.0
...     data[t, 40:46, 40:46] = 3.0
>>> stack = AFMImageStack(
...     data,
...     pixel_size_nm=2.0,
...     channel="height_trace",
...     file_path="demo.h5-jpk",
...     frame_metadata=[{"timestamp": 0.5 * t} for t in range(4)],
... )
>>> detected = FeatureDetectionModule().run(
...     stack, mask_fn="mask_threshold", threshold=1.0
... )
>>> previous = {"feature_detection": detected}
>>> from playnano.analysis.modules.x_means_clustering import (
...     XMeansClusteringModule,
... )
>>> result = XMeansClusteringModule().run(stack, previous, use_time=False)
>>> result["cluster_centers"].round(2)
array([[12.5, 15. ],
       [42.5, 42.5],
       [12.5, 13. ]])

The still particle is one cluster; the moving one is split in two, because its positions spread more widely than one cluster explains well.

property name: str

Name of this module in a pipeline, "x_means_clustering".

requires = ['feature_detection', 'log_blob_detection']
run(stack: AFMImageStack, previous_results: dict[str, Any] | None = None, *, detection_module: str = 'feature_detection', coord_key: str = 'features_per_frame', coord_columns: Sequence[str] = ('centroid_x', 'centroid_y'), use_time: bool = True, min_k: int = 1, max_k: int = 10, normalise: bool = True, time_weight: float | None = None, replicates: int = 3, max_iter: int = 300, bic_threshold: float = 0.0) → dict[str, Any][source]

Cluster the detected features with X-means.

Parameters:
  • stack (AFMImageStack) – The stack; used for the frame times.

  • previous_results (dict) – Outputs of earlier steps. Must hold a detection output.

  • detection_module (str, optional) – Name of the detection step to use. If it has not run, log_blob_detection is tried, then feature_detection. Default is "feature_detection".

  • coord_key (str, optional) – Key of the per-frame feature lists in the detection output. Default is "features_per_frame".

  • coord_columns (list or tuple of str, optional) – Keys of each feature’s coordinates. If a feature lacks them, the first two values of its centroid, (row, col), are used instead. feature_detection has no centroid_x or centroid_y, so this is what happens with the default. Default is ("centroid_x", "centroid_y").

  • use_time (bool, optional) – Add each feature’s frame time, in seconds, as a third coordinate (only when there are two coordinates). Default is True.

  • min_k (int, optional) – Number of clusters to start with. Must not be more than max_k. Default is 1.

  • max_k (int, optional) – Largest number of clusters allowed. Default is 10.

  • normalise (bool, optional) – Rescale each coordinate to the range 0 to 1 (minimum to maximum over all points) before clustering. Default is True.

  • time_weight (float, optional) – Multiply the rescaled time coordinate by this, so time counts more (above 1) or less (below 1) than position. Must be positive. Only used with normalise and a time coordinate. Default is None (no weighting).

  • replicates (int, optional) – Number of times each k-means run is started; the best is kept. Default is 3.

  • max_iter (int, optional) – Largest number of iterations of each k-means run. Default is 300.

  • bic_threshold (float, optional) – How much a split must raise the BIC to be accepted. Higher values give fewer clusters. Default is 0.0.

Returns:

"clusters"

One dict per cluster, with id (int), and for each member point frames (frame index), point_indices (index in that frame’s feature list) and coords (the point’s coordinates as clustered, so rescaled if normalise).

"cluster_centers"

Array of shape (n_clusters, n_coordinates): the centre of each cluster, in the original units (pixels, and seconds for time).

"summary"

n_clusters and members_per_cluster (cluster ID to number of points).

Return type:

dict

Raises:
  • RuntimeError – If previous_results holds no detection output.

  • KeyError – If the detection output lacks coord_key, or a feature has neither coord_columns nor centroid.

  • ValueError – If min_k is more than the number of points.

Notes

If min_k is more than max_k, no clustering is done: the result has min_k centres picked at random from the points.

version = '0.1.0'
playnano.analysis.modules.x_means_clustering.compute_bic(points: ndarray, center: ndarray) → float[source]

Return the Bayesian information criterion (BIC) of one cluster; higher is better.

The cluster is modelled as a spherical Gaussian around center.

Parameters:
  • points (numpy.ndarray) – The cluster’s points, shape (n_points, n_coordinates).

  • center (numpy.ndarray) – The cluster’s centre, shape (1, n_coordinates).

Returns:

The BIC, or -inf for fewer than 2 points.

Return type:

float

playnano.analysis.modules.x_means_clustering.core_xmeans(data: ndarray, init_k: int, max_k: int, min_cluster_size: int, distance: str, replicates: int, max_iter: int, bic_threshold: float) → tuple[ndarray, ndarray][source]

Run X-means on an array of points.

Parameters:
  • data (numpy.ndarray) – Points, shape (n_points, n_coordinates).

  • init_k (int) – Number of clusters to start with.

  • max_k (int) – Largest number of clusters allowed.

  • min_cluster_size (int) – Smallest number of points in each half of a split.

  • distance (str) – Not used; distances are always squared Euclidean.

  • replicates (int) – Number of starts of each k-means run.

  • max_iter (int) – Largest number of iterations of each k-means run.

  • bic_threshold (float) – How much a split must raise the BIC to be accepted.

Returns:

  • labels (numpy.ndarray) – Index of each point’s cluster: the nearest centre.

  • centers (numpy.ndarray) – Cluster centres, shape (n_clusters, n_coordinates).

playnano.analysis.modules.x_means_clustering.initialize_centers(points: ndarray, k: int) → ndarray[source]

Pick k starting centres from the points, spread out like k-means++.

Uses NumPy’s global random generator, which is not seeded.

Parameters:
  • points (numpy.ndarray) – Points, shape (n_points, n_coordinates).

  • k (int) – Number of centres.

Returns:

The centres, shape (k, n_coordinates).

Return type:

numpy.ndarray