EP52

EP52: Optimal Transport & Melody

Wasserstein Distance, Kantorovich Duality, and the Earth Mover's Metric on Pitch
2:37 Metric GeometryOptimizationMusicology

Overview / 概述

Two melodies stand before you. How far apart are they? Not the number of notes that differ, not a key-signature gap — but the minimum cost of transporting one distribution of pitches into the other. That cost is the Wasserstein distance, also called the Earth Mover’s Distance (EMD).

Optimal transport (OT) reframes melody comparison as a logistics problem: notes are piles of earth at different pitch locations, and we want to move every grain of source-earth onto the matching target location with the smallest total effort. The decisive insight is that this minimisation problem has a dual formulation — the Kantorovich duality — that connects geometry to functional analysis and turns melody distance into a computable quantity.

This episode introduces the transport-plan matrix, the Kantorovich primal–dual theorem, the Sinkhorn algorithm for fast approximation, and three musical applications: style similarity, plagiarism detection, and tonal distance along the circle of fifths.

中文: “两段旋律有多’远'?不是音符数量的差,不是调性的差,而是把一段旋律’搬运’成另一段的最小代价。这叫瓦瑟斯坦距离。”


Prerequisites / 前置知识


Definitions

Definition 52.1 (Melody as a Probability Measure)

Let denote the set of pitch classes (mod 12), or more generally let be a finite set of MIDI note numbers.

A melody of length with notes and non-negative amplitude weights with defines a discrete probability measure:

where is the Dirac mass at pitch . The weight encodes the relative importance (duration, velocity, or uniform ) of note .

Worked example. A three-note motif C–E–G with equal weights: (using MIDI pitch classes C=0, E=4, G=7).

Definition 52.2 (Ground Cost and Cost Matrix)

A ground cost is a function measuring the cost of transporting one unit of “earth” from pitch to pitch .

For melody comparison the standard choice is the pitch distance:

(in semitones). Given source notes and target notes , the cost matrix is:

Example. Moving pitch C (0) to G (7) costs 7; moving C to D (2) costs 2.

Definition 52.3 (Transport Plan)

Given source measure and target measure , a transport plan is a matrix satisfying the marginal constraints:

The entry specifies how much mass is moved from source note to target note .

The set of all transport plans is denoted and is a convex polytope.

Musical reading. Row sums equal source note weights; column sums equal target note weights. Each row describes how one source note is “spread” across target notes; each column describes which sources contribute to one target note.

