osrm-backend/include/engine/plugins/match.hpp

374 lines
15 KiB
C++
Raw Normal View History

#ifndef MATCH_HPP
#define MATCH_HPP
2014-09-23 12:46:14 -04:00
2016-01-02 11:13:44 -05:00
#include "engine/plugins/plugin_base.hpp"
#include "engine/map_matching/bayes_classifier.hpp"
#include "engine/object_encoder.hpp"
#include "engine/search_engine.hpp"
2016-01-04 04:19:25 -05:00
#include "engine/guidance/textual_route_annotation.hpp"
#include "engine/guidance/segment_list.hpp"
#include "engine/api_response_generator.hpp"
2016-01-02 11:13:44 -05:00
#include "engine/routing_algorithms/map_matching.hpp"
#include "util/compute_angle.hpp"
#include "util/integer_range.hpp"
#include "util/json_logger.hpp"
#include "util/json_util.hpp"
#include "util/string_util.hpp"
2014-09-23 12:46:14 -04:00
#include <cstdlib>
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
template <class DataFacadeT> class MapMatchingPlugin : public BasePlugin
{
std::shared_ptr<SearchEngine<DataFacadeT>> search_engine_ptr;
using ClassifierT = BayesClassifier<LaplaceDistribution, LaplaceDistribution, double>;
using TraceClassification = ClassifierT::ClassificationT;
2014-09-23 12:46:14 -04:00
public:
MapMatchingPlugin(DataFacadeT *facade, const int max_locations_map_matching)
: descriptor_string("match"), facade(facade),
2015-03-31 04:15:12 -04:00
max_locations_map_matching(max_locations_map_matching),
// the values where derived from fitting a laplace distribution
// to the values of manually classified traces
2015-03-31 04:15:12 -04:00
classifier(LaplaceDistribution(0.005986, 0.016646),
LaplaceDistribution(0.054385, 0.458432),
0.696774) // valid apriori probability
2014-09-23 12:46:14 -04:00
{
search_engine_ptr = std::make_shared<SearchEngine<DataFacadeT>>(facade);
}
virtual ~MapMatchingPlugin() {}
2014-09-23 12:46:14 -04:00
const std::string GetDescriptor() const final override { return descriptor_string; }
2014-09-23 12:46:14 -04:00
TraceClassification
classify(const float trace_length, const float matched_length, const int removed_points) const
{
2015-09-04 12:23:57 -04:00
(void)removed_points; // unused
const double distance_feature = -std::log(trace_length) + std::log(matched_length);
// matched to the same point
if (!std::isfinite(distance_feature))
{
return std::make_pair(ClassifierT::ClassLabel::NEGATIVE, 1.0);
}
const auto label_with_confidence = classifier.classify(distance_feature);
return label_with_confidence;
}
2015-12-17 10:45:15 -05:00
osrm::matching::CandidateLists getCandidates(
const std::vector<FixedPointCoordinate> &input_coords,
const std::vector<std::pair<const int, const boost::optional<int>>> &input_bearings,
const double gps_precision,
std::vector<double> &sub_trace_lengths)
2014-09-23 12:46:14 -04:00
{
2015-12-17 10:45:15 -05:00
osrm::matching::CandidateLists candidates_lists;
2016-01-07 10:30:54 -05:00
// assuming the gps_precision is the standart-diviation of normal distribution that models
// GPS noise (in this model) this should give us the correct candidate with >0.95
double query_radius = 3 * gps_precision;
2015-12-17 10:45:15 -05:00
double last_distance =
2016-01-04 07:30:03 -05:00
coordinate_calculation::haversineDistance(input_coords[0], input_coords[1]);
2015-02-17 06:22:11 -05:00
sub_trace_lengths.resize(input_coords.size());
sub_trace_lengths[0] = 0;
for (const auto current_coordinate : osrm::irange<std::size_t>(0, input_coords.size()))
2014-09-23 12:46:14 -04:00
{
2015-02-08 18:55:12 -05:00
bool allow_uturn = false;
2014-12-08 17:46:31 -05:00
if (0 < current_coordinate)
{
2016-01-04 07:30:03 -05:00
last_distance = coordinate_calculation::haversineDistance(
2015-12-17 10:45:15 -05:00
input_coords[current_coordinate - 1], input_coords[current_coordinate]);
sub_trace_lengths[current_coordinate] +=
sub_trace_lengths[current_coordinate - 1] + last_distance;
}
if (input_coords.size() - 1 > current_coordinate && 0 < current_coordinate)
{
double turn_angle = ComputeAngle::OfThreeFixedPointCoordinates(
input_coords[current_coordinate - 1], input_coords[current_coordinate],
input_coords[current_coordinate + 1]);
// sharp turns indicate a possible uturn
if (turn_angle <= 90.0 || turn_angle >= 270.0)
{
2015-02-08 18:55:12 -05:00
allow_uturn = true;
}
}
2014-12-08 17:46:31 -05:00
// Use bearing values if supplied, otherwise fallback to 0,180 defaults
auto bearing = input_bearings.size() > 0 ? input_bearings[current_coordinate].first : 0;
2015-12-17 10:45:15 -05:00
auto range = input_bearings.size() > 0
? (input_bearings[current_coordinate].second
? *input_bearings[current_coordinate].second
: 10)
: 180;
auto candidates = facade->NearestPhantomNodesInRange(input_coords[current_coordinate],
query_radius, bearing, range);
if (candidates.size() == 0)
{
2015-12-17 10:45:15 -05:00
break;
}
2015-12-26 03:06:10 -05:00
// sort by forward id, then by reverse id and then by distance
2015-12-17 10:45:15 -05:00
std::sort(
candidates.begin(), candidates.end(),
[](const PhantomNodeWithDistance &lhs, const PhantomNodeWithDistance &rhs)
{
2015-12-09 16:34:22 -05:00
return lhs.phantom_node.forward_node_id < rhs.phantom_node.forward_node_id ||
2015-12-17 10:45:15 -05:00
(lhs.phantom_node.forward_node_id == rhs.phantom_node.forward_node_id &&
(lhs.phantom_node.reverse_node_id < rhs.phantom_node.reverse_node_id ||
(lhs.phantom_node.reverse_node_id ==
rhs.phantom_node.reverse_node_id &&
lhs.distance < rhs.distance)));
});
2015-12-17 10:45:15 -05:00
auto new_end = std::unique(
candidates.begin(), candidates.end(),
[](const PhantomNodeWithDistance &lhs, const PhantomNodeWithDistance &rhs)
{
2015-12-09 16:34:22 -05:00
return lhs.phantom_node.forward_node_id == rhs.phantom_node.forward_node_id &&
lhs.phantom_node.reverse_node_id == rhs.phantom_node.reverse_node_id;
});
candidates.resize(new_end - candidates.begin());
if (!allow_uturn)
2015-02-08 18:55:12 -05:00
{
const auto compact_size = candidates.size();
for (const auto i : osrm::irange<std::size_t>(0, compact_size))
2015-02-08 18:55:12 -05:00
{
// Split edge if it is bidirectional and append reverse direction to end of list
2015-12-09 16:34:22 -05:00
if (candidates[i].phantom_node.forward_node_id != SPECIAL_NODEID &&
candidates[i].phantom_node.reverse_node_id != SPECIAL_NODEID)
2015-02-08 18:55:12 -05:00
{
2015-12-09 16:34:22 -05:00
PhantomNode reverse_node(candidates[i].phantom_node);
2015-02-08 18:55:12 -05:00
reverse_node.forward_node_id = SPECIAL_NODEID;
2015-12-17 10:45:15 -05:00
candidates.push_back(
PhantomNodeWithDistance{reverse_node, candidates[i].distance});
2015-02-08 18:55:12 -05:00
2015-12-09 16:34:22 -05:00
candidates[i].phantom_node.reverse_node_id = SPECIAL_NODEID;
2015-02-08 18:55:12 -05:00
}
}
2014-09-23 12:46:14 -04:00
}
// sort by distance to make pruning effective
std::sort(candidates.begin(), candidates.end(),
2015-12-17 10:45:15 -05:00
[](const PhantomNodeWithDistance &lhs, const PhantomNodeWithDistance &rhs)
{
return lhs.distance < rhs.distance;
});
candidates_lists.push_back(std::move(candidates));
2015-02-08 18:55:12 -05:00
}
2015-12-17 10:45:15 -05:00
return candidates_lists;
2015-02-08 18:55:12 -05:00
}
osrm::json::Object submatchingToJSON(const osrm::matching::SubMatching &sub,
const RouteParameters &route_parameters,
const InternalRouteResult &raw_route)
{
osrm::json::Object subtrace;
2015-03-02 17:12:44 -05:00
if (route_parameters.classify)
{
2015-03-02 17:12:44 -05:00
subtrace.values["confidence"] = sub.confidence;
}
2016-01-04 04:19:25 -05:00
auto response_generator = osrm::engine::MakeApiResponseGenerator(facade);
2015-06-10 05:40:35 -04:00
2016-01-04 04:19:25 -05:00
subtrace.values["hint_data"] = response_generator.BuildHintData(raw_route);
2015-06-10 05:40:35 -04:00
if (route_parameters.geometry || route_parameters.print_instructions)
{
2016-01-04 04:19:25 -05:00
using SegmentList = osrm::engine::guidance::SegmentList<DataFacadeT>;
//Passing false to extract_alternative extracts the route.
const constexpr bool EXTRACT_ROUTE = false;
// by passing false to segment_list, we skip the douglas peucker simplification
// and mark all segments as necessary within the generation process
const constexpr bool NO_ROUTE_SIMPLIFICATION = false;
SegmentList segment_list(raw_route, EXTRACT_ROUTE, route_parameters.zoom_level,
NO_ROUTE_SIMPLIFICATION, facade);
2015-06-10 05:40:35 -04:00
if (route_parameters.geometry)
2015-03-17 18:50:20 -04:00
{
2015-12-17 10:45:15 -05:00
subtrace.values["geometry"] =
2016-01-04 04:19:25 -05:00
response_generator.GetGeometry(route_parameters.compression, segment_list);
2015-03-17 18:50:20 -04:00
}
2015-06-10 05:40:35 -04:00
if (route_parameters.print_instructions)
{
2015-12-17 10:45:15 -05:00
subtrace.values["instructions"] =
2016-01-04 04:19:25 -05:00
osrm::engine::guidance::AnnotateRoute<DataFacadeT>(
segment_list.Get(), facade);
2015-06-10 05:40:35 -04:00
}
osrm::json::Object json_route_summary;
2016-01-04 04:19:25 -05:00
json_route_summary.values["total_distance"] = segment_list.GetDistance();
json_route_summary.values["total_time"] = segment_list.GetDuration();
subtrace.values["route_summary"] = json_route_summary;
}
subtrace.values["indices"] = osrm::json::make_array(sub.indices);
osrm::json::Array points;
for (const auto &node : sub.nodes)
{
points.values.emplace_back(
osrm::json::make_array(node.location.lat / COORDINATE_PRECISION,
node.location.lon / COORDINATE_PRECISION));
}
subtrace.values["matched_points"] = points;
osrm::json::Array names;
for (const auto &node : sub.nodes)
{
2015-12-17 10:45:15 -05:00
names.values.emplace_back(facade->get_name_for_id(node.name_id));
}
subtrace.values["matched_names"] = names;
return subtrace;
}
2015-12-17 10:45:15 -05:00
Status HandleRequest(const RouteParameters &route_parameters,
osrm::json::Object &json_result) final override
2015-02-08 18:55:12 -05:00
{
// enforce maximum number of locations for performance reasons
if (max_locations_map_matching > 0 &&
static_cast<int>(route_parameters.coordinates.size()) > max_locations_map_matching)
{
2015-12-18 12:18:48 -05:00
json_result.values["status_message"] = "Too many coodindates";
2015-12-17 10:45:15 -05:00
return Status::Error;
}
2015-02-08 18:55:12 -05:00
// check number of parameters
if (!check_all_coordinates(route_parameters.coordinates))
{
2015-12-18 12:18:48 -05:00
json_result.values["status_message"] = "Invalid coordinates";
2015-12-17 10:45:15 -05:00
return Status::Error;
2015-02-08 18:55:12 -05:00
}
2015-02-17 06:22:11 -05:00
std::vector<double> sub_trace_lengths;
const auto &input_coords = route_parameters.coordinates;
const auto &input_timestamps = route_parameters.timestamps;
const auto &input_bearings = route_parameters.bearings;
if (input_timestamps.size() > 0 && input_coords.size() != input_timestamps.size())
{
2015-12-17 10:45:15 -05:00
json_result.values["status_message"] =
2015-12-18 12:18:48 -05:00
"Number of timestamps does not match number of coordinates";
2015-12-17 10:45:15 -05:00
return Status::Error;
}
if (input_bearings.size() > 0 && input_coords.size() != input_bearings.size())
{
2015-12-17 10:45:15 -05:00
json_result.values["status_message"] =
2015-12-18 12:18:48 -05:00
"Number of bearings does not match number of coordinates";
2015-12-17 10:45:15 -05:00
return Status::Error;
}
2015-12-26 03:06:10 -05:00
// at least two coordinates are needed for map matching
if (static_cast<int>(input_coords.size()) < 2)
{
2015-12-18 12:18:48 -05:00
json_result.values["status_message"] = "At least two coordinates needed";
2015-12-17 10:45:15 -05:00
return Status::Error;
}
2015-12-17 10:45:15 -05:00
const auto candidates_lists = getCandidates(
input_coords, input_bearings, route_parameters.gps_precision, sub_trace_lengths);
if (candidates_lists.size() != input_coords.size())
2015-02-08 18:55:12 -05:00
{
2015-12-17 10:45:15 -05:00
BOOST_ASSERT(candidates_lists.size() < input_coords.size());
json_result.values["status_message"] =
std::string("Could not find a matching segment for coordinate ") +
std::to_string(candidates_lists.size());
return Status::NoSegment;
2014-09-23 12:46:14 -04:00
}
2015-03-02 17:12:44 -05:00
// setup logging if enabled
if (osrm::json::Logger::get())
osrm::json::Logger::get()->initialize("matching");
2015-03-02 17:12:44 -05:00
// call the actual map matching
osrm::matching::SubMatchingList sub_matchings;
search_engine_ptr->map_matching(candidates_lists, input_coords, input_timestamps,
2015-03-02 17:12:44 -05:00
route_parameters.matching_beta,
route_parameters.gps_precision, sub_matchings);
2015-02-22 17:21:37 -05:00
osrm::json::Array matchings;
for (auto &sub : sub_matchings)
2014-12-08 17:46:31 -05:00
{
2015-02-17 06:22:11 -05:00
// classify result
2015-03-02 17:12:44 -05:00
if (route_parameters.classify)
2015-02-17 06:22:11 -05:00
{
double trace_length =
sub_trace_lengths[sub.indices.back()] - sub_trace_lengths[sub.indices.front()];
TraceClassification classification =
classify(trace_length, sub.length,
(sub.indices.back() - sub.indices.front() + 1) - sub.nodes.size());
2015-03-02 17:12:44 -05:00
if (classification.first == ClassifierT::ClassLabel::POSITIVE)
{
sub.confidence = classification.second;
}
else
{
sub.confidence = 1 - classification.second;
2015-03-02 17:12:44 -05:00
}
2015-02-17 06:22:11 -05:00
}
2014-12-08 17:46:31 -05:00
2015-02-19 18:35:51 -05:00
BOOST_ASSERT(sub.nodes.size() > 1);
// FIXME we only run this to obtain the geometry
// The clean way would be to get this directly from the map matching plugin
2015-02-17 06:22:11 -05:00
InternalRouteResult raw_route;
PhantomNodes current_phantom_node_pair;
for (unsigned i = 0; i < sub.nodes.size() - 1; ++i)
{
current_phantom_node_pair.source_phantom = sub.nodes[i];
current_phantom_node_pair.target_phantom = sub.nodes[i + 1];
2016-01-05 06:41:16 -05:00
BOOST_ASSERT(current_phantom_node_pair.source_phantom.IsValid());
BOOST_ASSERT(current_phantom_node_pair.target_phantom.IsValid());
2015-02-17 06:22:11 -05:00
raw_route.segment_end_coordinates.emplace_back(current_phantom_node_pair);
}
search_engine_ptr->shortest_path(
raw_route.segment_end_coordinates,
std::vector<bool>(raw_route.segment_end_coordinates.size() + 1, true), raw_route);
2015-09-01 18:39:50 -04:00
BOOST_ASSERT(raw_route.shortest_path_length != INVALID_EDGE_WEIGHT);
matchings.values.emplace_back(submatchingToJSON(sub, route_parameters, raw_route));
2015-02-17 06:22:11 -05:00
}
2014-12-08 17:46:31 -05:00
if (osrm::json::Logger::get())
osrm::json::Logger::get()->render("matching", json_result);
2015-02-22 17:21:37 -05:00
json_result.values["matchings"] = matchings;
2014-12-08 17:46:31 -05:00
2015-11-18 16:21:17 -05:00
if (sub_matchings.empty())
{
2015-12-18 12:18:48 -05:00
json_result.values["status_message"] = "Cannot find matchings";
2015-12-17 10:45:15 -05:00
return Status::EmptyResult;
2015-11-18 16:21:17 -05:00
}
2015-12-18 12:18:48 -05:00
json_result.values["status_message"] = "Found matchings";
2015-12-17 10:45:15 -05:00
return Status::Ok;
2014-09-23 12:46:14 -04:00
}
private:
std::string descriptor_string;
DataFacadeT *facade;
int max_locations_map_matching;
ClassifierT classifier;
2014-09-23 12:46:14 -04:00
};
#endif // MATCH_HPP