< Summary

Class:Itinero.Routing.IRouterExtensions
Assembly:Itinero
File(s):/home/runner/work/routing2/routing2/src/Itinero/Routing/IRouterExtensions.cs
Covered lines:115
Uncovered lines:55
Coverable lines:170
Total lines:300
Line coverage:67.6% (115 of 170)
Covered branches:28
Total branches:48
Branch coverage:58.3% (28 of 48)
Tag:284_38118444584

Metrics

MethodBranch coverage Cyclomatic complexity Line coverage
From(...)100%1100%
From(...)100%1100%
From(...)100%10%
From(...)100%10%
From(...)100%10%
From(...)100%10%
CalculateAsync()90%10100%
<CalculateAsync()50%257.14%
CalculateAsync()80%1092.1%
<CalculateAsync()50%257.14%
BuildHeuristic(...)100%2100%
BuildHeuristic(...)10%1016%

File(s)

/home/runner/work/routing2/routing2/src/Itinero/Routing/IRouterExtensions.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Threading;
 4using System.Threading.Tasks;
 5using Itinero.Geo;
 6using Itinero.Geo.Directions;
 7using Itinero.Network;
 8using Itinero.Profiles;
 9using Itinero.Routes.Paths;
 10using Itinero.Routing.Alternatives;
 11using Itinero.Routing.Costs;
 12using Itinero.Routing.Flavours.Dijkstra;
 13using Itinero.Snapping;
 14
 15namespace Itinero.Routing;
 16
 17/// <summary>
 18///     Contains extensions for the IRouter interface.
 19/// </summary>
 20public static class IRouterExtensions
 21{
 22    /// <summary>
 23    ///     Configures the router to route from the given point.
 24    /// </summary>
 25    /// <param name="router">The router.</param>
 26    /// <param name="snapPoint">The point to route from.</param>
 27    /// <returns>A configured router.</returns>
 28    public static IHasSource From(this IRouter router, SnapPoint snapPoint)
 1161829    {
 1161830        return router.From((snapPoint, (bool?)null));
 1161831    }
 32
 33    /// <summary>
 34    ///     Configures the router to route from the given point.
 35    /// </summary>
 36    /// <param name="router">The router.</param>
 37    /// <param name="directedSnapPoint">The point to route from.</param>
 38    /// <returns>A configured router.</returns>
 39    public static IHasSource From(this IRouter router, (SnapPoint snapPoint, bool? direction) directedSnapPoint)
 1161940    {
 1161941        return new Router(router.Network, router.Settings)
 1161942        {
 1161943            Source = directedSnapPoint
 1161944        };
 1161945    }
 46
 47    /// <summary>
 48    ///     Configures the router to route from the given point.
 49    /// </summary>
 50    /// <param name="router">The router.</param>
 51    /// <param name="directedSnapPoint">The point to route from.</param>
 52    /// <returns>A configured router.</returns>
 53    public static IHasSource From(this IRouter router,
 54        (SnapPoint snapPoint, DirectionEnum? direction) directedSnapPoint)
 055    {
 056        return router.From(directedSnapPoint.ToDirected(router.Network));
 057    }
 58
 59    /// <summary>
 60    ///     Configures the router to route from the given point.
 61    /// </summary>
 62    /// <param name="router">The router.</param>
 63    /// <param name="snapPoints">The points to route from.</param>
 64    /// <returns>A configured router.</returns>
 65    public static IHasSources From(this IRouter router, IReadOnlyList<SnapPoint> snapPoints)
 066    {
 067        return router.From(snapPoints.ToDirected());
 068    }
 69
 70    /// <summary>
 71    ///     Configures the router to route from the given point.
 72    /// </summary>
 73    /// <param name="router">The router.</param>
 74    /// <param name="directedSnapPoints">The points to route from.</param>
 75    /// <returns>A configured router.</returns>
 76    public static IHasSources From(this IRouter router,
 77        IReadOnlyList<(SnapPoint snapPoint, DirectionEnum? direction)> directedSnapPoints)
 078    {
 079        return router.From(directedSnapPoints.ToDirected(router.Network));
 080    }
 81
 82    /// <summary>
 83    ///     Configures the router to route from the given point.
 84    /// </summary>
 85    /// <param name="router">The router.</param>
 86    /// <param name="directedSnapPoints">The points to route from.</param>
 87    /// <returns>A configured router.</returns>
 88    public static IHasSources From(this IRouter router,
 89        IReadOnlyList<(SnapPoint snapPoint, bool? direction)> directedSnapPoints)
 090    {
 091        return new Router(router.Network, router.Settings)
 092        {
 093            Sources = directedSnapPoints
 094        };
 095    }
 96
 97    internal static async Task<IReadOnlyList<IReadOnlyList<Result<Path>>>> CalculateAsync(this IRouter manyToManyRouter,
 98        IReadOnlyList<SnapPoint> sources, IReadOnlyList<SnapPoint> targets, CancellationToken cancellationToken)
 1154299    {
 11542100        var settings = manyToManyRouter.Settings;
 11542101        var routingNetwork = manyToManyRouter.Network;
 102
 11542103        var profile = settings.Profile;
 11542104        var costFunction = routingNetwork.GetCostFunctionFor(profile);
 11542105        if (settings.CostFunctionWrapper != null) costFunction = settings.CostFunctionWrapper(costFunction);
 106
 11542107        var maxBox = settings.MaxBoxFor(routingNetwork, sources);
 108
 109        bool CheckMaxDistance(VertexId v)
 304245110        {
 304245111            if (maxBox == null)
 4112            {
 4113                return false;
 114            }
 115
 304241116            if (routingNetwork == null)
 0117            {
 0118                throw new Exception("Router cannot be null here.");
 119            }
 120
 304241121            var vertex = routingNetwork.GetVertex(v);
 304241122            if (!maxBox.Value.Overlaps(vertex))
 51273123            {
 51273124                return true;
 125            }
 126
 252968127            return false;
 304245128        }
 129
 11542130        var heuristic = BuildHeuristic(routingNetwork, profile, targets);
 11542131        var isMainN = routingNetwork.GetIsMainNFunc(profile);
 11542132        var results = new IReadOnlyList<Result<Path>>[sources.Count];
 46168133        for (var s = 0; s < sources.Count; s++)
 11542134        {
 11542135            var source = sources[s];
 11542136            var search = Flavours.Dijkstra.SearchPool<Flavours.Dijkstra.Dijkstra>.Rent();
 137            (Path? path, double cost)[] pathsAndCosts;
 138            try
 11542139            {
 11542140                pathsAndCosts = await search.RunAsync(routingNetwork, source, targets,
 11542141                    costFunction.GetDijkstraWeightFunc(),
 11542142                    async v =>
 304245143                    {
 304245144                        if (!routingNetwork.UsageNotifier.IsVertexDataReady(routingNetwork, v.vertexId))
 0145                        {
 0146                            await routingNetwork.UsageNotifier.NotifyVertex(routingNetwork, v.vertexId, cancellationToke
 0147                        }
 304245148                        return CheckMaxDistance(v.vertexId);
 315787149                    }, isMainN: isMainN, heuristic: heuristic);
 11542150            }
 151            finally
 11542152            {
 11542153                Flavours.Dijkstra.SearchPool<Flavours.Dijkstra.Dijkstra>.Return(search);
 11542154            }
 155
 11542156            var sourceResults = new Result<Path>[pathsAndCosts.Length];
 402636157            for (var r = 0; r < sourceResults.Length; r++)
 189776158            {
 189776159                var (path, _) = pathsAndCosts[r];
 189776160                if (path == null)
 59484161                {
 59484162                    sourceResults[r] = new Result<Path>("Path not found!");
 59484163                }
 164                else
 130292165                {
 130292166                    sourceResults[r] = path;
 130292167                }
 189776168            }
 169
 11542170            results[s] = sourceResults;
 11542171        }
 172
 11542173        return results;
 11542174    }
 175
 176    internal static async Task<IReadOnlyList<IReadOnlyList<Result<Path>>>> CalculateAsync(this IRouter manyToManyRouter,
 177        IReadOnlyList<(SnapPoint snapPoint, bool? direction)> sources,
 178        IReadOnlyList<(SnapPoint snapPoint, bool? direction)> targets)
 5179    {
 5180        var settings = manyToManyRouter.Settings;
 5181        var routerDb = manyToManyRouter.Network;
 182
 5183        var profile = settings.Profile;
 5184        var costFunction = routerDb.GetCostFunctionFor(profile);
 5185        if (settings.CostFunctionWrapper != null) costFunction = settings.CostFunctionWrapper(costFunction);
 186
 5187        var maxBox = settings.MaxBoxFor(routerDb, sources);
 188
 189        bool CheckMaxDistance(VertexId v)
 12190        {
 12191            if (maxBox == null)
 12192            {
 12193                return false;
 194            }
 195
 0196            if (routerDb == null)
 0197            {
 0198                throw new Exception("Router cannot be null here.");
 199            }
 200
 0201            var vertex = routerDb.GetVertex(v);
 0202            if (!maxBox.Value.Overlaps(vertex))
 0203            {
 0204                return true;
 205            }
 206
 0207            return false;
 12208        }
 209
 5210        var heuristic = BuildHeuristic(routerDb, profile, targets);
 5211        var isMainN = routerDb.GetIsMainNFunc(profile);
 5212        var results = new IReadOnlyList<Result<Path>>[sources.Count];
 20213        for (var s = 0; s < sources.Count; s++)
 5214        {
 5215            var source = sources[s];
 5216            var search = Flavours.Dijkstra.SearchPool<Flavours.Dijkstra.Dijkstra>.Rent();
 217            (Path? path, double cost)[] paths;
 218            try
 5219            {
 5220                paths = await search.RunAsync(routerDb, source, targets,
 5221                    costFunction.GetDijkstraWeightFunc(),
 5222                    async e =>
 12223                    {
 12224                        if (!routerDb.UsageNotifier.IsVertexDataReady(routerDb, e.vertexId))
 0225                        {
 0226                            await routerDb.UsageNotifier.NotifyVertex(routerDb, e.vertexId);
 0227                        }
 12228                        return CheckMaxDistance(e.vertexId);
 17229                    }, isMainN: isMainN, heuristic: heuristic);
 5230            }
 231            finally
 5232            {
 5233                Flavours.Dijkstra.SearchPool<Flavours.Dijkstra.Dijkstra>.Return(search);
 5234            }
 235
 5236            var sourceResults = new Result<Path>[paths.Length];
 20237            for (var r = 0; r < sourceResults.Length; r++)
 5238            {
 5239                var (path, _) = paths[r];
 5240                if (path == null)
 5241                {
 5242                    sourceResults[r] = new Result<Path>("Routes not found!");
 5243                }
 244                else
 0245                {
 0246                    sourceResults[r] = path;
 0247                }
 5248            }
 249
 5250            results[s] = sourceResults;
 5251        }
 252
 5253        return results;
 5254    }
 255
 256    /// <summary>
 257    /// Builds the A* estimate — straight-line distance to the nearest target ×
 258    /// <see cref="Profile.MinFactor"/>, in centimetres — or null when the profile
 259    /// declares no bound and the search should stay plain Dijkstra.
 260    /// </summary>
 261    private static HeuristicFunc? BuildHeuristic(RoutingNetwork network, Profile profile,
 262        IReadOnlyList<(SnapPoint snapPoint, bool? direction)> targets)
 5263    {
 5264        var points = new SnapPoint[targets.Count];
 25265        for (var i = 0; i < targets.Count; i++) points[i] = targets[i].snapPoint;
 266
 5267        return BuildHeuristic(network, profile, points);
 5268    }
 269
 270    private static HeuristicFunc? BuildHeuristic(RoutingNetwork network, Profile profile,
 271        IReadOnlyList<SnapPoint> targets)
 11547272    {
 11547273        var minFactor = profile.MinFactor;
 23094274        if (minFactor == 0) return null;
 0275        if (targets.Count == 0) return null;
 276
 0277        var targetLocations = new (double longitude, double latitude, float? e)[targets.Count];
 0278        for (var t = 0; t < targets.Count; t++)
 0279        {
 0280            targetLocations[t] = targets[t].LocationOnNetwork(network);
 0281        }
 282
 0283        return (longitude, latitude) =>
 0284        {
 0285            var from = (longitude, latitude, (float?)null);
 0286
 0287            var nearest = double.MaxValue;
 0288            foreach (var target in targetLocations)
 0289            {
 0290                var distance = from.DistanceEstimateInMeter(target);
 0291                if (distance < nearest) nearest = distance;
 0292            }
 0293
 0294            // 1% margin: DistanceEstimateInMeter is equirectangular and can slightly
 0295            // overestimate east-west, which would make the bound inadmissible.
 0296            return nearest * 0.99 * 100.0 * minFactor;
 0297        };
 11547298    }
 299
 300}