Documentation
¶
Index ¶
- Constants
- Variables
- func ExponentialDistribution(beta, x float64) float64
- func LogExponentialDistribution(beta, x float64) float64
- func LogExponentialDistributionUnnormalized(beta, x float64) float64
- func LogNormalDistribution(sigma, x float64) float64
- func LogNormalDistributionUnnormalized(sigma, x float64) float64
- func NormalDistribution(sigma, x float64) float64
- func ResolveRadius(radius *float64, defaultValue float64) float64
- func WithEdges(edges []*spatial.Edge) func(*MapEngine)
- func WithGPSAccuracy(accuracy float64) func(*GPSMeasurement)
- func WithGPSTime(t time.Time) func(*GPSMeasurement)
- func WithGraph(graph ch.Graph) func(*MapEngine)
- func WithHmmParameters(params *HmmProbabilities) func(*MapMatcher)
- func WithMapEngine(engine *MapEngine) func(*MapMatcher)
- func WithS2Storage(storage *spatial.S2Storage) func(*MapEngine)
- func WithStorage(storage spatial.Storage) func(*MapEngine)
- func WithVertices(vertices []*spatial.Vertex) func(*MapEngine)
- type CandidateLayer
- type EdgeResult
- type GPSMeasurement
- type GPSMeasurements
- type GPSTrack
- type HmmProbabilities
- func (hp *HmmProbabilities) EmissionLogProbability(value float64) float64
- func (hp *HmmProbabilities) EmissionProbability(value float64) float64
- func (hp *HmmProbabilities) TransitionLogProbability(routeLength, linearDistance, timeDiff float64) (float64, error)
- func (hp *HmmProbabilities) TransitionProbability(routeLength, linearDistance, timeDiff float64) (float64, error)
- type Isochrone
- type IsochronesResult
- type MapEngine
- type MapMatcher
- func (matcher *MapMatcher) FindIsochrones(source *GPSMeasurement, maxCost float64, maxNearestRadius float64) (IsochronesResult, error)
- func (matcher *MapMatcher) FindShortestPath(source, target *GPSMeasurement, statesRadiusMeters float64) (MatcherResult, error)
- func (matcher *MapMatcher) PrepareViterbi(obsStates []*CandidateLayer, routeLengths map[int]map[int]float64, ...) (*viterbi.Viterbi, error)
- func (matcher *MapMatcher) Run(gpsMeasurements []*GPSMeasurement, statesRadiusMeters float64, maxStates int) (MatcherResult, error)
- type MatcherCode
- type MatcherResult
- type ObservationResult
- type RoadPosition
- type RoadPositions
- type Segment
- type StrongComponentsResult
- type SubMatch
- type WeakComponentsResult
Constants ¶
const ( ViterbiDebug = false ROUTE_LENGTH_THRESHOLD = 9_999_999_999.0 )
const ( // Default search radius for map matching DEFAULT_STATE_RADIUS = 50.0 // Default search radius for shortest path (more permissive) DEFAULT_SP_RADIUS = 100.0 )
Default radius values (in meters)
const (
// Default number of candidates to consider when searching for a path
DEFAULT_CANDIDATES_LIMIT = 10
)
const SMALL_COMPONENT_SIZE = 1000
SMALL_COMPONENT_SIZE - components with fewer vertices are considered to be very small and deprioritized during routing.
Variables ¶
var ( ErrMinumimGPSMeasurements = fmt.Errorf("number of gps measurements need to be 3 atleast") ErrCandidatesNotFound = fmt.Errorf("there is no a single GPS point having candidates") ErrTimeDifference = fmt.Errorf("time difference between subsequent location measurements must be >= 0") ErrSourceNotFound = fmt.Errorf("can't find closest edge for 'source' point") ErrSourceHasMoreEdges = fmt.Errorf("more than 1 edge for 'source' point") ErrTargetNotFound = fmt.Errorf("can't find closest edge for 'target' point") ErrTargetHasMoreEdges = fmt.Errorf("more than 1 edge for 'target' point") ErrPathNotFound = fmt.Errorf("path not found") ErrSameVertex = fmt.Errorf("same vertex") ErrDifferentComponents = fmt.Errorf("vertices are in different connected components") )
Functions ¶
func ExponentialDistribution ¶
ExponentialDistribution computes (1/beta) * exp(-x/beta), where beta = 1/lambda
func LogExponentialDistribution ¶
LogExponentialDistribution computes log of exponential distribution PDF (normalized) log(f(x)) = log(1/beta) - x/beta Note: Can return positive values when beta < 1 (valid for PDFs)
func LogExponentialDistributionUnnormalized ¶ added in v0.8.0
LogExponentialDistributionUnnormalized computes unnormalized log of exponential distribution PDF For Viterbi/HMM we only need relative probabilities, so we drop constant terms log(f(x)) ~ -x/beta Reference: GraphHopper/OSRM implementations Always returns values <= 0
func LogNormalDistribution ¶
LogNormalDistribution computes log of normal distribution PDF (normalized) log(f(x)) = log(1/(sigma*sqrt(2*pi))) - 0.5*(x/sigma)^2 Note: Can return positive values when density > 1 (valid for PDFs)
func LogNormalDistributionUnnormalized ¶ added in v0.8.0
LogNormalDistributionUnnormalized computes unnormalized log of normal distribution PDF For Viterbi/HMM we only need relative probabilities, so we drop constant terms log(f(x)) ~ -0.5*(x/sigma)^2 Reference: GraphHopper/OSRM implementations Always returns values <= 0
func NormalDistribution ¶
NormalDistribution https://en.wikipedia.org/wiki/Normal_distribution
func ResolveRadius ¶ added in v0.11.0
ResolveRadius resolves the radius value based on the API design:
- < 0: no limit (returns -1 to signal unlimited search)
- 0 or nil: use default
- > 0: use provided value
func WithEdges ¶ added in v0.8.0
WithEdges is an option which sets edges for MapEngine and populate existing spatial index This option requires that storage is already set in MapEngine which you can do via WithStorage option If storage is nil then edges are just set without populating spatial index!!!
func WithGPSAccuracy ¶ added in v0.8.0
func WithGPSAccuracy(accuracy float64) func(*GPSMeasurement)
WithGPSAccuracy sets user defined accuracy for GPS measurement in meters Value of <=0 means use default sigma from HmmProbabilities
func WithGPSTime ¶ added in v0.6.0
func WithGPSTime(t time.Time) func(*GPSMeasurement)
WithGPSTime sets user defined time for GPS measurement
func WithHmmParameters ¶ added in v0.8.0
func WithHmmParameters(params *HmmProbabilities) func(*MapMatcher)
WithHmmParameters sets the HMM parameters for the matcher
func WithMapEngine ¶ added in v0.8.0
func WithMapEngine(engine *MapEngine) func(*MapMatcher)
WithMapEngine sets the map engine for the matcher
func WithS2Storage ¶ added in v0.8.0
WithS2Storage is an option which sets s2Storage for MapEngine (backward compatibility) Deprecated: Use WithStorage instead
func WithStorage ¶ added in v0.8.1
WithStorage is an option which sets storage for MapEngine
func WithVertices ¶ added in v0.8.0
WithVertices is an option which sets vertices for MapEngine
Types ¶
type CandidateLayer ¶
type CandidateLayer struct {
Observation *GPSMeasurement
States RoadPositions
EmissionLogProbabilities []emission
TransitionLogProbabilities []transition
}
CandidateLayer Wrapper around Observation
Observation - observation itself States - set of projections on road network EmissionLogProbabilities - emission probabilities between Observation and corresponding States TransitionLogProbabilities - transition probabilities between States
func NewCandidateLayer ¶
func NewCandidateLayer(observation *GPSMeasurement, states RoadPositions) *CandidateLayer
NewCandidateLayer Returns pointer to created CandidateLayer
func (*CandidateLayer) AddEmissionProbability ¶
func (ts *CandidateLayer) AddEmissionProbability(candidate *RoadPosition, emissionLogProbability float64)
AddEmissionProbability Append emission probability to slice of emission probablities
func (*CandidateLayer) AddTransitionProbability ¶
func (ts *CandidateLayer) AddTransitionProbability(fromPosition, toPosition *RoadPosition, transitionLogProbability float64)
AddTransitionProbability Append transition probability to slice of transition probablities
type EdgeResult ¶ added in v0.6.0
type GPSMeasurement ¶
GPSMeasurement Representation of telematic data
id - unique identifier dateTime - timestamp GeoPoint - latitude(Y)/longitude(X), pointer to GeoPoint (wrapper) accuracy - GPS measurement accuracy in meters (<=0 means use default sigma)
func NewGPSMeasurement ¶
func NewGPSMeasurement(id int, lon, lat float64, srid int, options ...func(*GPSMeasurement)) *GPSMeasurement
NewGPSMeasurement Returns pointer to created GPSMeasurement
id - unique identifier lon - longitude (X for SRID = 0) lat - latitude (Y for SRID = 0) srid - SRID (see https://en.wikipedia.org/wiki/Spatial_reference_system), if not provided then SRID(4326) is used. 0 and 4326 are supported.
func NewGPSMeasurementFromID ¶
func NewGPSMeasurementFromID(id int, lon, lat float64, srid ...int) *GPSMeasurement
NewGPSMeasurementFromID Returns pointer to created GPSMeasurement
id - unique identifier (will be converted to time.Time also) lon - longitude (X for SRID = 0) lat - latitude (Y for SRID = 0) srid - SRID (see https://en.wikipedia.org/wiki/Spatial_reference_system), if not provided then SRID(4326) is used. 0 and 4326 are supported.
func (*GPSMeasurement) Accuracy ¶ added in v0.8.0
func (gps *GPSMeasurement) Accuracy() float64
Accuracy Returns GPS measurement accuracy in meters (0 means use default sigma)
func (*GPSMeasurement) ID ¶
func (gps *GPSMeasurement) ID() int
ID Returns generated identifier for GPS-point
func (*GPSMeasurement) TM ¶ added in v0.2.4
func (gps *GPSMeasurement) TM() time.Time
TM Returns generated (or provided) timestamp for GPS-point
type HmmProbabilities ¶
type HmmProbabilities struct {
// contains filtered or unexported fields
}
HmmProbabilities Parameters used in evaluating of Normal Distribution and Exponentional Distribution
func HmmProbabilitiesDefault ¶
func HmmProbabilitiesDefault() *HmmProbabilities
HmmProbabilitiesDefault Constructor for creating HmmProbabilities with default values Sigma - standard deviation of the normal distribution [m] used for modeling the GPS error Beta - beta parameter of the exponential distribution used for modeling transition probabilities
func NewHmmProbabilities ¶
func NewHmmProbabilities(sigma, beta float64) *HmmProbabilities
NewHmmProbabilities Constructor for creating HmmProbabilities with provided values
func (*HmmProbabilities) EmissionLogProbability ¶
func (hp *HmmProbabilities) EmissionLogProbability(value float64) float64
EmissionLogProbability Evaluate emission probability (log-normal distribution is used)
func (*HmmProbabilities) EmissionProbability ¶
func (hp *HmmProbabilities) EmissionProbability(value float64) float64
EmissionProbability Evaluate emission probability (normal distribution is used). Absolute distance [m] between GPS measurement and map matching candidate.
func (*HmmProbabilities) TransitionLogProbability ¶
func (hp *HmmProbabilities) TransitionLogProbability(routeLength, linearDistance, timeDiff float64) (float64, error)
TransitionLogProbability Evaluate transition probability (log-exponential distribution is used)
func (*HmmProbabilities) TransitionProbability ¶
func (hp *HmmProbabilities) TransitionProbability(routeLength, linearDistance, timeDiff float64) (float64, error)
TransitionProbability Evaluate transition probability (exponential distribution is used)
type IsochronesResult ¶ added in v0.5.0
type IsochronesResult []*Isochrone
IsochronesResult Representation of isochrones algorithm's output
type MapEngine ¶
type MapEngine struct {
// contains filtered or unexported fields
}
MapEngine Engine for solving finding shortest path and KNN problems edges - set of edges (map[from_vertex]map[to_vertex]Edge) storage - spatial storage for solving KNN problem (implements spatial.Storage interface) vertices - datastore for graph vertices (with geometry property) graph - Graph(E,V). It wraps ch.Graph (see https://github.com/LdDl/ch/blob/master/graph.go#L17). It used for solving finding shortest path problem. queryPool - thread-safe query pool for concurrent shortest path queries (ch v1.10.0+) vertexComponent - matches vertex ID to its weakly connected component ID bigComponentID - ID of the largest weakly connected component. -1 if no components found
func NewMapEngine ¶
NewMapEngine Returns pointer to created MapEngine with provided parameters
func NewMapEngineDefault ¶
func NewMapEngineDefault() *MapEngine
NewMapEngineDefault Returns pointer to created MapEngine with default parameters
type MapMatcher ¶
type MapMatcher struct {
// contains filtered or unexported fields
}
MapMatcher Engine for solving map matching problem
hmmParams - parameters of Hidden Markov Model engine - wrapper around MapEngine (for KNN and finding shortest path problems) viterbiSemaphore - limits concurrent Viterbi computations globally
func NewMapMatcher ¶
func NewMapMatcher(ops ...func(*MapMatcher)) *MapMatcher
NewMapMatcher returns pointer to created MapMatcher with provided options
func NewMapMatcherDefault ¶
func NewMapMatcherDefault() *MapMatcher
NewMapMatcherDefault Returns pointer to created MapMatcher with default parameters
func NewMapMatcherFromFiles ¶ added in v0.8.0
func NewMapMatcherFromFiles(props *HmmProbabilities, edgesFilename string) (*MapMatcher, error)
NewMapMatcherFromFiles Returns pointer to created MapMatcher from CSV files
props - parameters of Hidden Markov Model
edgesFilename - path to the edges CSV file (e.g., "graph.csv")
This function expects three CSV files with the same prefix:
- {prefix}.csv - edges file (required)
Format: from_vertex_id;to_vertex_id;weight;geom;was_one_way;edge_id
geom is GeoJSON LineString
- {prefix}_vertices.csv - vertices file (required)
Format: vertex_id;order_pos;importance;geom
geom is GeoJSON Point
order_pos and importance are used for contraction hierarchies
- {prefix}_shortcuts.csv - shortcuts file (required, can be empty with header only)
Format: from_vertex_id;to_vertex_id;weight;via_vertex_id
These are precomputed contraction hierarchy shortcuts.
If empty, shortcuts will be computed via PrepareContractionHierarchies()
Example: if edgesFilename is "./data/roads.csv", it will look for:
- ./data/roads.csv
- ./data/roads_vertices.csv
- ./data/roads_shortcuts.csv
func (*MapMatcher) FindIsochrones ¶ added in v0.5.0
func (matcher *MapMatcher) FindIsochrones(source *GPSMeasurement, maxCost float64, maxNearestRadius float64) (IsochronesResult, error)
FindIsochrones Find shortest path between two obserations (not necessary GPS points).
NOTICE: this function snaps point to only one nearest vertex (without multiple candidates for provided point) source - source for outcoming isochrones maxCost - max cost restriction for single isochrone line maxNearestRadius - max radius of search for nearest vertex
func (*MapMatcher) FindShortestPath ¶ added in v0.3.0
func (matcher *MapMatcher) FindShortestPath(source, target *GPSMeasurement, statesRadiusMeters float64) (MatcherResult, error)
FindShortestPath finds shortest path between two observations (not necessary GPS points). It searches for multiple candidates and selects the best pair that are in the same connected component. Priority is given to candidates in the big (main) component.
Parameters:
- source, target: GPS measurements to route between
- statesRadiusMeters: maximum radius to search nearest edges (use -1 for unlimited)
func (*MapMatcher) PrepareViterbi ¶
func (matcher *MapMatcher) PrepareViterbi(obsStates []*CandidateLayer, routeLengths map[int]map[int]float64, gpsMeasurements []*GPSMeasurement) (*viterbi.Viterbi, error)
PrepareViterbi Prepares engine for doing Viterbi's algorithm (see https://github.com/LdDl/viterbi/blob/master/viterbi.go#L25)
states - set of States gpsMeasurements - set of Observations
func (*MapMatcher) Run ¶
func (matcher *MapMatcher) Run(gpsMeasurements []*GPSMeasurement, statesRadiusMeters float64, maxStates int) (MatcherResult, error)
Run Do magic
gpsMeasurements - Observations statesRadiusMeters - maximum radius to search nearest polylines maxStates - maximum of corresponding states
type MatcherCode ¶ added in v0.11.1
type MatcherCode uint32
const ( // Everything is fine CODE_OK MatcherCode = iota + 900 // Simply no candidates CODE_NO_CANDIDATES // Observation is alone (no route to previous or next observation) CODE_ALONE_OBSERVATION )
type MatcherResult ¶
type MatcherResult struct {
SubMatches []SubMatch
}
MatcherResult Representation of map matching algorithm's output
SubMatches - set of SubMatch segments (split when route cannot be computed between consecutive points)
type ObservationResult ¶
type ObservationResult struct {
Observation *GPSMeasurement
IsMatched bool
Code MatcherCode
MatchedEdge spatial.Edge
MatchedVertex spatial.Vertex
ProjectedPoint s2.Point
ProjectionPointIdx int
NextEdges []EdgeResult
}
ObservationResult Representation of gps measurement matched to G(v,e)
Observation - gps measurement itself IsMatched - true if observation was successfully matched to a road, false if no candidates were found Code - matcher code providing additional info about matching result. See MatcherCode constants (enum workaround) for details MatchedEdge - edge in G(v,e) corresponding to current gps measurement (empty if IsMatched is false) MatchedVertex - stands for closest vertex to the observation (empty if IsMatched is false) ProjectedPoint - projection onto the matched edge (empty if IsMatched is false) ProjectedPointIdx - index of the point in polyline which follows projection point NextEdges - set of leading edges up to next observation. Could be an empty array if observations are very close to each other or if it just last observation
type RoadPosition ¶
type RoadPosition struct {
Projected *spatial.GeoPoint
GraphEdge *spatial.Edge
PickedGraphVertex int64
RoutingGraphVertex int64
RoadPositionID int
// contains filtered or unexported fields
}
RoadPosition Representation of state (in terms of Hidden Markov Model)
ID - unique identifier of state GraphEdge - pointer to closest edge in graph GraphVertex - indentifier of closest vertex Projected - point (Observation) project onto edge, pointer to GeoPoint beforeProjection - distance from starting point to projected one afterProjection - distance from projected point to last one next - index of the next vertex in s2.Polyline after the projected point
func NewRoadPositionFromLonLat ¶
func NewRoadPositionFromLonLat(stateID int, pickedGraphVertex, routingGraphVertex int64, e *spatial.Edge, lon, lat float64, srid ...int) *RoadPosition
NewRoadPositionFromLonLat Returns pointer to created State
stateID - unique identifier for state pickedGraphVertex - indentifier of vertex which is closest to Observation routingGraphVertex - indentifier of vertex which will be used in routing (initially it should match pickedGraphVertex in most cases) e - pointer to Edge lon - longitude (X for SRID = 0) lat - latitude (Y for SRID = 0) srid - SRID (see https://en.wikipedia.org/wiki/Spatial_reference_system)
func NewRoadPositionFromS2LatLng ¶
func NewRoadPositionFromS2LatLng(stateID int, pickedGraphVertex, routingGraphVertex int64, e *spatial.Edge, latLng *s2.LatLng, srid ...int) *RoadPosition
NewRoadPositionFromS2LatLng Returns pointer to created State
stateID - unique identifier for state pickedGraphVertex - indentifier of vertex which is closest to Observation routingGraphVertex - indentifier of vertex which will be used in routing (initially it should match pickedGraphVertex in most cases) e - pointer to Edge lon - longitude (X for SRID = 0) lat - latitude (Y for SRID = 0) srid - SRID (see https://en.wikipedia.org/wiki/Spatial_reference_system)
func (RoadPosition) ID ¶
func (state RoadPosition) ID() int
ID Method to fit interface State (see https://github.com/LdDl/viterbi/blob/master/viterbi.go#L9)
func (RoadPosition) String ¶
func (state RoadPosition) String() string
String Pretty format for State
type Segment ¶ added in v0.8.0
type Segment struct {
// contains filtered or unexported fields
}
Segment represents a continuous matched segment to process separately (split at break points)
type StrongComponentsResult ¶ added in v0.11.0
type StrongComponentsResult struct {
// matches each vertex ID to its SCC component ID
VertexComponent map[int64]int64
// ID of the largest component (-1 if no components found)
BigComponentID int64
// matches component ID to number of vertices in that component
ComponentSizes map[int64]int
// marks whether a component is really small
IsComponentVerySmall map[int64]bool
// overall number of components found
TotalComponents int64
}
StrongComponentsResult holds the result of strongly connected components evaluation.
type SubMatch ¶ added in v0.8.0
type SubMatch struct {
Observations []ObservationResult
Probability float64
}
SubMatch Representation of a single continuous matched segment
Observations - set of ObservationResult for this segment Probability - probability got from Viterbi's algorithm for this segment
type WeakComponentsResult ¶ added in v0.11.0
type WeakComponentsResult struct {
// matches each vertex ID to its component ID
VertexComponent map[int64]int64
// ID of the largest component
// Will be -1 if no components found
BigComponentID int64
// matches component ID to number of vertices in that component
ComponentSizes map[int64]int
// overall number of components found
TotalComponents int64
}
WeakComponentsResult holds the result of weakly connected components evaluation.

