← All papers
First page of A Machine-Checked Theory of Dynamic Time Warping in Lean 4

A Machine-Checked Theory of Dynamic Time Warping in Lean 4

Srihari Maruthachalam

eess.SP Nov 30, 2026 · v1 cs.LO
Formalizes dynamic time warping in Lean 4 with Mathlib: DP recurrence optimality, banded constraints, lower bounds (LB_Kim, LB_Keogh), and a verified executable implementation.
Dynamic time warping (DTW) is a standard dissimilarity measure for time series. In practice, large-scale DTW search depends on two ingredients whose correctness is usually argued on paper: global path constraints such as the Sakoe-Chiba band, and cheap lower bounds such as LB_Kim and LB_Keogh that prune candidates without false dismissals. We present a formalization of DTW in Lean 4 with mathlib, covering: warping paths and DTW as a minimum over them; correctness of the dynamic-programming recurrence; nonnegativity, symmetry and DTW(x,x)=0, with a machine-checked witness of the known failure of the triangle inequality; constrained and Sakoe-Chiba banded DTW; the LB_Kim, LB_KimFL, LB_Yi and LB_Keogh lower bounds, the last restated for an arbitrary global constraint; and an executable row-by-row implementation proved equal to the specification. The recurrence is proved once, for cell costs in an arbitrary linearly ordered additive commutative monoid. Instantiating it at the reals extended with a top element yields constrained DTW with no separate optimality proof. The development has no sorry, and every main theorem uses only Lean's standard axioms. To our knowledge it is the first formalization of DTW itself in a proof assistant. The mathematics is classical; the contribution is a checked, reusable development and the precision it forces.

Large-scale dynamic time warping (DTW) search relies on global path constraints such as the Sakoe-Chiba band and on cheap lower bounds such as LB_Kim and LB_Keogh. Their correctness has been argued only on paper. No prior formalization of DTW in a proof assistant was found.

DTW is defined in Lean 4 over Mathlib as a minimum over warping paths, with a DP table defined by well-founded recursion. The recurrence is proved optimal once, for cell costs in an arbitrary linearly ordered additive commutative monoid. Instantiating it at WithTop ℝ gives constrained and banded DTW without a separate optimality proof. Lower bounds are derived from the fact that DTW is attained by some path, and a single-row executable DP is proved equal to the specification.

The development proves nonnegativity, symmetry, DTW(x,x)=0, a kernel-checked counterexample to the triangle inequality, band monotonicity, exactness and finiteness, and the LB_Kim, LB_KimFL, LB_Yi and LB_Keogh bounds (LB_Keogh for arbitrary constraints), with no sorry and only standard axioms. The executable DP agrees with an independent Python implementation on 21 test pairs. Formalizing also made explicit two small issues in the prior presentation of the path conditions and of LB_Kim.