Deep dive in the distance profiles

In this notebook, we will talk more about the theory behind distance profile, how they are computed, and how they can be optimized. This notebook focuses on the exact, subsequence-based methods; for the theory behind the approximate whole-series index, see the Deep dive into SimHash and the LSH index notebook. For practical experiments on the speedups implemented in aeon, refer to the notebook on the Analysis of the speedups provided by similarity search module notebook.

What are distance profiles ?

In the context of similarity search, where we have as input a time series \(X = \{x_1, \ldots, x_m\}\) and a query \(Q = \{q_1, \ldots, q_l\}\), a distance profile is defined as a vector containing the similarity of \(Q\) to every subsequence of size \(l\) in \(X\), with the \(i^{th}\) subsequence denoted by \(W_i = \{x_i, \ldots, x_{i+(l-1)}\}\).

Given a distance or dissimilarity function \(dist\), such as the Euclidean distance, the distance profile \(P(X,Q)\) is expressed as :

\[P(X, Q) = \{dist(W_1, Q), \ldots, dist(W_{m-(l-1)}, Q)\}\]

We can then find the “best match” between \(Q\) and \(X\) by looking at the distance profile minimum value and extract the subsequence \(W_{\text{argmin} P(X,Q)}\) as the best match.

Trivial matches

One should be careful of what is called “trivial matches” in this situation. If \(Q\) is extracted from \(X\), it is extremely likely that it will match with itself, as \(dist(Q,Q)=0\). To avoid this, it is common to set the parts of the distance profile that are neighbors to \(Q\) to \(\infty\). This is the role of the X_index parameter in the similarity search predict methods. The exclusion_factor parameter is used to define the neighbors of \(Q\) that will also get \(\infty\) value.

For example, if \(Q\) was extracted at index \(i\) in \(X\) (i.e. \(Q = \{x_i, \ldots, x_{i+(l-1)}\}\)), then all points in the interval [i - floor(l*exclusion_factor), i + floor(l*exclusion_factor)] will the set to \(\infty\) in the distance profile to avoid a trivial match.

The same reasoning can also be applied for the best matches of \(Q\). It is highly likely that the two best matches will be neighbours, as \(W_i\) and \(W_{i+/-1}\) share \(l-1\) values. The allow_trivial_matches boolean parameter in predict (default False) controls this, with inverted semantics: when it is False, an exclusion zone of int(l * exclusion_factor) points on each side of every returned match is applied within the same series, so the returned matches do not overlap; when it is True, this exclusion is skipped and predict simply returns the globally smallest distances, which may overlap and therefore include such trivial neighbouring matches.

Optimizing the distance profile computation

The main idea behind optimizing the distance profile computation, in the case where we want to obtain the exact results (i.e. make no approximation), is to avoid recomputations as much as possible. For example, when computing the mean and standard deviation of each subsequence \(W_1, \ldots, W_{m-l+1}\), instead of computing these statistics independently for each subsequence \(W_i\), we can exploit the fact that these subsequences are extracted from the same time series.

Consider the case of the mean of \(W_i\) expressed as \(\displaystyle{\mu_i = \frac{1}{l}\sum_{j=0}^{l-1} x_{i+j}}\). Instead of completely recomputing the mean of \(W_{i+1}\), we can keep a rolling sum \(S\) and update it as we go from \(\mu_1\) to \(\mu_{m-l+1}\).

Let \(\displaystyle{S_1 = \sum_{j=0}^{l-1} x_{1+j}}\), we compute the mean of \(W_1\) as \(\displaystyle{\mu_1 = \frac{1}{l} S_1}\). Then we can compute \(S_2\) as \(S_2 = S_1 - x_1 + x_{2+l-1}\) and compute \(\displaystyle{\mu_2 = \frac{1}{l} S_2}\). It can be generalized as \(S_i = S_{i-1} - x_{i-1} + x_{i+l-1}\).

We can apply the same reasoning for computing the standard deviation by keeping a rolling squared sum. For a code example, you can check the sliding_mean_std_one_series function of aeon.

