Welcome to mirror list, hosted at ThFree Co, Russian Federation.

candidate_paths_getter.cpp « openlr - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 85aa91682641a4d0bd7347eea0bf25a0f82c0a58 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
#include "openlr/candidate_paths_getter.hpp"

#include "openlr/candidate_points_getter.hpp"
#include "openlr/graph.hpp"
#include "openlr/helpers.hpp"
#include "openlr/openlr_model.hpp"

#include "routing/road_graph.hpp"

#include "platform/location.hpp"

#include "geometry/angles.hpp"

#include <algorithm>
#include <iterator>
#include <queue>
#include <set>
#include <tuple>

using namespace std;
using namespace routing;

namespace openlr
{
namespace
{
// TODO(mgsergio): Maybe add a penalty if this value deviates, not just throw it away.
int const kFRCThreshold = 3;

int const kNumBuckets = 256;
double const kAnglesInBucket = 360.0 / kNumBuckets;

m2::PointD PointAtSegmentM(m2::PointD const & p1, m2::PointD const & p2, double const distanceM)
{
  auto const v = p2 - p1;
  auto const l = v.Length();
  auto const L = MercatorBounds::DistanceOnEarth(p1, p2);
  auto const delta = distanceM * l / L;
  return PointAtSegment(p1, p2, delta);
}

uint32_t Bearing(m2::PointD const & a, m2::PointD const & b)
{
  auto const angle = location::AngleToBearing(my::RadToDeg(ang::AngleTo(a, b)));
  CHECK_LESS_OR_EQUAL(angle, 360, ("Angle should be less than or equal to 360."));
  CHECK_GREATER_OR_EQUAL(angle, 0, ("Angle should be greater than or equal to 0"));
  return my::clamp(angle / kAnglesInBucket, 0.0, 255.0);
}

// This class is used to get correct points for further bearing calculations.
// Depending on |isLastPoint| it either calculates those points straightforwardly
// or reverses directions and then calculates.
class BearingPointsSelector
{
public:
  BearingPointsSelector(uint32_t const bearDistM, bool const isLastPoint)
    : m_bearDistM(bearDistM), m_isLastPoint(isLastPoint)
  {
  }

  m2::PointD GetBearingStartPoint(Graph::Edge const & e) const
  {
    return m_isLastPoint ? e.GetEndPoint() : e.GetStartPoint();
  }

