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

booking_quality_check.cpp « booking_quality_check « generator - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 2699ffeb389cfaef735ae719238887de0033f64f (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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
#include "generator/booking_dataset.hpp"
#include "generator/feature_builder.hpp"
#include "generator/opentable_dataset.hpp"
#include "generator/osm_source.hpp"
#include "generator/sponsored_scoring.hpp"

#include "indexer/classificator_loader.hpp"

#include "geometry/distance_on_sphere.hpp"

#include "coding/file_name_utils.hpp"

#include "base/stl_add.hpp"
#include "base/string_utils.hpp"

#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <memory>
#include <numeric>
#include <random>

#include "3party/gflags/src/gflags/gflags.h"

#include "boost/range/adaptor/map.hpp"
#include "boost/range/algorithm/copy.hpp"


using namespace std;

DEFINE_string(osm, "", "Input .o5m file");
DEFINE_string(booking, "", "Path to booking data in .tsv format");
DEFINE_string(opentable, "", "Path to opentable data in .tsv format");
DEFINE_string(factors, "", "Factors output path");
DEFINE_string(sample, "", "Path so sample file");

DEFINE_uint64(seed, minstd_rand::default_seed, "Seed for random shuffle");
DEFINE_uint64(selection_size, 1000, "Selection size");
DEFINE_bool(generate, false, "Generate unmarked sample");

using namespace generator;

namespace
{
string PrintBuilder(FeatureBuilder1 const & fb)
{
  ostringstream s;

  s << "Id: " << DebugPrint(fb.GetMostGenericOsmId()) << '\t'
    << "Name: " << fb.GetName(StringUtf8Multilang::kDefaultCode) << '\t';

  auto const params = fb.GetParams();
  auto const street = params.GetStreet();
  auto const house = params.house.Get();

  string address = street;
  if (!house.empty())
  {
    if (!street.empty())
      address += ", ";
    address += house;
  }

  if (!address.empty())
    s << "Address: " << address << '\t';

  auto const center = MercatorBounds::ToLatLon(fb.GetKeyPoint());
  s << "lat: " << center.lat << " lon: " << center.lon << '\t';

  if (fb.GetGeomType() == feature::GEOM_POINT)
    s << "GeomType: GEOM_POINT";
  else if (fb.GetGeomType() == feature::GEOM_AREA)
    s << "GeomType: GEOM_AREA";
  else
    CHECK(false, ());

  return s.str();
}

DECLARE_EXCEPTION(ParseError, RootException);

osm::Id ReadDebuggedPrintedOsmId(string const & str)
{
  istringstream sstr(str);
  string type;
  uint64_t id;
  sstr >> type >> id;

  if (sstr.fail())
    MYTHROW(ParseError, ("Can't make osmId from string", str));

  if (type == "relation")
    return osm::Id::Relation(id);
  if (type == "way")
    return osm::Id::Way(id);
  if (type == "node")
    return osm::Id::Node(id);

  MYTHROW(ParseError, ("Can't make osmId from string", str));
}

template <typename Dataset>
class Emitter : public EmitterBase
{
public:
  Emitter(Dataset const & dataset, map<osm::Id, FeatureBuilder1> & features)
    : m_dataset(dataset)
    , m_features(features)
  {
    LOG_SHORT(LINFO, ("OSM data:", FLAGS_osm));
  }

  void operator()(FeatureBuilder1 & fb) override
  {
    if (m_dataset.NecessaryMatchingConditionHolds(fb))
      m_features.emplace(fb.GetMostGenericOsmId(), fb);
  }

  void GetNames(vector<string> & names) const override
  {
    names.clear();
  }

  bool Finish() override
  {
    LOG_SHORT(LINFO, ("Num of tourism elements:", m_features.size()));
    return true;
  }

private:
  Dataset const & m_dataset;
  map<osm::Id, FeatureBuilder1> & m_features;
};

feature::GenerateInfo GetGenerateInfo()
{
  feature::GenerateInfo info;
  info.m_bookingDatafileName = FLAGS_booking;
  info.m_opentableDatafileName = FLAGS_opentable;
  info.m_osmFileName = FLAGS_osm;
  info.SetNodeStorageType("map");
  info.SetOsmFileType("o5m");

  info.m_intermediateDir = my::GetDirectory(FLAGS_factors);

  // Set other info params here.

  return info;
}

template <typename Object>
struct SampleItem
{
  enum MatchStatus {Uninitialized, Yes, No};
  using ObjectId = typename Object::ObjectId;

  SampleItem() = default;

  SampleItem(osm::Id const & osmId, ObjectId const sponsoredId, MatchStatus const match = Uninitialized)
   : m_osmId(osmId)
   , m_sponsoredId(sponsoredId)
   , m_match(match)
  {
  }

  osm::Id m_osmId;
  ObjectId m_sponsoredId = Object::InvalidObjectId();

  MatchStatus m_match = Uninitialized;
};

template <typename Object>
typename SampleItem<Object>::MatchStatus ReadMatchStatus(string const & str)
{
  if (str == "Yes")
    return SampleItem<Object>::Yes;

  if (str == "No")
    return SampleItem<Object>::No;

  if (str == "Uninitialized")
    return SampleItem<Object>::Uninitialized;

  MYTHROW(ParseError, ("Can't make SampleItem::MatchStatus from string:", str));
}

template <typename Object>
SampleItem<Object> ReadSampleItem(string const & str)
{
  SampleItem<Object> item;

  auto const parts = strings::Tokenize(str, "\t");
  CHECK_EQUAL(parts.size(), 3, ("Cant't make SampleItem from string:", str,
                                "due to wrong number of fields."));

  item.m_osmId = ReadDebuggedPrintedOsmId(parts[0]);
  if (!strings::to_uint(parts[1], item.m_sponsoredId.Get()))
    MYTHROW(ParseError, ("Can't make uint32 from string:", parts[1]));
  item.m_match = ReadMatchStatus<Object>(parts[2]);

  return item;
}

template <typename Object>
vector<SampleItem<Object>> ReadSample(istream & ist)
{
  vector<SampleItem<Object>> result;

  size_t lineNumber = 1;
  try
  {
    for (string line; getline(ist, line); ++lineNumber)
    {
      result.emplace_back(ReadSampleItem<Object>(line));
    }
  }
  catch (ParseError const & e)
  {
    LOG_SHORT(LERROR, ("Wrong format: line", lineNumber, e.Msg()));
    exit(1);
  }

  return result;
}

template <typename Object>
vector<SampleItem<Object>> ReadSampleFromFile(string const & name)
{
  ifstream ist(name);
  CHECK(ist.is_open(), ("Can't open file:", name, strerror(errno)));
  return ReadSample<Object>(ist);
}

template <typename Dataset, typename Object = typename Dataset::Object>
void GenerateFactors(Dataset const & dataset,
                     map<osm::Id, FeatureBuilder1> const & features,
                     vector<SampleItem<Object>> const & sampleItems, ostream & ost)
{
  for (auto const & item : sampleItems)
  {
    auto const & object = dataset.GetObjectById(item.m_sponsoredId);
    auto const & feature = features.at(item.m_osmId);

    auto const score = generator::sponsored_scoring::Match(object, feature);

    auto const center = MercatorBounds::ToLatLon(feature.GetKeyPoint());
    double const distanceMeters = ms::DistanceOnEarth(center, object.m_latLon);
    auto const matched = score.IsMatched();

    ost << "# ------------------------------------------" << fixed << setprecision(6)
        << endl;
    ost << (matched ? 'y' : 'n') << " \t" << DebugPrint(feature.GetMostGenericOsmId())
        << "\t " << object.m_id
        << "\tdistance: " << distanceMeters
        << "\tdistance score: " << score.m_linearNormDistanceScore
        << "\tname score: " << score.m_nameSimilarityScore
        << "\tresult score: " << score.GetMatchingScore()
        << endl;
    ost << "# " << PrintBuilder(feature) << endl;
    ost << "# " << object << endl;
    ost << "# URL: https://www.openstreetmap.org/?mlat="
        << object.m_latLon.lat << "&mlon=" << object.m_latLon.lon << "#map=18/"
        << object.m_latLon.lat << "/" << object.m_latLon.lon << endl;
  }
}

enum class DatasetType
{
  Booking,
  Opentable
};

template <typename Dataset, typename Object = typename Dataset::Object>
void GenerateSample(Dataset const & dataset,
                    map<osm::Id, FeatureBuilder1> const & features,
                    ostream & ost)
{
  LOG_SHORT(LINFO, ("Num of elements:", features.size()));
  vector<osm::Id> elementIndexes(features.size());
  boost::copy(features | boost::adaptors::map_keys, begin(elementIndexes));

  // TODO(mgsergio): Try RandomSample (from search:: at the moment of writing).
  shuffle(elementIndexes.begin(), elementIndexes.end(), minstd_rand(static_cast<uint32_t>(FLAGS_seed)));
  if (FLAGS_selection_size < elementIndexes.size())
    elementIndexes.resize(FLAGS_selection_size);

  stringstream outStream;

  for (auto osmId : elementIndexes)
  {
    auto const & fb = features.at(osmId);
    auto const sponsoredIndexes = dataset.GetNearestObjects(
        MercatorBounds::ToLatLon(fb.GetKeyPoint()),
        Dataset::kMaxSelectedElements,
        Dataset::kDistanceLimitInMeters);

    for (auto const sponsoredId : sponsoredIndexes)
    {
      auto const & object = dataset.GetObjectById(sponsoredId);
      auto const score = sponsored_scoring::Match(object, fb);

      auto const center = MercatorBounds::ToLatLon(fb.GetKeyPoint());
      double const distanceMeters = ms::DistanceOnEarth(center, object.m_latLon);
      auto const matched = score.IsMatched();

      outStream << "# ------------------------------------------" << fixed << setprecision(6)
                << endl;
      outStream << (matched ? 'y' : 'n') << " \t" << DebugPrint(osmId) << "\t " << sponsoredId
                << "\tdistance: " << distanceMeters
                << "\tdistance score: " << score.m_linearNormDistanceScore
                << "\tname score: " << score.m_nameSimilarityScore
                << "\tresult score: " << score.GetMatchingScore()
                << endl;
      outStream << "# " << PrintBuilder(fb) << endl;
      outStream << "# " << object << endl;
      outStream << "# URL: https://www.openstreetmap.org/?mlat="
                << object.m_latLon.lat << "&mlon=" << object.m_latLon.lon
                << "#map=18/" << object.m_latLon.lat << "/" << object.m_latLon.lon << endl;
    }
    if (!sponsoredIndexes.empty())
      outStream << endl << endl;
  }

  if (FLAGS_sample.empty())
  {
    cout << outStream.str();
  }
  else
  {
    ofstream file(FLAGS_sample);
    if (file.is_open())
      file << outStream.str();
    else
      LOG_SHORT(LERROR, ("Can't output into", FLAGS_sample, strerror(errno)));
  }
}

template <typename Dataset>
string GetDatasetFilePath(feature::GenerateInfo const & info);

template <>
string GetDatasetFilePath<BookingDataset>(feature::GenerateInfo const & info)
{
  return info.m_bookingDatafileName;
}

template <>
string GetDatasetFilePath<OpentableDataset>(feature::GenerateInfo const & info)
{
  return info.m_opentableDatafileName;
}

template <typename Dataset, typename Object = typename Dataset::Object>
void RunImpl(feature::GenerateInfo & info)
{
  auto const & dataSetFilePath = GetDatasetFilePath<Dataset>(info);
  Dataset dataset(dataSetFilePath);
  LOG_SHORT(LINFO, (dataset.Size(), "objects are loaded from a file:", dataSetFilePath));

  map<osm::Id, FeatureBuilder1> features;
  GenerateFeatures(info, [&dataset, &features](feature::GenerateInfo const & /* info */)
  {
    return my::make_unique<Emitter<Dataset>>(dataset, features);
  });

  if (FLAGS_generate)
  {
    ofstream ost(FLAGS_sample);
    GenerateSample(dataset, features, ost);
  }
  else
  {
    auto const sample = ReadSampleFromFile<Object>(FLAGS_sample);
    LOG_SHORT(LINFO, ("Sample size is", sample.size()));
    ofstream ost(FLAGS_factors);
    CHECK(ost.is_open(), ("Can't open file", FLAGS_factors, strerror(errno)));
    GenerateFactors<Dataset>(dataset, features, sample, ost);
  }
}

void Run(DatasetType const datasetType, feature::GenerateInfo & info)
{
  switch (datasetType)
  {
  case DatasetType::Booking: RunImpl<BookingDataset>(info); break;
  case DatasetType::Opentable: RunImpl<OpentableDataset>(info); break;
  }
}
}  // namespace

int main(int argc, char * argv[])
{
  google::SetUsageMessage("Calculates factors for given samples.");

  if (argc == 1)
  {
    google::ShowUsageWithFlags(argv[0]);
    exit(0);
  }

  google::ParseCommandLineFlags(&argc, &argv, true);

  CHECK(!FLAGS_sample.empty(), ("Please specify sample path."));
  CHECK(!FLAGS_osm.empty(), ("Please specify osm path."));
  CHECK(!FLAGS_booking.empty() ^ !FLAGS_opentable.empty(),
        ("Please specify either booking or opentable path."));
  CHECK(!FLAGS_factors.empty() ^ FLAGS_generate, ("Please either specify factors path"
                                                  "or use -generate."));

  auto const datasetType = FLAGS_booking.empty() ? DatasetType::Opentable : DatasetType::Booking;

  classificator::Load();

  auto info = GetGenerateInfo();
  GenerateIntermediateData(info);

  Run(datasetType, info);

  return 0;
}