Esempio n. 1
0
        /// <summary>
        /// Adds multiple shortcut db's at the same time.
        /// </summary>
        public static void AddShortcuts(this RouterDb routerDb, ShortcutSpecs[] shortcutSpecs, CancellationToken cancellationToken)
        {
            // check all specs.
            if (shortcutSpecs == null)
            {
                throw new ArgumentNullException();
            }
            for (var i = 0; i < shortcutSpecs.Length; i++)
            {
                if (shortcutSpecs[i] == null ||
                    shortcutSpecs[i].Locations == null)
                {
                    throw new ArgumentException(string.Format("Shortcut specs at index {0} not set or locations not set.",
                                                              i));
                }
                if (shortcutSpecs[i].LocationsMeta != null &&
                    shortcutSpecs[i].LocationsMeta.Length != shortcutSpecs[i].Locations.Length)
                {
                    throw new ArgumentException(string.Format("Shortcut specs at index {0} has a different dimensions for locations and meta-data.",
                                                              i));
                }
            }

            for (var i = 0; i < shortcutSpecs.Length; i++)
            {
                var specs = shortcutSpecs[i];

                var profiles = new List <Profile>();
                profiles.Add(specs.Profile);
                profiles.AddRange(specs.TransitionProfiles);

                var routerPointEmbedder = new Itinero.Algorithms.Networks.RouterPointEmbedder(routerDb, profiles.ToArray(), specs.Locations);
                routerPointEmbedder.Run(cancellationToken);
            }

            for (var i = 0; i < shortcutSpecs.Length; i++)
            {
                var specs = shortcutSpecs[i];
                Itinero.Logging.Logger.Log("RouterDbExtensions", Logging.TraceEventType.Information,
                                           "Building shortcuts for {0}...", specs.Name);

                var shortcutBuilder = new Itinero.Algorithms.Shortcuts.ShortcutBuilder(routerDb, specs.Profile, specs.Name, specs.Locations,
                                                                                       specs.LocationsMeta, specs.TransferTime, specs.MinTravelTime, specs.MaxShortcutDuration);
                shortcutBuilder.Run(cancellationToken);

                routerDb.AddShortcuts(specs.Name, shortcutBuilder.ShortcutsDb);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Gets covered edges, once an edge is covered by more then the given tolerance it's returned.
        /// </summary>
        public static IEnumerable <long> GetCoveredEdges(this ReferencedLine line, RouterDb routerDb, float tolerancePercentage = 1f)
        {
            if (line.PositiveOffsetPercentage == 0 &&
                line.NegativeOffsetPercentage == 0)
            {
                foreach (var e in line.Edges)
                {
                    yield return(e);
                }
            }
            else
            {
                var lengths     = new float[line.Edges.Length];
                var totalLength = 0f;
                for (var i = 0; i < line.Edges.Length; i++)
                {
                    lengths[i]   = routerDb.Network.GetEdge(line.Edges[i]).Data.Distance;
                    totalLength += lengths[i];
                }

                var offset = 0f;
                for (var i = 0; i < line.Edges.Length; i++)
                {
                    var endOffset = offset + lengths[i];

                    var startPercentage = (offset / totalLength) * 100;
                    var endPercentage   = (endOffset / totalLength) * 100;

                    var startDiff = startPercentage - line.PositiveOffsetPercentage;
                    if (System.Math.Abs(startDiff) < tolerancePercentage)
                    {
                        startDiff = 0;
                    }
                    var endDiff = (100 - endPercentage) - line.NegativeOffsetPercentage;
                    if (System.Math.Abs(endDiff) < tolerancePercentage)
                    {
                        endDiff = 0;
                    }

                    if (startDiff >= 0 && endDiff >= 0)
                    {
                        yield return(line.Edges[i]);
                    }

                    offset = endOffset;
                }
            }
        }
Esempio n. 3
0
        public void TestBicycleHighwayPedestrian()
        {
            // the input osm-data.
            var osmGeos = new OsmGeo[]
            {
                new Node()
                {
                    Id        = 1,
                    Latitude  = 51.04963322083945f,
                    Longitude = 3.719692826271057f
                },
                new Node()
                {
                    Id        = 2,
                    Latitude  = 51.05062804602733f,
                    Longitude = 3.7198376655578613f
                },
                new Way()
                {
                    Id    = 1,
                    Nodes = new long[]
                    {
                        1, 2
                    },
                    Tags = new TagsCollection(
                        new Tag("highway", "pedestrian"))
                }
            };

            // build router db.
            var routerDb = new RouterDb();

            routerDb.LoadOsmData(osmGeos, Vehicle.Bicycle);

            // test some routes.
            var router = new Router(routerDb);

            // confirm it's not working for bicycles.
            var route = router.TryCalculate(Vehicle.Bicycle.Fastest(),
                                            new Coordinate(51.04963322083945f, 3.719692826271057f),
                                            new Coordinate(51.05062804602733f, 3.7198376655578613f));

            Assert.IsTrue(route.IsError);
            route = router.TryCalculate(Vehicle.Bicycle.Fastest(),
                                        new Coordinate(51.05062804602733f, 3.7198376655578613f),
                                        new Coordinate(51.04963322083945f, 3.719692826271057f));
            Assert.IsTrue(route.IsError);
        }
Esempio n. 4
0
        public void RouterDbGraphEnumerator_ShouldEnumerateEdgesInGraph()
        {
            var routerDb = new RouterDb();
            var vertex1  = routerDb.AddVertex(4.792613983154297, 51.26535213392538);
            var vertex2  = routerDb.AddVertex(4.797506332397461, 51.26674845584085);

            var edgeId = routerDb.AddEdge(vertex1, vertex2);

            var enumerator = routerDb.GetEdgeEnumerator();

            enumerator.MoveTo(vertex1);
            Assert.True(enumerator.MoveNext());
            Assert.Equal(vertex1, enumerator.From);
            Assert.Equal(vertex2, enumerator.To);
            Assert.True(enumerator.Forward);
        }
Esempio n. 5
0
        private static void ProcessDbToGetOnlyCarRoutes()
        {
            var routerDb = new RouterDb();

            using (var stream = new FileInfo(@"C:\GIT\private\map\quebec-latest.osm.pbf").OpenRead())
            {
                // create the network for cars.
                routerDb.LoadOsmData(stream, Vehicle.Car);
            }

            // write the routerDb to disk
            using (var stream = new FileInfo(@"C:\GIT\private\map\quebec.routerdb").Open(FileMode.Create))
            {
                routerDb.Serialize(stream);
            }
        }
        /// <summary>
        /// Extracts a vector tile of the given tile.
        /// </summary>
        public static VectorTile ExtractTile(this RouterDb routerDb, ulong tileId,
                                             VectorTileConfig config)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            var layers = routerDb.ExtractLayers(tileId, config);

            return(new VectorTile()
            {
                Layers = new List <Layer>(layers),
                TileId = tileId
            });
        }
        /// <summary>
        /// Creates a new processor.
        /// </summary>
        public DynamicVehicleNodeRestrictionProcessor(RouterDb routerDb, DynamicVehicle vehicle, Func <Node, uint> markCore,
                                                      Action <string, List <uint> > foundRestriction)
        {
            _foundRestriction    = foundRestriction;
            _routerDb            = routerDb;
            _vehicle             = vehicle;
            _markCore            = markCore;
            _nodeRestrictionFunc = vehicle.Script.Globals["node_restriction"];
            _markCore            = markCore;

            if (_nodeRestrictionFunc != null)
            {
                _attributesTable = new Table(vehicle.Script);
                _resultsTable    = new Table(vehicle.Script);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Builds a routerdb.
        /// </summary>
        /// <returns></returns>
        public static RouterDb Build(string queryName, Vehicle vehicle)
        {
            Download.ToFile(queryName);

            var fileName = queryName + ".osm";

            RouterDb routerDb = null;

            Itinero.Logging.Logger.Log("RouterDbBuilder", Itinero.Logging.TraceEventType.Information, "No existing RouterDb file found, creating now.");
            using (var stream = File.OpenRead(fileName))
            {
                var xmlStream  = new OsmSharp.Streams.XmlOsmStreamSource(stream);
                var sortedData = xmlStream.ToList();
                sortedData.Sort((x, y) =>
                {
                    if (x.Type == y.Type)
                    {
                        return(x.Id.Value.CompareTo(y.Id.Value));
                    }
                    if (x.Type == OsmSharp.OsmGeoType.Node)
                    {
                        return(-1);
                    }
                    else if (x.Type == OsmSharp.OsmGeoType.Way)
                    {
                        if (y.Type == OsmSharp.OsmGeoType.Node)
                        {
                            return(1);
                        }
                        return(-1);
                    }
                    return(1);
                });

                routerDb = new RouterDb();
                routerDb.LoadOsmData(sortedData, vehicle);
            }

            Itinero.Logging.Logger.Log("RouterDbBuilder", Itinero.Logging.TraceEventType.Information, "RouterDb file created.");

            if (!routerDb.HasContractedFor(vehicle.Fastest()))
            {
                Itinero.Logging.Logger.Log("RouterDbBuilder", Itinero.Logging.TraceEventType.Information, "No contracted graph found for the 'car' profile, building now...");
                routerDb.AddContracted(vehicle.Fastest(), true);
            }
            return(routerDb);
        }
Esempio n. 9
0
        /// <summary>
        /// Creates a new router db stream target.
        /// </summary>
        public RouterDbStreamTarget(RouterDb db, Vehicle[] vehicles, ITagNormalizer tagNormalizer, bool allCore = false,
                                    int minimumStages = 1, bool normalizeTags = true, IEnumerable <ITwoPassProcessor> processors = null, bool processRestrictions = false)
        {
            _db       = db;
            _vehicles = vehicles;

            _vehicleTypes = new HashSet <string>();
            foreach (var vehicle in _vehicles)
            {
                foreach (var vehicleType in vehicle.VehicleTypes)
                {
                    _vehicleTypes.Add(vehicleType);
                }
            }

            _allNodesAreCore = allCore;
            _normalizeTags   = normalizeTags;
            _tagNormalizer   = tagNormalizer;

            _createNodeCoordinatesDictionary = () =>
            {
                return(new NodeCoordinatesDictionary());
            };
            _stageCoordinates = _createNodeCoordinatesDictionary();
            _allRoutingNodes  = new SparseLongIndex();
            _anyStageNodes    = new SparseLongIndex();
            _coreNodes        = new SparseLongIndex();
            _coreNodeIdMap    = new CoreNodeIdMap();
            _processedWays    = new SparseLongIndex();
            _minimumStages    = minimumStages;

            foreach (var vehicle in vehicles)
            {
                foreach (var profiles in vehicle.GetProfiles())
                {
                    db.AddSupportedProfile(profiles);
                }
            }

            if (processors == null)
            {
                processors = new List <ITwoPassProcessor>();
            }
            this.Processors = new List <ITwoPassProcessor>(processors);

            this.InitializeDefaultProcessors(processRestrictions);
        }
Esempio n. 10
0
        /// <summary>
        /// Creates a new reader.
        /// </summary>
        public ShapefileReader(RouterDb routerDb, IList <ShapefileDataReader> shapefileReaders, Vehicle[] vehicles, string sourceVertexColumn, string targetVertexColumn)
        {
            _routerDb           = routerDb;
            _shapefileReaders   = shapefileReaders;
            _vehicles           = vehicles;
            _sourceVertexColumn = sourceVertexColumn;
            _targetVertexColumn = targetVertexColumn;

            _vehicleCache = new VehicleCache(vehicles);

            if (string.IsNullOrEmpty(_sourceVertexColumn) &&
                string.IsNullOrEmpty(_targetVertexColumn))
            { // check for these in the vehicle(s).
                foreach (var vehicle in vehicles)
                {
                    var profileSourceVertex = string.Empty;
                    var profileTargetVertex = string.Empty;

                    if (vehicle.Parameters != null &&
                        vehicle.Parameters.TryGetValue("source_vertex", out profileSourceVertex) &&
                        vehicle.Parameters.TryGetValue("target_vertex", out profileTargetVertex))
                    {
                        if (string.IsNullOrWhiteSpace(_sourceVertexColumn))
                        {
                            _sourceVertexColumn = profileSourceVertex;
                        }
                        else if (_sourceVertexColumn != profileSourceVertex)
                        {
                            throw new Exception(string.Format(
                                                    "Cannot configure shapefile reader: Multiple vehicle definitions but different source vertex column defined: {0} and {1} found.",
                                                    _sourceVertexColumn, profileSourceVertex));
                        }

                        if (string.IsNullOrWhiteSpace(_targetVertexColumn))
                        {
                            _targetVertexColumn = profileTargetVertex;
                        }
                        else if (_targetVertexColumn != profileTargetVertex)
                        {
                            throw new Exception(string.Format(
                                                    "Cannot configure shapefile reader: Multiple vehicle definitions but different target vertex column defined: {0} and {1} found.",
                                                    _targetVertexColumn, profileTargetVertex));
                        }
                    }
                }
            }
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            // enable logging.
            OsmSharp.Logging.Logger.LogAction = (o, level, message, parameters) =>
            {
                Console.WriteLine(string.Format("[{0}] {1} - {2}", o, level, message));
            };
            Itinero.Logging.Logger.LogAction = (o, level, message, parameters) =>
            {
                Console.WriteLine(string.Format("[{0}] {1} - {2}", o, level, message));
            };

            Download.ToFile("http://files.itinero.tech/data/OSM/planet/europe/luxembourg-latest.osm.pbf", "luxembourg-latest.osm.pbf").Wait();

            // load some routing data and create a router.
            var routerDb = new RouterDb();
            var router   = new Router(routerDb);

            using (var stream = File.OpenRead("luxembourg-latest.osm.pbf"))
            {
                routerDb.LoadOsmData(stream, Vehicle.Car);
            }

            // create a new srtm data instance.
            // it accepts a folder to download and cache data into.
            var srtmCache = new DirectoryInfo("srtm-cache");

            if (!srtmCache.Exists)
            {
                srtmCache.Create();
            }
            var srtmData = new SRTMData("srtm-cache");

            ElevationHandler.GetElevation = (lat, lon) =>
            {
                return((short)srtmData.GetElevation(lat, lon));
            };

            // add elevation.
            routerDb.AddElevation();

            // calculate route.
            // this should be the result: http://geojson.io/#id=gist:anonymous/c944cb9741f1fd511c8213b2dd83d58d&map=17/49.75454/6.09571
            var route = router.Calculate(Vehicle.Car.Fastest(), new Coordinate(49.75635954613685f, 6.095362901687622f),
                                         new Coordinate(49.75263039062888f, 6.098860502243042f));
            var routeGeoJson = route.ToGeoJson();
        }
Esempio n. 12
0
        /// <summary>
        /// Loads a routing network created from OSM data.
        /// </summary>
        public static void LoadOsmData(this RouterDb db, IEnumerable <OsmGeo> source, bool allCore = false, bool processRestrictions = false, params Itinero.Osm.Vehicles.Vehicle[] vehicles)
        {
            if (!db.IsEmpty)
            {
                throw new ArgumentException("Can only load a new routing network into an empty router db.");
            }

            // load the data.
            var target = new Streams.RouterDbStreamTarget(db,
                                                          vehicles, allCore, processRestrictions: processRestrictions);

            target.RegisterSource(source);
            target.Pull();

            // sort the network.
            db.Sort();
        }
Esempio n. 13
0
 public RoadNet(string routerDbFilePath, string osmFilePath)
 {
     //EnableLogging();
     routerDb = new RouterDb();
     if (File.Exists(routerDbFilePath))
     {
         using (var stream = File.OpenRead(routerDbFilePath))
         {
             routerDb = RouterDb.Deserialize(stream);
             router   = new Router(routerDb);
         }
     }
     else
     {
         BuildRoutingDB(osmFilePath, routerDbFilePath);
     }
 }
Esempio n. 14
0
        public static void Main(string[] args)
        {
            Download.ToFile("http://files.itinero.tech/data/itinero/routerdbs/planet/europe/belgium.c.cf.routerdb", "belgium.c.cf.routerdb").Wait();

            var routerDb = RouterDb.Deserialize(File.OpenRead("belgium.c.cf.routerdb"));
            var router   = new Router(routerDb);

            var locations = new List <Coordinate>(new Coordinate[]
            {
                new Coordinate(51.270453873703080f, 4.8008108139038080f),
                new Coordinate(51.264197451065370f, 4.8017120361328125f),
                new Coordinate(51.267446600889850f, 4.7830009460449220f),
                new Coordinate(51.260733228426076f, 4.7796106338500980f),
                new Coordinate(51.256489871317920f, 4.7884941101074220f),
                new Coordinate(51.270964016530680f, 4.7894811630249020f)
            });

            // METHOD1: quick and easy for high-quality data already on the road network.
            // calculate drive time in seconds between all given locations.
            var resolved      = router.Resolve(Vehicle.Car.Fastest(), locations.ToArray());
            var invalidPoints = new HashSet <int>();
            var matrix        = router.CalculateWeight(Vehicle.Car.Fastest(), resolved, invalidPoints);

            // METHOD2: most datasets contain large numbers of unconfirmed locations that may be too far from the road network or contain errors.
            //          this method can handle coordinates sets that contains errors.

            // let's add a location that's in the middle of nowhere.
            var invalidLocation = new Coordinate(51.275689280878694f, 4.7779369354248040f);

            locations.Insert(3, invalidLocation);

            // for advanced applications there is a helper class
            var matrixCalculator = new Itinero.Algorithms.WeightMatrixAlgorithm(router, Vehicle.Car.Fastest(), locations.ToArray());

            matrixCalculator.Run();

            // there is some usefull output data here now.
            var weights = matrixCalculator.Weights;             // the weights, in this case seconds travel time.
            var errors  = matrixCalculator.Errors;              // some locations could be unreachable, this contains details about those locations.

            resolved = matrixCalculator.RouterPoints.ToArray(); // the resolved routerpoints, you can use these later without the need to resolve again.

            // when there are failed points, the weight matrix is smaller, use these functions to map locations from the original array to succeeded points.
            var newIndex = matrixCalculator.IndexOf(4);         // returns the index of the original location in the weight matrix.
            var oldIndex = matrixCalculator.LocationIndexOf(5); // returns the index of the weight matrix point in the original locations array.
        }
Esempio n. 15
0
        public void TestCustomResolverDelegate()
        {
            var routerDb = new RouterDb();

            routerDb.AddSupportedVehicle(VehicleMock.Car());
            var router = new Router(routerDb);
            var called = false;

            router.CreateCustomResolver = (latitude, longitude, isAcceptable, isBetter) =>
            {
                called = true;
                return(new MockResolver(new RouterPoint(latitude, longitude, 0, 0)));
            };
            router.Resolve(new Itinero.Profiles.Profile[] { VehicleMock.Car().Fastest() }, 0, 0);

            Assert.IsTrue(called);
        }
Esempio n. 16
0
 public RoadNet(string routerDbFilePath)
 {
     //EnableLogging();
     routerDb = new RouterDb();
     if (File.Exists(routerDbFilePath))
     {
         using (var stream = File.OpenRead(routerDbFilePath))
         {
             routerDb = RouterDb.Deserialize(stream);
             router   = new Router(routerDb);
         }
     }
     else
     {
         throw new FileNotFoundException();
     }
 }
Esempio n. 17
0
        public void GeometricSearchRegressionTest()
        {
            // setup a routing network to test against.
            var routerDb = new RouterDb();

            routerDb.LoadTestNetwork(
                System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(
                    "Itinero.Test.test_data.networks.network7.geojson"));
            routerDb.Sort();
            routerDb.AddSupportedVehicle(Itinero.Osm.Vehicles.Vehicle.Car);

            var vertex7  = routerDb.Network.GetVertex(7);
            var vertices = routerDb.Network.GeometricGraph.Search(vertex7.Latitude, vertex7.Longitude, 0.001f);

            Assert.AreEqual(1, vertices.Count);
            Assert.AreEqual(7, vertices.First());
        }
Esempio n. 18
0
        private void InitializeRouting()
        {
            using (var ms = new MemoryStream())
            {
                using (var stream = Activity.BaseContext.Assets.Open(RouterDbName))
                {
                    stream.CopyTo(ms);
                }

                ms.Seek(0, SeekOrigin.Begin);
                var routerDb = RouterDb.Deserialize(ms);

                router = new Router(routerDb);
            }

            itineroProfile = Vehicle.Pedestrian.Shortest();
        }
Esempio n. 19
0
        public void TestOptimizeNetwork()
        {
            // build and load network.
            var routerDb = new RouterDb();

            routerDb.LoadTestNetwork(
                System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(
                    "Itinero.Test.test_data.networks.network9.geojson"));

            routerDb.AddSupportedVehicle(Itinero.Osm.Vehicles.Vehicle.Car);

            // optimize.
            Assert.AreEqual(10, routerDb.Network.EdgeCount);
            routerDb.OptimizeNetwork();
            routerDb.Network.Compress();
            Assert.AreEqual(6, routerDb.Network.EdgeCount);
        }
Esempio n. 20
0
        public void TestTwoDistinctEdges()
        {
            // build routerdb.
            var routerDb = new RouterDb();

            routerDb.Network.AddVertex(0, 0, 0);
            routerDb.Network.AddVertex(1, 1, 1);
            routerDb.Network.AddEdge(0, 1, new Itinero.Data.Network.Edges.EdgeData()
            {
                Distance = 100,
                Profile  = 1
            }, null);
            routerDb.Network.AddVertex(2, 0, 0);
            routerDb.Network.AddVertex(3, 1, 1);
            routerDb.Network.AddEdge(2, 3, new Itinero.Data.Network.Edges.EdgeData()
            {
                Distance = 100,
                Profile  = 1
            }, null);

            // build speed profile function.
            var speed = 100f / 3.6f;
            Func <ushort, Itinero.Profiles.Factor> getFactor = (x) =>
            {
                return(new Itinero.Profiles.Factor()
                {
                    Direction = 0,
                    Value = 1.0f / speed
                });
            };

            // start island detector.
            var islandDetector = new IslandDetector(routerDb, new Func <ushort, Itinero.Profiles.Factor>[] { getFactor });

            islandDetector.Run();

            // verify the islands.
            var islands = islandDetector.Islands;

            Assert.IsNotNull(islands);
            Assert.AreEqual(4, islands.Length);
            Assert.AreEqual(1, islands[0]);
            Assert.AreEqual(1, islands[1]);
            Assert.AreEqual(2, islands[2]);
            Assert.AreEqual(2, islands[3]);
        }
Esempio n. 21
0
 /// <summary>
 /// Searches a vertex for the given location.
 /// </summary>
 public static uint SearchVertexFor(this RouterDb db, float latitude, float longitude)
 {
     for (uint vertex = 0; vertex < db.Network.VertexCount; vertex++)
     {
         float lat, lon;
         if (db.Network.GetVertex(vertex, out lat, out lon))
         {
             var dist = Itinero.LocalGeo.Coordinate.DistanceEstimateInMeter(latitude, longitude,
                                                                            lat, lon);
             if (dist < Tolerance)
             {
                 return(vertex);
             }
         }
     }
     return(Itinero.Constants.NO_VERTEX);
 }
Esempio n. 22
0
        public void TestLocationOnNetwork()
        {
            var routerDb = new RouterDb();

            routerDb.Network.AddVertex(0, 0, 0);
            routerDb.Network.AddVertex(1, .1f, -.1f);
            routerDb.Network.AddEdge(0, 1, new EdgeData()
            {
                Distance = 1000,
                MetaId   = routerDb.EdgeProfiles.Add(new AttributeCollection(
                                                         new Attribute("name", "Abelshausen Blvd."))),
                Profile = (ushort)routerDb.EdgeProfiles.Add(new AttributeCollection(
                                                                new Attribute("highway", "residential")))
            }, new Coordinate(0.025f, -0.025f),
                                     new Coordinate(0.050f, -0.050f),
                                     new Coordinate(0.075f, -0.075f));

            // mock profile.
            var profile = MockProfile.CarMock();

            var point = new RouterPoint(0.04f, -0.04f, 0, (ushort)(0.4 * ushort.MaxValue));

            var location = point.LocationOnNetwork(routerDb);

            Assert.AreEqual(0.04f, location.Latitude, 0.001f);
            Assert.AreEqual(-0.04f, location.Longitude, 0.001f);

            point = new RouterPoint(0.08f, -0.08f, 0, (ushort)(0.8 * ushort.MaxValue));

            location = point.LocationOnNetwork(routerDb);
            Assert.AreEqual(0.08f, location.Latitude, 0.001f);
            Assert.AreEqual(-0.08f, location.Longitude, 0.001f);

            point = new RouterPoint(0, 0, 0, 0);

            location = point.LocationOnNetwork(routerDb);
            Assert.AreEqual(0, location.Latitude, 0.001f);
            Assert.AreEqual(0, location.Longitude, 0.001f);

            point = new RouterPoint(.1f, -.1f, 0, ushort.MaxValue);

            location = point.LocationOnNetwork(routerDb);
            Assert.AreEqual(.1f, location.Latitude, 0.001f);
            Assert.AreEqual(-.1f, location.Longitude, 0.001f);
        }
        /// <summary>
        /// Gets all features inside the given bounding box.
        /// </summary>
        public static FeatureCollection GetFeaturesIn(this RouterDb db, float minLatitude, float minLongitude,
                                                      float maxLatitude, float maxLongitude, bool includeEdges = true, bool includeVertices = true)
        {
            var features = new FeatureCollection();

            var vertices = Itinero.Algorithms.Search.Hilbert.HilbertExtensions.Search(db.Network.GeometricGraph, minLatitude, minLongitude,
                                                                                      maxLatitude, maxLongitude);
            var edges = new HashSet <long>();

            var edgeEnumerator = db.Network.GetEdgeEnumerator();

            foreach (var vertex in vertices)
            {
                if (includeVertices)
                {
                    features.Add(db.GetFeatureForVertex(vertex));
                }

                if (includeEdges)
                {
                    edgeEnumerator.MoveTo(vertex);
                    edgeEnumerator.Reset();
                    while (edgeEnumerator.MoveNext())
                    {
                        if (edges.Contains(edgeEnumerator.Id))
                        {
                            continue;
                        }
                        edges.Add(edgeEnumerator.Id);

                        var edgeAttributes = new Itinero.Attributes.AttributeCollection(db.EdgeMeta.Get(edgeEnumerator.Data.MetaId));
                        edgeAttributes.AddOrReplace(db.EdgeProfiles.Get(edgeEnumerator.Data.Profile));

                        var geometry   = new LineString(db.Network.GetShape(edgeEnumerator.Current).ToCoordinatesArray());
                        var attributes = edgeAttributes.ToAttributesTable();
                        attributes.AddAttribute("id", edgeEnumerator.Id.ToInvariantString());
                        attributes.AddAttribute("distance", edgeEnumerator.Data.Distance.ToInvariantString());
                        features.Add(new Feature(geometry,
                                                 attributes));
                    }
                }
            }

            return(features);
        }
Esempio n. 24
0
        /// <summary>
        /// Adds a test edge.
        /// </summary>
        public static uint AddTestEdge(this RouterDb routerDb, float latitude1, float longitude1,
                                       float latitude2, float longitude2)
        {
            var vertex1 = routerDb.Network.VertexCount;

            routerDb.Network.AddVertex(vertex1, latitude1, longitude1);
            var vertex2 = routerDb.Network.VertexCount;

            routerDb.Network.AddVertex(vertex2, latitude2, longitude2);

            return(routerDb.Network.AddEdge(vertex1, vertex2,
                                            new Itinero.Data.Network.Edges.EdgeData()
            {
                Distance = Coordinate.DistanceEstimateInMeter(latitude1, longitude1, latitude2, longitude2),
                Profile = 0,
                MetaId = 0
            }));
        }
Esempio n. 25
0
        /// <summary>
        /// Returns a coverage in meters for all given edges.
        /// </summary>
        /// <param name="coverage"></param>
        /// <returns></returns>
        public static List <EdgeCoverInMeter> ConvertToMeter(this RouterDb routerDb, List <RouterDbExtensions.EdgeCover> coverage)
        {
            var result = new List <EdgeCoverInMeter>(coverage.Count);

            foreach (var cover in coverage)
            {
                var length = routerDb.Network.GetEdge(cover.DirectedEdgeId.EdgeId).Data.Distance;

                result.Add(new EdgeCoverInMeter()
                {
                    DirectedEdgeId = cover.DirectedEdgeId,
                    StartOffset    = cover.StartPercentage / 100.0f * length,
                    EndOffset      = cover.EndPercentage / 100.0f * length
                });
            }

            return(result);
        }
Esempio n. 26
0
        private void Create(string pbfPath, string routerDbPath)
        {
            // load some routing data and build a routing network.
            var routerDb = new RouterDb();

            using (var stream = new FileInfo(pbfPath).OpenRead())
            {
                // create the network for cars only.
                routerDb.LoadOsmData(stream, Vehicle.Car);
            }

            // write the routerdb to disk.
            using (var stream = new FileInfo(routerDbPath).Open(FileMode.Create))
            {
                routerDb.Serialize(stream);
            }
            _router = new Router(routerDb);
        }
        /// <summary>
        /// Loads routing data from the given shapefiles for the given vehicles.
        /// </summary>
        public static void LoadFromShape(this RouterDb routerDb, string path, string searchPattern, string sourceVertexColumn, string targetVertexColumn,
                                         params Vehicle[] vehicles)
        {
            // build a list of nw-files.
            var directoryInfo = new DirectoryInfo(path);
            var networkFiles  = directoryInfo.EnumerateFiles(searchPattern, SearchOption.AllDirectories);

            // create all readers.
            var readers         = new List <ShapefileDataReader>();
            var geometryFactory = NtsGeometryServices.Instance.CreateGeometryFactory();

            foreach (var networkFile in networkFiles)
            {
                readers.Add(new ShapefileDataReader(networkFile.FullName, geometryFactory));
            }

            routerDb.LoadFromShape(readers, sourceVertexColumn, targetVertexColumn, vehicles);
        }
Esempio n. 28
0
        public void TestOneEdgeDontCareDirections()
        {
            var routerDb = new RouterDb();

            routerDb.LoadTestNetwork(
                System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(
                    "Itinero.Test.test_data.networks.network1.geojson"));
            routerDb.Network.Sort();
            routerDb.Network.Compress();
            var profile = Itinero.Osm.Vehicles.Vehicle.Pedestrian.Fastest();

            routerDb.AddSupportedVehicle(profile.Parent);
            var router = new Router(routerDb);

            var location1 = new Coordinate(51.22972151230172f, 4.461323618888854f);
            var location2 = new Coordinate(51.22973830827689f, 4.462852478027344f);
            var point1    = router.Resolve(profile, location1);
            var point2    = router.Resolve(profile, location2);

            // test forward -> don't care
            var route = router.TryCalculate(profile, point1, true, point2, null);

            Assert.IsNotNull(route);
            Assert.IsFalse(route.IsError);
            Assert.IsNotNull(route.Value.Shape);
            Assert.IsTrue(Coordinate.DistanceEstimateInMeter(route.Value.Shape[0], point1.LocationOnNetwork(routerDb)) < 1);
            Assert.IsTrue(Coordinate.DistanceEstimateInMeter(route.Value.Shape[route.Value.Shape.Length - 1], point2.LocationOnNetwork(routerDb)) < 1);

            // test don't care -> forward
            route = router.TryCalculate(profile, point1, null, point2, true);
            Assert.IsNotNull(route);
            Assert.IsFalse(route.IsError);
            Assert.IsNotNull(route.Value.Shape);
            Assert.IsTrue(Coordinate.DistanceEstimateInMeter(route.Value.Shape[0], point1.LocationOnNetwork(routerDb)) < 1);
            Assert.IsTrue(Coordinate.DistanceEstimateInMeter(route.Value.Shape[route.Value.Shape.Length - 1], point2.LocationOnNetwork(routerDb)) < 1);

            // test don't care -> don't care
            route = router.TryCalculate(profile, point1, (bool?)null, point2, null);
            Assert.IsNotNull(route);
            Assert.IsFalse(route.IsError);
            Assert.IsNotNull(route.Value.Shape);
            Assert.IsTrue(Coordinate.DistanceEstimateInMeter(route.Value.Shape[0], point1.LocationOnNetwork(routerDb)) < 1);
            Assert.IsTrue(Coordinate.DistanceEstimateInMeter(route.Value.Shape[route.Value.Shape.Length - 1], point2.LocationOnNetwork(routerDb)) < 1);
        }
        /// <summary>
        /// Gets all data from the edge meta collections for the given segment.
        /// </summary>
        /// <param name="routerDb">The router db.</param>
        /// <param name="edgeId">The edge.</param>
        /// <returns>An enumerable of attributes associated with the given edge.</returns>
        public static IEnumerable <Attribute> GetEdgeAttributes(this RouterDb routerDb, uint edgeId)
        {
            var edge = routerDb.Network.GetEdge(edgeId);

            var profileMeta = routerDb.EdgeProfiles.Get(edge.Data.Profile);

            if (profileMeta != null)
            {
                foreach (var a in profileMeta)
                {
                    yield return(a);
                }
            }

            var edgeMeta = routerDb.EdgeMeta.Get(edge.Data.MetaId);

            if (edgeMeta != null)
            {
                foreach (var a in edgeMeta)
                {
                    yield return(a);
                }
            }

            if (routerDb.EdgeData == null)
            {
                yield break;
            }
            var edgeData = routerDb.EdgeData;

            foreach (var metaName in routerDb.EdgeData.Names)
            {
                var edgeMetaCollection = edgeData.Get(metaName);
                var edgeMetaData       = edgeMetaCollection.GetRaw(edgeId);
                var key   = metaName;
                var value = string.Empty;
                if (edgeMetaData != null)
                {
                    value = edgeMetaData.ToInvariantString();
                }

                yield return(new Attribute(key, value));
            }
        }
        /// <summary>
        /// Loads a routing network created from OSM data.
        /// </summary>
        public static void LoadOsmData(this RouterDb db, OsmStreamSource[] sources, bool allCore = false, bool processRestrictions = true,
                                       IEnumerable <ITwoPassProcessor> processors = null, params Itinero.Profiles.Vehicle[] vehicles)
        {
            if (!db.IsEmpty)
            {
                throw new ArgumentException("Can only load a new routing network into an empty router db, add multiple streams at once to load multiple files.");
            }
            if (vehicles == null || vehicles.Length == 0)
            {
                throw new ArgumentNullException("vehicles", "A least one vehicle is needed to load OSM data.");
            }
            if (sources == null || sources.Length == 0)
            {
                throw new ArgumentNullException("sources", "A least one source is needed to load OSM data.");
            }

            // merge sources if needed.
            var source = sources[0];

            for (var i = 1; i < sources.Length; i++)
            {
                var merger = new OsmSharp.Streams.Filters.OsmStreamFilterMerge();
                merger.RegisterSource(source);
                merger.RegisterSource(sources[i]);
                source = merger;
            }

            if (sources.Length > 1 && !(source is OsmStreamFilterProgress))
            { // just one source the the callee is choosing a progress filter but assumed the default for a merged stream.
                var progress = new OsmStreamFilterProgress();
                progress.RegisterSource(source);
                source = progress;
            }

            // load the data.
            var target = new Streams.RouterDbStreamTarget(db,
                                                          vehicles, allCore, processRestrictions: processRestrictions, processors: processors);

            target.RegisterSource(source);
            target.Pull();

            // sort the network.
            db.Sort();
        }