Optimization for the (squared) euclidean distance

In this section, we consider the case of the squared euclidean distance (i.e. no square root), but the following also holds for the euclidean distance by using \(\displaystyle{\sqrt{d(W_i, Q)}}\).

Applying the same reasoning as the computation of the mean, we can minimize recomputation in the case of the euclidean distance profile. If we consider the euclidean distance between a subsequence \(W_i = \{x_i, \ldots, x_{i+(l-1)}\}\) extracted from a time series \(X = \{x_1, \ldots, x_m\}\), and a query \(Q = \{q_1, \ldots, q_l\}\), we have :

\(\displaystyle{d(W_i, Q) = \sum_{j=1}^{l} (q_j - x_{i+j-1})^2}\)

\(\displaystyle{d(W_i, Q) = \sum_{j=1}^{l} q_j^2 + \sum_{j=1}^{l} x_{i+j-1}^2 - 2 \times \sum_{j=1}^{l} q_j \times x_{i+j-1}}\)

Seeing the euclidean distance as the second equation allows us to :

  • Compute the sum \(\sum_{j=1}^{l} q_j^2\) only once for all \(W_i\)

  • Keep a rolling sum to update \(\sum_{j=1}^{l} x_{i+j-1}^2\) as we go from \(W_1\) to \(W_{m-l+1}\)

  • Use a cross-correlation operation efficiently to compute \(\sum_{j=1}^{l} q_j \times x_{i+j-1}\) as \(X*Q\). For large inputs, we can also compute this in the frequency domain with a convolution (see scipy convolve function), in which case we need to flip the query Q before computing the convolution.

What about the normalised (squared) euclidean distance ?

The trick we use for the non normalised euclidean distance cannot apply to the normalised distance, as we cannot keep the rolling sum between subsequences with different means and standard deviations. However, we can compute the normalised euclidean distance as the pearson correlation coefficient, as show in the paper Matrix Profile I: All Pairs Similarity Joins for Time Series.

Consider the mean \(\mu_i\) and standard deviation \(\sigma_i\) of a subsequence \(W_i\) (computed with rolling sums) and the mean \(\mu_q\) and standard deviation \(\sigma_q\) of the query. Given \(QW_i\) the dot product obtained from a cross correlation or a convolution operation between \(X\) and \(Q\), we can compute the normalised squared euclidean distance as :

\(\displaystyle{d(W_i, Q) = 2l \left(1 - \frac{QW_i - l.\mu_q.\mu_i}{l.\sigma_q.\sigma_i}\right)}\)

The term inside the parenthesis is the Pearson correlation coefficient \(p \in [-1, 1]\) between the query and the subsequence. The \(1 -\) term is essential: a perfect match has \(p = 1\), giving a distance of \(0\), while full anti-correlation has \(p = -1\), giving the maximal distance of \(4l\). This matches aeon’s implementation, which computes the per-position value as abs(2 * query_length * (1.0 - p)) in aeon/similarity_search/subsequence/_mass.py.

Search options in predict

Beyond computing the distance profile, the predict method of a subsequence searcher exposes several options that control which matches are returned. Below we illustrate them on a small synthetic example using the MASS estimator. The estimator is fitted on a single noisy sine series, and we query with a subsequence of length=20. Recall that predict returns a tuple (indexes, distances), where indexes is an array of (i_case, i_timepoint) pairs and distances the associated distances.

[1]:
import numpy as np

from aeon.similarity_search.subsequence import MASS

# Build a single, light synthetic series: a noisy sine of ~200 points.
rng = np.random.default_rng(0)
n_timepoints = 200
t = np.linspace(0, 6 * np.pi, n_timepoints)
series = np.sin(t) + 0.1 * rng.standard_normal(n_timepoints)

# fit expects a 3D collection (n_cases, n_channels, n_timepoints).
X_fit = series.reshape(1, 1, n_timepoints)

length = 20
searcher = MASS(length=length, normalize=True)
searcher.fit(X_fit)

