# Python implementation for Frechet Distance

I am working on a trajectory analysis project using python and its data science related libraries. I am planning to implement Frechet Distance algorithm for trajectory analysis, each trajectory has sequence of (x,y) coordinates along with timestamp, speed, dist between consecutive points, etc.

I would kindly request if anyone who has experience with in this field and trajectory analysis, can provide with some useful links for Python implementation of Frechet Distance. My ultimate goal is to cluster the similar trajectories (location and direction wise).

• You might be better off with your question if you defined in mathematical terms the problem you want to solve, rather than just in words. – Wolfgang Bangerth May 22 '17 at 22:57
• May this help: discrete_frechet. – Herpes Free Engineer Jun 8 '17 at 13:42

## 2 Answers

I realize this question was asked a while ago, but I recently needed the Freschet distance as well. I couldn't find any implementations for Python, so I wrote my own based on the paper: "Computing Discrete Frechet Distance" by "Thomas Eiter and Heikki Mannila", and thought I would share it for future reference.

It's written in Cython (save as frechet.pyx)

# Julius Bier Kirkegaard 2017
# Based on "Computing Discrete Frechet Distance" by "Thomas Eiter and Heikki Mannila".
#cython: boundscheck=False
#cython: wraparound=False
import numpy as np
cimport numpy as np
from libc.math cimport sqrt, cos, sin

cdef double d(double p, double q):
return (p - q)*(p - q)

cdef double c(int i, int j, double* P, double* Q, double* ca, int N):
cdef int index = i*N+j
cdef double d_t = d(P[i], Q[j])
cdef double m1, m2

if ca[index] > -1:
return ca[index]

elif i == 0 and j == 0:
ca[index] = d(P[i], Q[j])

elif i > 0 and j == 0:
if d_t > ca[(i-1)*N+j]:
ca[index] = d_t
else:
ca[index] = ca[(i-1)*N+j]

elif i == 0 and j > 0:
if d_t > ca[i*N+(j-1)]:
ca[index] = d_t
else:
ca[index] = ca[i*N+(j-1)]

elif i > 0 and j > 0:
m1 = c(i - 1, j, P, Q, ca, N)
m2 = c(i, j - 1, P, Q, ca, N)
if m2 < m1:
m1 = m2
m2 = c(i - 1, j - 1, P, Q, ca, N)
if m2 < m1:
m1 = m2
if d_t > m1:
ca[index] = d_t
else:
ca[index] = m1
else:
ca[index] = 1e50

return ca[index]

def frechet(np.ndarray[np.float64_t,ndim=1,
negative_indices=False,
mode='c'] P,
np.ndarray[np.float64_t,ndim=1,
negative_indices=False,
mode='c'] Q):

cdef np.ndarray[np.float64_t,ndim=2,
negative_indices=False,
mode='c'] ca = np.zeros((len(P), len(Q))) - 1

return c(len(P)-1, len(Q)-1, &P, &Q, &ca[0,0], ca.shape)


Here's an example:

import pyximport; pyximport.install()
from frechet import frechet
import numpy as np

P = np.arange(5, dtype=np.float64)
Q = 2*np.arange(7, dtype=np.float64)

print P, Q

ca = frechet(P, Q)
print ca

print (P[-1] - Q[-1])**2


There is a discussion in Tyler Reddy's very recent pycon2017 tutorial on youtube https://youtu.be/ETJc3NfU9aA?t=9540 (at 2:39.00) where he discusses implementing the Frechet Distance in scipy.spatial. It is not done yet but he runs an implementation that he has wrapped in Python.
{"ft_lang_label":"__label__en","ft_lang_prob":0.6207404,"math_prob":0.9560241,"size":1892,"snap":"2021-04-2021-17","text_gpt3_token_len":691,"char_repetition_ratio":0.12870763,"word_repetition_ratio":0.1495327,"special_character_ratio":0.3757928,"punctuation_ratio":0.1923077,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9988374,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-04-14T16:51:29Z\",\"WARC-Record-ID\":\"<urn:uuid:41acb681-fc82-4fc4-8f3e-c77e5d92f001>\",\"Content-Length\":\"183170\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:09dc0308-3517-4d3b-96b0-89017a953818>\",\"WARC-Concurrent-To\":\"<urn:uuid:ae55fa81-e756-40c6-85e9-43de4e25c344>\",\"WARC-IP-Address\":\"151.101.65.69\",\"WARC-Target-URI\":\"https://scicomp.stackexchange.com/questions/26942/python-implementation-for-frechet-distance/28142\",\"WARC-Payload-Digest\":\"sha1:PE3WTZRH67U3OMSN6HLID5ZWWA67DDWQ\",\"WARC-Block-Digest\":\"sha1:XTTVBCYIMN6CR2HW7MOBAKMTV5AHE4JW\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-17/CC-MAIN-2021-17_segments_1618038077843.17_warc_CC-MAIN-20210414155517-20210414185517-00354.warc.gz\"}"}