Objects that move together: trajectory clustering#

When many objects (units, sensors, countries, customers) are observed in the same phase space over time, two questions arise: which objects move along similar paths, and which ones stay neighbours over time. The neighbourhood-preservation similarity – the share of time steps at which two objects are among each other’s nearest neighbours – answers the second, and DBSCAN on it yields groups of co-moving objects.

import matplotlib.pyplot as plt
import numpy as np

from mvtsa import clustering as cl

rng = np.random.default_rng(0)
T, groups = 60, [(0, 12), (12, 24), (24, 36)]
P = np.zeros((36, T, 2))
for g, (a, b) in enumerate(groups):
    centre = np.cumsum(rng.normal(0, 0.3, (T, 2)), axis=0) + 4 * np.array(
        [np.cos(2 * g), np.sin(2 * g)]
    )
    P[a:b] = centre + 0.4 * rng.normal(size=(b - a, T, 2))
truth = np.repeat([0, 1, 2], 12)

Neighbourhood preservation#

tc = cl.TrajectoryClustering(method="neighborhood", k=6, window=20).fit(P)
print("labels:", tc.labels_)
print(
    "labels per 20-step window:",
    [lab.tolist()[:6] for lab in tc.labels_window_],
)
fig, ax = plt.subplots(figsize=(5, 4))
for i in range(36):
    ax.plot(
        P[i, :, 0],
        P[i, :, 1],
        color=f"C{max(tc.labels_[i], 0)}",
        lw=0.6,
        alpha=0.7,
    )
ax.set_title("trajectories coloured by cluster")
plt.show()
trajectories coloured by cluster
labels: [0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2]
labels per 20-step window: [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]

Total running time of the script: (0 minutes 0.066 seconds)

Gallery generated by Sphinx-Gallery