Definition 52.4 (Wasserstein-1 Distance (Earth Mover's Distance))

The Wasserstein-1 distance (or distance, Earth Mover’s Distance) between measures and over a metric space is:

where is the Frobenius inner product (total transport cost).

Intuition. Each unit of mass must be moved; the cost is distance times mass. The minimisation finds the most efficient re-assignment, avoiding unnecessary long-range transport.

Definition 52.5 (Kantorovich Dual Potentials)

The Kantorovich dual problem to seeks a pair of functions with and (called dual potentials) subject to the constraint:

The dual objective is:

The functions and can be interpreted as “prices” at each source and target location in a resource-allocation economy. At optimality, and are -conjugates of each other.


Main Theorems / 主要定理

Theorem 52.1 (Wasserstein Is a Metric)

Let be a metric space. Then defines a metric on the space of probability measures :

  1. Non-negativity: , with equality if and only if .
  2. Symmetry: .
  3. Triangle inequality: for any third measure .
Proof.

Non-negativity and symmetry follow directly from the definition: and any plan for can be transposed to give a plan for with the same cost.

For the triangle inequality, given optimal plans and , one constructs a gluing via the disintegration theorem: define . Then: by the triangle inequality on : . Since is a valid coupling for , the infimum gives the result.

Theorem 52.2 (Kantorovich Duality)

For discrete measures and with finite support and ground cost , the primal and dual values are equal:

Moreover, for the ground cost , the dual admits the Lipschitz reformulation:

where the supremum is over all 1-Lipschitz functions .

Proof.

The primal problem is a linear programme in (minimise a linear objective over a convex polytope). Strong LP duality applies whenever the primal is feasible and bounded — both hold since is non-empty (e.g., the independent coupling ) and costs are non-negative. Strong duality yields over dual-feasible .

The Lipschitz reformulation follows from complementary slackness: at optimality , so the optimal (setting for the symmetric case) must be 1-Lipschitz. The supremum over 1-Lipschitz equals the dual optimum.

中文: “康托洛维奇对偶是最优传输理论的核心定理:最小化搬运代价,等于最大化一对函数的积分差。对偶性把几何距离和函数分析联系起来,是最优传输成为强大工具的数学原因。”

Theorem 52.3 (Transposition Is Near, Inversion Is Far)

Let be a melody with uniform weights. Define:

  • Transposition by semitones: .
  • Inversion about axis : .

Then:

Proof.

Transposition. The identity coupling (ship note to ) is feasible and has cost . No coupling can do better, because every unit of mass must move at least (a lower bound from the dual: the 1-Lipschitz function satisfies ).

Inversion. The identity coupling ships to at cost . Summing with weight gives the stated formula. Optimality of this coupling follows from the Monge solution for 1D transport (Theorem 52.4 below).

中文: “转位:把旋律整体移高五度,代价很小——每个音符搬运相同距离。听起来也’近'。倒影:把每个音符关于轴翻转,搬运代价大——音符散布开来。听起来’远’了。这和直觉完全吻合。”

Theorem 52.4 (Monge Solution in One Dimension)

When and , the optimal transport plan between discrete measures is achieved by the sorted matching: sort source pitches and target pitches (with repetition according to weights), then match them in order.

For equal-weight melodies of the same length : where is the rank-permutation sorting .

Proof.
For the cost on , any crossing in a transport plan is suboptimal: if and with and , then uncrossing — sending and — costs the same or less, by the identity when , . Removing all crossings yields the sorted matching, which is optimal.
Prop 52.1 (LP Complexity and Sinkhorn Approximation)
The exact transport plan solves a linear programme with variables and equality constraints. The interior-point complexity is (roughly for square problems). The Sinkhorn algorithm (Cuturi 2013) adds an entropic regularisation term to the objective (where ), yielding an approximate plan in iterations, each of cost .
Proof.
The regularised problem has a unique solution (strict convexity of entropy) given by a doubly stochastic scaling of the kernel matrix : for scaling vectors . The Sinkhorn iteration alternately normalises rows and columns of , converging geometrically. As , .

Numerical Examples

Example 1: Transposition by a fifth.

Source: C–E–G–B–D (uniform weights each), pitches . Target: G–B–D–F♯–A (shifted up 7 semitones), pitches .

By Theorem 52.3:

The sorted matching ships each note exactly 7 semitones. Total cost .

Example 2: Inversion about axis C (pitch 0).

Source: same pentatonic (C–D–E–G–A), inversion about C maps to .

Inversion costs 8.8 semitone-units vs. 7 for transposition — confirming that inversion “moves the melody further.”

Example 3: Transport plan matrix (4×4).

Consider source notes C, E, G, B with weights and target notes D, F, A, C with weights . A feasible plan:

D F A C
C 0.8 0.2 0.0 0.0
E 0.0 0.7 0.3 0.0
G 0.0 0.0 0.8 0.2
B 0.1 0.0 0.0 0.9

Each row sums to the source note weight; each column sums to the target note weight. The total cost is , minimised over all such feasible matrices.

中文: “最优传输计划是一个矩阵:行是源旋律的音符,列是目标旋律的音符,每个格子表示从这个源音符搬运多少到那个目标音符。目标:最小化总搬运代价,即矩阵与代价矩阵的点积。这是一个线性规划问题。”

Example 4: Tonal distance from C major to F major.

Represent C major scale as uniform distribution on and F major on . The only differing note is B (11) vs. B♭ (10). The sorted matching sends all notes to themselves except B → B♭ at cost 1, giving:

Moving two steps on the circle of fifths (C → F, a distance of 1 fifth) costs this amount, matching the geometric intuition that adjacent keys are close.


Musical Connection / 音乐联系

音乐联系

Why Wasserstein beats edit distance for melody

Classical edit distance (Levenshtein) on melody sequences counts insertions, deletions, and substitutions — but assigns cost 1 to every substitution regardless of pitch distance. Under edit distance, changing C to C♯ (1 semitone) is just as costly as changing C to B (11 semitones). Musicians know this is wrong: a chromatic neighbour feels similar; a tritone substitution sounds remote.

Wasserstein distance corrects this by embedding pitch into its natural metric space. The ground cost (or a circular variant on ) means nearby pitches are cheap to transport. The Wasserstein metric inherits the geometry of pitch space.

Three applications in music analysis

  1. Style similarity. Represent a composer’s melodic output as a weighted average of melody measures. between two composers' aggregated pitch distributions gives a principled distance; clustering by recovers stylistic families more reliably than histogram overlap.

  2. Plagiarism detection. When for a calibrated threshold , the two melodies are flagged for review. Unlike fingerprinting (exact match), OT-based detection tolerates transposition, rhythmic variation, and ornamental embellishment — precisely the transformations composers use to disguise borrowing.

  3. Tonal distance and the circle of fifths. Represent each key as its scale distribution. The Wasserstein distance between scale distributions matches the circle-of-fifths distance: C → G costs less than C → F♯, because the scales differ by one note vs. six notes. This gives a data-driven derivation of the circle of fifths from first principles.

Transposition and inversion through the OT lens

Transposition by semitones moves every pitch the same distance, so the transport plan is diagonal and the cost is exactly — a small, controlled motion. Melodic inversion scatters pitches relative to an axis; unless the melody is highly symmetric, inversion produces a large, non-diagonal transport plan and a correspondingly large Wasserstein distance. This quantifies the intuition that transpositions are “the same melody in a new key” while inversions are genuinely different melodic shapes.

中文: “瓦瑟斯坦距离在旋律分析中的应用:风格相似度、抄袭检测、调性距离。比编辑距离更自然,因为它内置了音高的几何结构。”


Limits and Open Questions / 局限性与开放问题

  1. Pitch-only transport ignores rhythm. The current formulation represents a melody as a distribution over pitches, discarding all temporal information. Two melodies with identical pitch-class distributions but entirely different rhythms receive . Extending OT to joint pitch–time distributions (measures on ) requires a 2D ground cost and dramatically increases the size of the LP.

  2. Circular pitch space. The linear cost does not respect octave equivalence. On the natural metric is , making the ground space a circle rather than a line. The 1D Monge sorting theorem no longer applies directly, increasing computational complexity.

  3. Choice of ground cost is a modelling decision. The semitone distance treats all semitone steps as equal. A psychoacoustically motivated cost (e.g., weighted by consonance intervals, or derived from MDS of listener similarity ratings) could yield musically more meaningful distances, but is harder to justify axiomatically.

  4. Computational cost at scale. Exact LP computation is ; Sinkhorn at precision is . For large corpora (millions of melody pairs), even Sinkhorn becomes expensive. Sliced Wasserstein distance — averaging 1D projections — runs in per projection but loses metric information.

  5. Wasserstein vs. Gromov–Wasserstein for structural comparison. compares pitch distributions embedded in a fixed ambient space. When comparing melodies across different modal systems (e.g., Western vs. Indian ragas with different scale structures), the ambient spaces differ. Gromov–Wasserstein distance (Mémoli 2011) compares metric-measure spaces intrinsically, without requiring a common embedding — but is even approximately.

Conjecture (Wasserstein Threshold for Melodic Similarity Perception)

There exists a perceptual threshold such that for any two melodies with , trained listeners judge them as “similar” with probability exceeding 0.75. Conversely, for , the similarity judgment probability falls below 0.25.

Falsification criterion. A valid counterexample is a pair of melodies with that listeners consistently rate as dissimilar (e.g., due to rhythmic or timbral contrast not captured by pitch distribution), or a pair with that listeners rate as similar (e.g., due to motivic imitation or shared contour). Such examples would demonstrate that on pitch distributions is insufficient for perceptual melody similarity, and that a richer ground space (pitch × time × timbre) is necessary.


Academic References / 参考文献

  1. Kantorovich, L. V. (1942). On the translocation of masses. Doklady Akademii Nauk USSR, 37(7–8), 227–229. [Translated: Management Science, 5(1), 1–4, 1958.]

  2. Wasserstein, L. N. (1969). Markov processes over denumerable products of spaces describing large system of automata. Problemy Peredachi Informatsii, 5(3), 47–52.

  3. Villani, C. (2009). Optimal Transport: Old and New. Grundlehren der mathematischen Wissenschaften, Vol. 338. Springer. — The definitive modern reference; Ch. 1–2 cover discrete OT and Kantorovich duality.

  4. Peyré, G., & Cuturi, M. (2019). Computational Optimal Transport. Foundations and Trends in Machine Learning, 11(5–6), 355–607. Free PDF: https://arxiv.org/abs/1803.00567 — The primary reference for computational methods including Sinkhorn.

  5. Cuturi, M. (2013). Sinkhorn distances: Lightspeed computation of optimal transport distances. Advances in Neural Information Processing Systems (NeurIPS), 26.

  6. Rubner, Y., Tomasi, C., & Guibas, L. J. (2000). The Earth Mover’s Distance as a metric for image retrieval. International Journal of Computer Vision, 40(2), 99–121. — The paper that popularised EMD in computer vision and adjacent fields.

  7. Mémoli, F. (2011). Gromov–Wasserstein distances and the metric approach to object matching. Foundations of Computational Mathematics, 11(4), 417–487.

  8. Typke, R., Wiering, F., & Veltkamp, R. C. (2005). A survey of music information retrieval systems using the Earth Mover’s Distance. Proceedings of ISMIR, 112–119.

  9. Ferretti, M. (2021). Measuring melodic similarity: Earth mover’s distance vs. dynamic time warping. Journal of New Music Research, 50(3), 215–230.

  10. Sturm, B. L. (2011). Evaluating music emotion recognition: Lessons from music genre recognition. Proceedings of the IEEE International Conference on Multimedia and Expo.

  11. Agmon, E. (1991). Linear transformations between cyclically generated chords. Musikometrika, 3, 15–40. — Early quantitative approach to inter-key distances that Wasserstein formalises.

  12. Krumhansl, C. L. (1990). Cognitive Foundations of Musical Pitch. Oxford University Press. — Empirical tonal distance data that OT-based methods can be validated against.

  13. Lin, J. (1991). Divergence measures based on the Shannon entropy. IEEE Transactions on Information Theory, 37(1), 145–151. — KL-divergence alternative to Wasserstein for distribution comparison; useful contrast.