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

hierarchy.cpp « generator - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: afd7a3b2fb7b7a7fc0dc63d9a070ced9944069e5 (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
#include "generator/hierarchy.hpp"

#include "indexer/feature_algo.hpp"

#include "geometry/mercator.hpp"
#include "geometry/rect2d.hpp"

#include "base/assert.hpp"
#include "base/stl_helpers.hpp"

#include <algorithm>
#include <cmath>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iterator>
#include <limits>
#include <numeric>

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/register/point.hpp>
#include <boost/geometry/geometries/register/ring.hpp>

BOOST_GEOMETRY_REGISTER_POINT_2D(m2::PointD, double, boost::geometry::cs::cartesian, x, y);
BOOST_GEOMETRY_REGISTER_RING(std::vector<m2::PointD>);

using namespace feature;

namespace generator
{
namespace hierarchy
{
namespace
{
double CalculateOverlapPercentage(std::vector<m2::PointD> const & lhs,
                                  std::vector<m2::PointD> const & rhs)
{
  if (!boost::geometry::intersects(lhs, rhs))
    return 0.0;

  using BoostPolygon = boost::geometry::model::polygon<m2::PointD>;
  std::vector<BoostPolygon> coll;
  boost::geometry::intersection(lhs, rhs, coll);
  auto const min = std::min(boost::geometry::area(lhs), boost::geometry::area(rhs));
  CHECK_GREATER(min, 0.0, (min));
  auto const binOp = [](double x, BoostPolygon const & y) { return x + boost::geometry::area(y); };
  auto const sum = std::accumulate(std::cbegin(coll), std::cend(coll), 0.0, binOp);
  return sum * 100 / min;
}
}  // namespace

bool FilterFeatureDefault(feature::FeatureBuilder const &) { return true; }

HierarchyPlace::HierarchyPlace(FeatureBuilder const & fb)
  : m_id(MakeCompositeId(fb))
  , m_name(fb.GetMultilangName())
  , m_types(fb.GetTypes())
  , m_rect(fb.GetLimitRect())
  , m_center(fb.GetKeyPoint())
{
  if (fb.IsPoint())
  {
    m_isPoint = true;
  }
  else if (fb.IsArea())
  {
    m_polygon = fb.GetOuterGeometry();
    boost::geometry::correct(m_polygon);
    m_area = boost::geometry::area(m_polygon);
  }
}

bool HierarchyPlace::Contains(HierarchyPlace const & smaller) const
{
  if (IsPoint())
    return false;

  if (smaller.IsPoint())
    return Contains(smaller.GetCenter());

  return smaller.GetArea() <= GetArea() &&
         CalculateOverlapPercentage(m_polygon, smaller.m_polygon) > 80.0;
}

bool HierarchyPlace::Contains(m2::PointD const & point) const
{
  return boost::geometry::covered_by(point, m_polygon);
}

HierarchyLinker::HierarchyLinker(Node::Ptrs && nodes)
  : m_nodes(std::move(nodes)), m_tree(MakeTree4d(m_nodes))
{
}

// static
HierarchyLinker::Tree4d HierarchyLinker::MakeTree4d(Node::Ptrs const & nodes)
{
  Tree4d tree;
  for (auto const & n : nodes)
    tree.Add(n, n->GetData().GetLimitRect());
  return tree;
}

HierarchyLinker::Node::Ptr HierarchyLinker::FindPlaceParent(HierarchyPlace const & place)
{
  Node::Ptr parent = nullptr;
  auto minArea = std::numeric_limits<double>::max();
  auto const point = place.GetCenter();
  m_tree.ForEachInRect({point, point}, [&](auto const & candidateNode) {
    // https://wiki.openstreetmap.org/wiki/Simple_3D_buildings
    // An object with tag 'building:part' is a part of a relation with outline 'building' or
    // is contained in a object with tag 'building'. This case is second. We suppose a building part is
    // only inside a building.
    static auto const & buildingChecker = ftypes::IsBuildingChecker::Instance();
    static auto const & buildingPartChecker = ftypes::IsBuildingPartChecker::Instance();
    auto const & candidate = candidateNode->GetData();
    if (buildingPartChecker(place.GetTypes()) &&
        !(buildingChecker(candidate.GetTypes()) || buildingPartChecker(candidate.GetTypes())))
    {
      return;
    }

    // A building part must have children only with 'building:part' type.
    if (!buildingPartChecker(place.GetTypes()) && buildingPartChecker(candidate.GetTypes()))
      return;

    if (place.GetCompositeId() == candidate.GetCompositeId())
      return;

    if (candidate.GetArea() < minArea && candidate.Contains(place))
    {
      // Sometimes there can be two places with the same geometry. We must check place node and
      // its parents to avoid cyclic connections.
      auto node = candidateNode;
      while (node->HasParent())
      {
        node = node->GetParent();
        if (node->GetData().GetCompositeId() == place.GetCompositeId())
          return;
      }

      parent = candidateNode;
      minArea = candidate.GetArea();
    }
  });
  return parent;
}

HierarchyLinker::Node::Ptrs HierarchyLinker::Link()
{
  for (auto & node : m_nodes)
  {
    auto const & place = node->GetData();
    auto const parentPlace = FindPlaceParent(place);
    if (!parentPlace)
      continue;

    tree_node::Link(node, parentPlace);
  }
  return m_nodes;
}

HierarchyEntryEnricher::HierarchyEntryEnricher(std::string const & osm2FtIdsPath,
                                             std::string const & countryFullPath)
  : m_featureGetter(countryFullPath)
{
  CHECK(m_osm2FtIds.ReadFromFile(osm2FtIdsPath), (osm2FtIdsPath));
}

std::optional<m2::PointD> HierarchyEntryEnricher::GetFeatureCenter(CompositeId const & id) const
{
  auto const optIds = m_osm2FtIds.GetFeatureIds(id);
  if (optIds.empty())
    return {};

  // A CompositeId id may correspond to several feature ids. These features can be represented by
  // three types of geometry. Logically, their centers coincide, but in practice they don’t,
  // because the centers are calculated differently. For example, for an object with a type area,
  // the area will be computed using the triangles geometry, but for an object with a type line,
  // the area will be computed using the outer geometry of a polygon.
  std::unordered_map<std::underlying_type_t<feature::GeomType>, m2::PointD> m;
  for (auto optId : optIds)
  {
    auto const ftPtr = m_featureGetter.GetFeatureByIndex(optId);
    if (!ftPtr)
      continue;

    CHECK(m.emplace(base::Underlying(ftPtr->GetGeomType()), feature::GetCenter(*ftPtr)).second,
          (id, optIds));
  }

  for (auto type : {
       base::Underlying(feature::GeomType::Point),
       base::Underlying(feature::GeomType::Area),
       base::Underlying(feature::GeomType::Line)})
  {
    if (m.count(type) != 0)
      return m[type];
  }

  return {};
}

HierarchyLinesBuilder::HierarchyLinesBuilder(HierarchyLinker::Node::Ptrs && trees)
  : m_trees(std::move(trees))
{
}

void HierarchyLinesBuilder::SetGetMainTypeFunction(GetMainTypeFn const & getMainType)
{
  m_getMainType = getMainType;
}

void HierarchyLinesBuilder::SetGetNameFunction(GetNameFn const & getName) { m_getName = getName; }

void HierarchyLinesBuilder::SetCountry(storage::CountryId const & country)
{
  m_countryName = country;
}

void HierarchyLinesBuilder::SetHierarchyEntryEnricher(
    std::unique_ptr<HierarchyEntryEnricher> && enricher)
{
  m_enricher = std::move(enricher);
}

std::vector<HierarchyEntry> HierarchyLinesBuilder::GetHierarchyLines()
{
  CHECK(m_getName, ());
  CHECK(m_getMainType, ());

  std::vector<HierarchyEntry> lines;
  for (auto const & tree : m_trees)
  {
    tree_node::PreOrderVisit(tree, [&](auto const & node) {
      lines.emplace_back(Transform(node));
    });
  }

  return lines;
}

m2::PointD HierarchyLinesBuilder::GetCenter(HierarchyLinker::Node::Ptr const & node)
{
  auto const & data = node->GetData();
  if (!m_enricher)
    return data.GetCenter();

  auto const optCenter = m_enricher->GetFeatureCenter(data.GetCompositeId());
  return optCenter ? *optCenter : data.GetCenter();
}

HierarchyEntry HierarchyLinesBuilder::Transform(HierarchyLinker::Node::Ptr const & node)
{
  HierarchyEntry line;
  auto const & data = node->GetData();
  line.m_id = data.GetCompositeId();
  auto const parent = node->GetParent();
  if (parent)
    line.m_parentId = parent->GetData().GetCompositeId();

  line.m_country = m_countryName;
  line.m_depth = GetDepth(node);
  line.m_name = m_getName(data.GetName());
  line.m_type = m_getMainType(data.GetTypes());
  line.m_center = GetCenter(node);
  return line;
}

HierarchyLinker::Node::Ptrs BuildHierarchy(std::vector<feature::FeatureBuilder> && fbs,
                                           GetMainTypeFn const & getMainType,
                                           std::shared_ptr<FilterInterface> const & filter)
{
  base::EraseIf(fbs, [&](auto const & fb) { return !filter->IsAccepted(fb); });
  HierarchyLinker::Node::Ptrs places;
  places.reserve(fbs.size());
  base::Transform(fbs, std::back_inserter(places), [](auto const & fb) {
    return tree_node::MakeTreeNode(HierarchyPlace(fb));
  });
  auto nodes = HierarchyLinker(std::move(places)).Link();
  // We leave only the trees.
  base::EraseIf(nodes, [](auto const & node) {
    return node->HasParent();
  });
  return nodes;
}


void AddChildrenTo(HierarchyLinker::Node::Ptrs & trees,
                   std::function<std::vector<HierarchyPlace>(CompositeId const &)> const & fn)
{
  for (auto & tree : trees)
  {
    CHECK(!tree->HasParent(), ());

    tree_node::PostOrderVisit(tree, [&](auto const & n) {
      auto const id = n->GetData().GetCompositeId();
      auto const & places = fn(id);
      for (auto place : places)
      {
        auto const newNode = tree_node::MakeTreeNode(std::move(place));
        tree_node::Link(newNode, n);
      }
    });
  }
}

void FlattenBuildingParts(HierarchyLinker::Node::Ptrs & trees)
{
  for (auto & tree : trees)
  {

    CHECK(!tree->HasParent(), ());

    std::vector<
        std::pair<hierarchy::HierarchyLinker::Node::Ptr, hierarchy::HierarchyLinker::Node::Ptr>>
        buildingPartsTrees;

    static auto const & buildingPartChecker = ftypes::IsBuildingPartChecker::Instance();
    std::function<void(hierarchy::HierarchyLinker::Node::Ptr const &)> visit;
    visit = [&](auto const & n) {
      if (buildingPartChecker(n->GetData().GetTypes()))
      {
        CHECK(n->HasParent(), ());
        auto building = n->GetParent();
        buildingPartsTrees.emplace_back(building, n);
        return;
      }

      CHECK(!buildingPartChecker(n->GetData().GetTypes()), ());
      for (auto const & ch : n->GetChildren())
        visit(ch);
    };

    visit(tree);

    for (auto const & buildingAndParts : buildingPartsTrees)
    {
      Unlink(buildingAndParts.second, buildingAndParts.first);
      tree_node::PostOrderVisit(buildingAndParts.second, [&](auto const & buildingPartNode) {
        CHECK(buildingPartChecker(buildingPartNode->GetData().GetTypes()), ());
        buildingPartNode->RemoveChildren();
        tree_node::Link(buildingPartNode, buildingAndParts.first);
      });
    }
  }
}
}  // namespace hierarchy
}  // namespace generator