Skip to content

Commit

Permalink
linear implementation of Frechet distance
Browse files Browse the repository at this point in the history
  • Loading branch information
Marco Conte committed Jul 11, 2024
1 parent ff0eccb commit a81943c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 17 deletions.
2 changes: 2 additions & 0 deletions geo/CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
* <https://github.com/georust/geo/pull/1192>
* Fix `AffineTransform::compose` ordering to be conventional - such that the argument is applied *after* self.
* <https://github.com/georust/geo/pull/1196>
* Implement Frechet distance using linear algorithm to avoid `fatal runtime error: stack overflow` and improve overall performances.
* <https://github.com/georust/geo/pull/1199>

## 0.28.0

Expand Down
42 changes: 25 additions & 17 deletions geo/src/algorithm/frechet_distance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,12 @@ where
{
fn frechet_distance(&self, ls: &LineString<T>) -> T {
if self.coords_count() != 0 && ls.coords_count() != 0 {
let mut data = Data {
cache: vec![vec![T::nan(); ls.coords_count()]; self.coords_count()],
Data {
cache: vec![T::zero(); self.coords_count() * ls.coords_count()],
ls_a: self,
ls_b: ls,
};
data.compute(self.coords_count() - 1, ls.coords_count() - 1)
}
.compute_linear()
} else {
T::zero()
}
Expand All @@ -63,7 +63,7 @@ struct Data<'a, T>
where
T: GeoFloat + FromPrimitive,
{
cache: Vec<Vec<T>>,
cache: Vec<T>,
ls_a: &'a LineString<T>,
ls_b: &'a LineString<T>,
}
Expand All @@ -72,19 +72,27 @@ impl<'a, T> Data<'a, T>
where
T: GeoFloat + FromPrimitive,
{
fn compute(&mut self, i: usize, j: usize) -> T {
if self.cache[i][j].is_nan() {
let eucl = Point::from(self.ls_a[i]).euclidean_distance(&Point::from(self.ls_b[j]));
self.cache[i][j] = match (i, j) {
(0, 0) => eucl,
(_, 0) => self.compute(i - 1, 0).max(eucl),
(0, _) => self.compute(0, j - 1).max(eucl),
(_, _) => ((self.compute(i - 1, j).min(self.compute(i - 1, j - 1)))
.min(self.compute(i, j - 1)))
.max(eucl),
};
/// [Reference implementation]: https://github.com/joaofig/discrete-frechet/tree/master
fn compute_linear(&mut self) -> T {
let columns_count = self.ls_b.coords_count();

for (i, &a) in self.ls_a.coords().enumerate() {
for (j, &b) in self.ls_b.coords().enumerate() {
let dist = Point::from(a).euclidean_distance(&Point::from(b));

self.cache[i * columns_count + j] = match (i, j) {
(0, 0) => dist,
(_, 0) => self.cache[(i - 1) * columns_count].max(dist),
(0, _) => self.cache[j - 1].max(dist),
(_, _) => self.cache[(i - 1) * columns_count + j]
.min(self.cache[(i - 1) * columns_count + j - 1])
.min(self.cache[i * columns_count + j - 1])
.max(dist),
};
}
}
self.cache[i][j]

self.cache[self.cache.len() - 1]
}
}

Expand Down

0 comments on commit a81943c

Please sign in to comment.