  m2::PointD GetBearingEndPoint(Graph::Edge const & e, double const distanceM)
  {
    if (distanceM < m_bearDistM && m_bearDistM <= distanceM + EdgeLength(e))
    {
      auto const edgeLen = EdgeLength(e);
      auto const edgeBearDist = min(m_bearDistM - distanceM, edgeLen);
      ASSERT_LESS_OR_EQUAL(edgeBearDist, edgeLen, ());
      return m_isLastPoint ? PointAtSegmentM(e.GetEndPoint(), e.GetStartPoint(),
                                             static_cast<double>(edgeBearDist))
                           : PointAtSegmentM(e.GetStartPoint(), e.GetEndPoint(),
                                             static_cast<double>(edgeBearDist));
    }
    return m_isLastPoint ? e.GetStartPoint() : e.GetEndPoint();
  }

private:
  double m_bearDistM;
  bool m_isLastPoint;
};
}  // namespace

// CandidatePathsGetter::Link ----------------------------------------------------------------------
bool CandidatePathsGetter::Link::operator<(Link const & o) const
{
  if (m_distanceM != o.m_distanceM)
    return m_distanceM < o.m_distanceM;

  if (m_edge != o.m_edge)
    return m_edge < o.m_edge;

  if (m_parent == o.m_parent)
    return false;

  if (m_parent && o.m_parent)
    return *m_parent < *o.m_parent;

  if (!m_parent)
    return true;

  return false;
}

Graph::Edge CandidatePathsGetter::Link::GetStartEdge() const
{
  auto * start = this;
  while (start->m_parent)
    start = start->m_parent.get();

  return start->m_edge;
}

bool CandidatePathsGetter::Link::IsJunctionInPath(routing::Junction const & j) const
{
  for (auto * l = this; l; l = l->m_parent.get())
  {
    if (l->m_edge.GetEndJunction() == j)
    {
      LOG(LDEBUG, ("A loop detected, skipping..."));
      return true;
    }
  }

  return false;
}

// CandidatePathsGetter ----------------------------------------------------------------------------
bool CandidatePathsGetter::GetLineCandidatesForPoints(
    vector<LocationReferencePoint> const & points,
    vector<vector<Graph::EdgeVector>> & lineCandidates)
{
  for (size_t i = 0; i < points.size(); ++i)
  {
    if (i != points.size() - 1 && points[i].m_distanceToNextPoint == 0)
    {
      LOG(LINFO, ("Distance to next point is zero. Skipping the whole segment"));
      ++m_stats.m_dnpIsZero;
      return false;
    }

    lineCandidates.emplace_back();
    auto const isLastPoint = i == points.size() - 1;
    double const distanceToNextPointM =
        (isLastPoint ? points[i - 1] : points[i]).m_distanceToNextPoint;

    vector<m2::PointD> pointCandidates;
    m_pointsGetter.GetCandidatePoints(MercatorBounds::FromLatLon(points[i].m_latLon),
                                      pointCandidates);
    GetLineCandidates(points[i], isLastPoint, distanceToNextPointM, pointCandidates,
                      lineCandidates.back());

    if (lineCandidates.back().empty())
    {
      LOG(LINFO, ("No candidate lines found for point", points[i].m_latLon, "Giving up"));
      ++m_stats.m_noCandidateFound;
      return false;
    }
  }

  ASSERT_EQUAL(lineCandidates.size(), points.size(), ());

  return true;
}

void CandidatePathsGetter::GetStartLines(vector<m2::PointD> const & points, bool const isLastPoint,
                                         Graph::EdgeVector & edges)
{
  for (auto const & pc : points)
  {
    if (!isLastPoint)
      m_graph.GetOutgoingEdges(Junction(pc, 0 /* altitude */), edges);
    else
      m_graph.GetIngoingEdges(Junction(pc, 0 /* altitude */), edges);
  }

  // Same edges may start on different points if those points are close enough.
  my::SortUnique(edges, less<Graph::Edge>(), EdgesAreAlmostEqual);
}

void CandidatePathsGetter::GetAllSuitablePaths(Graph::EdgeVector const & startLines,
                                               bool const isLastPoint, double const bearDistM,
                                               FunctionalRoadClass const frc,
                                               vector<LinkPtr> & allPaths)
{
  queue<LinkPtr> q;

  for (auto const & e : startLines)
  {
    auto const u = make_shared<Link>(nullptr /* parent */, e, 0 /* distanceM */);
    q.push(u);
  }

  while (!q.empty())
  {
    auto const u = q.front();
    q.pop();

    auto const & currentEdge = u->m_edge;
    auto const currentEdgeLen = EdgeLength(currentEdge);

    // TODO(mgsergio): Maybe weak this constraint a bit.
    if (u->m_distanceM + currentEdgeLen >= bearDistM)
    {
      allPaths.push_back(u);
      continue;
    }

    ASSERT_LESS(u->m_distanceM + currentEdgeLen, bearDistM, ());

    Graph::EdgeVector edges;
    if (!isLastPoint)
      m_graph.GetOutgoingEdges(currentEdge.GetEndJunction(), edges);
    else
      m_graph.GetIngoingEdges(currentEdge.GetStartJunction(), edges);

    for (auto const & e : edges)
    {
      // Fake edges are allowed only at the start/end of the path.
      if (e.IsFake())
        continue;

      if (EdgesAreAlmostEqual(e.GetReverseEdge(), currentEdge))
        continue;

      ASSERT(currentEdge.HasRealPart(), ());

      if (!PassesRestriction(e, frc, kFRCThreshold, m_infoGetter))
        continue;

      // TODO(mgsergio): Should we check form of way as well?

      if (u->IsJunctionInPath(e.GetEndJunction()))
        continue;

      auto const p = make_shared<Link>(u, e, u->m_distanceM + currentEdgeLen);
      q.push(p);
    }
  }
}

void CandidatePathsGetter::GetBestCandidatePaths(
    vector<LinkPtr> const & allPaths, bool const isLastPoint, uint32_t const requiredBearing,
    double const bearDistM, m2::PointD const & startPoint, vector<Graph::EdgeVector> & candidates)
{
  set<CandidatePath> candidatePaths;
  set<CandidatePath> fakeEndingsCandidatePaths;

  BearingPointsSelector pointsSelector(bearDistM, isLastPoint);
  for (auto const & l : allPaths)
  {
    auto const bearStartPoint = pointsSelector.GetBearingStartPoint(l->GetStartEdge());
    auto const startPointsDistance = MercatorBounds::DistanceOnEarth(bearStartPoint, startPoint);

    // Number of edges counting from the last one to check bearing on. Accorfing to OpenLR spec
    // we have to check bearing on a point that is no longer than 25 meters traveling down the path.
    // But sometimes we may skip the best place to stop and generate a candidate. So we check several
    // edges before the last one to avoid such a situation. Number of iterations is taken
    // by intuition.
    // Example:
    // o -------- o  { Partners segment. }
    // o ------- o --- o { Our candidate. }
    //               ^ 25m
    //           ^ This one may be better than
    //                 ^ this one.
    // So we want to check them all.
    uint32_t traceBackIterationsLeft = 3;
    for (auto part = l; part; part = part->m_parent)
    {
      if (traceBackIterationsLeft == 0)
        break;

      --traceBackIterationsLeft;

      auto const bearEndPoint =
          pointsSelector.GetBearingEndPoint(part->m_edge, part->m_distanceM);

      auto const bearing = Bearing(bearStartPoint, bearEndPoint);
      auto const bearingDiff = AbsDifference(bearing, requiredBearing);
      auto const pathDistDiff = AbsDifference(part->m_distanceM, bearDistM);

      // TODO(mgsergio): Check bearing is within tolerance. Add to canidates if it is.

      if (part->m_hasFake)
        fakeEndingsCandidatePaths.emplace(part, bearingDiff, pathDistDiff, startPointsDistance);
      else
        candidatePaths.emplace(part, bearingDiff, pathDistDiff, startPointsDistance);
    }
  }

  ASSERT(
      none_of(begin(candidatePaths), end(candidatePaths), mem_fn(&CandidatePath::HasFakeEndings)),
      ());
  ASSERT(fakeEndingsCandidatePaths.empty() ||
             any_of(begin(fakeEndingsCandidatePaths), end(fakeEndingsCandidatePaths),
                    mem_fn(&CandidatePath::HasFakeEndings)),
         ());

  vector<CandidatePath> paths;
  copy_n(begin(candidatePaths), min(static_cast<size_t>(kMaxCandidates), candidatePaths.size()),
         back_inserter(paths));

  copy_n(begin(fakeEndingsCandidatePaths),
         min(static_cast<size_t>(kMaxFakeCandidates), fakeEndingsCandidatePaths.size()),
         back_inserter(paths));

  LOG(LDEBUG, ("List candidate paths..."));
  for (auto const & path : paths)
  {
    LOG(LDEBUG, ("CP:", path.m_bearingDiff, path.m_pathDistanceDiff, path.m_startPointDistance));
    Graph::EdgeVector edges;
    for (auto * p = path.m_path.get(); p; p = p->m_parent.get())
      edges.push_back(p->m_edge);
    if (!isLastPoint)
      reverse(begin(edges), end(edges));

    candidates.emplace_back(move(edges));
  }
}

void CandidatePathsGetter::GetLineCandidates(openlr::LocationReferencePoint const & p,
                                             bool const isLastPoint,
                                             double const distanceToNextPointM,
                                             vector<m2::PointD> const & pointCandidates,
                                             vector<Graph::EdgeVector> & candidates)
{
  double const kDefaultBearDistM = 25.0;
  double const bearDistM = min(kDefaultBearDistM, distanceToNextPointM);

  LOG(LINFO, ("BearDist is", bearDistM));

  Graph::EdgeVector startLines;
  GetStartLines(pointCandidates, isLastPoint, startLines);

  LOG(LINFO, (startLines.size(), "start line candidates found for point (LatLon)", p.m_latLon));
  LOG(LDEBUG, ("Listing start lines:"));
  for (auto const & e : startLines)
    LOG(LDEBUG, (LogAs2GisPath(e)));

  auto const startPoint = MercatorBounds::FromLatLon(p.m_latLon);

  vector<LinkPtr> allPaths;
  GetAllSuitablePaths(startLines, isLastPoint, bearDistM, p.m_functionalRoadClass, allPaths);
  GetBestCandidatePaths(allPaths, isLastPoint, p.m_bearing, bearDistM, startPoint, candidates);
  LOG(LDEBUG, (candidates.size(), "candidate paths found for point (LatLon)", p.m_latLon));
}
}  // namespace openlr