# Use a subsequence extracted from the series itself as the query, so that
# X_index self-queries below are meaningful. It is located at (case 0, tp 40).
i_case_query, i_tp_query = 0, 40
query = X_fit[i_case_query, :, i_tp_query : i_tp_query + length]
query.shape
[1]:
(1, 20)

Default: k=1 nearest match

With the default parameters, predict returns the single nearest subsequence. Because the query was extracted from the series itself, the nearest match is the query’s own location (distance close to 0).

[2]:
# Default call: k=1 returns the single best (nearest) match.
indexes, distances = searcher.predict(query)
print("indexes  :", indexes)
print("distances:", distances)
indexes  : [[ 0 40]]
distances: [0.]

allow_trivial_matches: overlapping neighbours

By default (allow_trivial_matches=False), an exclusion zone of int(length * exclusion_factor) points is applied around each returned match, so the returned matches never overlap. Setting allow_trivial_matches=True skips this exclusion and returns the globally smallest distances, which can surface a match that directly overlaps a better one (e.g. a subsequence shifted by one position).

[4]:
# Default: exclusion zone applied, so the returned matches do not overlap.
idx_excl, dist_excl = searcher.predict(query, k=4, allow_trivial_matches=False)
print("allow_trivial_matches=False (non-overlapping):")
print("  indexes  :", idx_excl.tolist())
print("  distances:", np.round(dist_excl, 3))

# Allowing trivial matches returns the globally smallest distances. Here the 4th
# match is a neighbour overlapping the 3rd one (its timepoint differs by 1),
# a trivial overlapping match that the exclusion zone had removed above.
idx_triv, dist_triv = searcher.predict(query, k=4, allow_trivial_matches=True)
print("allow_trivial_matches=True (overlapping neighbour surfaces):")
print("  indexes  :", idx_triv.tolist())
print("  distances:", np.round(dist_triv, 3))
allow_trivial_matches=False (non-overlapping):
  indexes  : [[0, 40], [0, 103], [0, 170], [0, 29]]
  distances: [ 0.    11.402 12.348 22.231]
allow_trivial_matches=True (overlapping neighbour surfaces):
  indexes  : [[0, 40], [0, 103], [0, 170], [0, 171]]
  distances: [ 0.    11.402 12.348 13.592]

inverse_distance: farthest match

With inverse_distance=True, candidates are ranked by inverse distance, so the farthest (most dissimilar) subsequences are returned instead of the nearest. This is useful to find the least similar pattern to the query.

[5]:
# inverse_distance=True ranks by inverse distance: the farthest subsequence.
indexes, distances = searcher.predict(query, inverse_distance=True)
print("farthest match index:", indexes.tolist())
print("(inverse) distance   :", np.round(distances, 3))
farthest match index: [[0, 7]]
(inverse) distance   : [0.014]

X_index: excluding the query’s own location

When the query is itself a subsequence of the fitted collection, its own location is a trivial self-match at distance ~0. Passing X_index=(i_case, i_timepoint) masks that location and its exclusion zone from the distance profile, so predict returns a genuine neighbour instead of the query itself.

[6]:
# Without X_index: the nearest match is the query's own location, distance ~0.
idx_self, dist_self = searcher.predict(query)
print("without X_index -> self-match:")
print("  index   :", idx_self.tolist(), "(query is at", [i_case_query, i_tp_query], ")")
print("  distance:", np.round(dist_self, 3))

# With X_index: the query's location (and its exclusion zone) is masked, so a
# real neighbour elsewhere in the series is returned instead.
idx_nn, dist_nn = searcher.predict(query, X_index=(i_case_query, i_tp_query))
print("with X_index -> genuine neighbour:")
print("  index   :", idx_nn.tolist())
print("  distance:", np.round(dist_nn, 3))
without X_index -> self-match:
  index   : [[0, 40]] (query is at [0, 40] )
  distance: [0.]
with X_index -> genuine neighbour:
  index   : [[0, 103]]
  distance: [11.402]

Generated using nbsphinx. The Jupyter notebook can be found here.

binder