comparison trajectorymanagement/src/DTWMetric.h @ 1159:e1e7acef8eab

moved trajectory management library into Traffic Intelligence
author Nicolas Saunier <nicolas.saunier@polymtl.ca>
date Mon, 22 Feb 2021 22:09:35 -0500
parents
children
comparison
equal deleted inserted replaced
1158:7eb972942f22 1159:e1e7acef8eab
1 #ifndef DTWMETRIC_H_
2 #define DTWMETRIC_H_
3
4 #include "Metric.h"
5
6 /**
7 * DTWMetric class.
8 *
9 * The Dynamic Time Warping metric measures the similarity between two trajectories.
10 */
11 template<typename Tr, typename To>
12 class DTWMetric: public Metric<Tr, To>
13 {
14 public:
15 /**
16 * Constructor.
17 */
18 DTWMetric()
19 {
20 maxDTWValue = (std::numeric_limits<To>::max()) / To(2);
21 }
22
23 /**
24 * Set maximum value that occurs during the calculation process.
25 *
26 * @param[in] maxDTWValue maximum value
27 */
28 bool setMaxDTWValue(To maxDTWValue)
29 {
30 if (maxDTWValue >= 0.0)
31 {
32 this->maxDTWValue = maxDTWValue;
33 return true;
34 }
35 return false;
36 }
37
38 /**
39 * Set maximum value that occurs during the calculation process.
40 *
41 * @param[in] imgSize image size
42 * @param[in] eps machine epsilon
43 */
44 bool setMaxDTWValue(CvSize &imgSize, double eps)
45 {
46 if (imgSize.width > 0 && imgSize.height > 0 && eps > 0)
47 {
48 cv::Point_<int> p(imgSize.width, imgSize.height);
49 maxDTWValue = std::numeric_limits<To>::max() - norm(p) - eps;
50 return true;
51 }
52 return false;
53 }
54
55 /**
56 * Compute similarity between two trajectories.
57 *
58 * @param[in] a input trajectory
59 * @param[in] b input trajectory
60 * @param[out] result distance between two trajectories.
61 */
62 void distance(const Trajectory<Tr> *a, const Trajectory<Tr> *b, To &result, unsigned int nbOfPoints = std::numeric_limits<unsigned int>::max())
63 {
64 To DTW[a->size() + 1][b->size() + 1];
65
66 { //initialization
67 for (unsigned int i = 0; i <= a->size(); ++i)
68 {
69 DTW[i][0] = maxDTWValue;
70 }
71
72 for (unsigned int j = 0; j <= b->size(); ++j)
73 {
74 DTW[0][j] = maxDTWValue;
75 }
76
77 DTW[0][0] = 0.0;
78 }
79
80 { //algorithm
81 for (unsigned int i = 1; i <= a->size(); ++i)
82 {
83 for (unsigned int j = 1; j <= b->size(); ++j)
84 {
85 To smallest = min(DTW[i - 1][j], DTW[i][j - 1], DTW[i - 1][j - 1]);
86 cv::Point3_<typeof(static_cast<Tr>(a->getPoint(i-1)).x)> p(a->getPoint(i - 1) - b->getPoint(j - 1));
87 To distance = std::sqrt(std::pow(p.x, 2) + std::pow(p.y, 2) + std::pow(p.z, 2));
88 DTW[i][j] = std::min(smallest + distance, maxDTWValue);
89 }
90 }
91 }
92
93 result = DTW[a->size()][b->size()];
94 }
95
96 private:
97 /**
98 * Maximum value that occurs during the calculation process.
99 */
100 To maxDTWValue;
101
102 /**
103 * Compute the minimum of \a a, \a b and \c c.
104 *
105 * @param[in] a input parameter
106 * @param[in] b input parameter
107 * @param[in] c input parameter
108 */
109 To min(To a, To b, To c)
110 {
111 return std::min(std::min(a, b), c);
112 }
113 };
114
115 #endif /* DTWMETRIC_H_ */