Skip to content

Instantly share code, notes, and snippets.

@pukpr
Created December 8, 2023 17:14
Show Gist options
  • Save pukpr/fcc9ba38c5f92bde0b53dc95c44ff7dc to your computer and use it in GitHub Desktop.
Save pukpr/fcc9ba38c5f92bde0b53dc95c44ff7dc to your computer and use it in GitHub Desktop.
Dynamic Time Warping Distance
function DTW_Distance(X, Y: in Data_Pairs; Window_Size: Positive) return Long_Float is
N : Positive := X'Length;
type Real_Array is array(X'First - Window_Size .. X'Last + Window_Size) of Long_Float;
DTW_Current, DTW_Previous : Real_Array := (others => Long_Float'Last);
begin
DTW_Previous(X'First) := 0.0;
for I in X'First .. X'Last loop
DTW_Current(X'First) := Long_Float'Last; -- Reset current row
for J in Integer'Max(X'First, I - Window_Size) .. Integer'Min(X'Last, I + Window_Size) loop
declare
Cost : Long_Float := Abs(X(I).Value - Y(J).Value);
Min_Cost : Long_Float;
J_Previous : Integer := Integer'Max(J - 1, Y'First);
begin
-- Compute minimum cost considering the DTW constraint
Min_Cost := Long_Float'Min( Long_Float'Min(
DTW_Previous(J_Previous),
DTW_Current(J_Previous)),
(if J > Y'First then DTW_Previous(J) else Long_Float'Last)
);
DTW_Current(J) := Cost + Min_Cost;
end;
end loop;
-- Swap the rows
DTW_Previous := DTW_Current;
end loop;
return 1.0/DTW_Current(N);
end DTW_Distance;
@pukpr
Copy link
Author

pukpr commented Mar 31, 2024

reconstructed QBO driving from above

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment