Example #1
0
        /// <summary>
        /// Builds the data.
        /// </summary>
        /// <param name="interpreter"></param>
        /// <param name="embeddedString"></param>
        /// <returns></returns>
        public override IRoutingAlgorithmData <CHEdgeData> BuildData(IOsmRoutingInterpreter interpreter,
                                                                     string embeddedString)
        {
            string key = string.Format("CHEdgeDifference.Routing.IRoutingAlgorithmData<CHEdgeData>.OSM.{0}",
                                       embeddedString);
            var data = StaticDictionary.Get <IRoutingAlgorithmData <CHEdgeData> >(
                key);

            if (data == null)
            {
                var tagsIndex = new TagsIndex();

                // do the data processing.
                var memoryData = new RouterDataSource <CHEdgeData>(new DirectedGraph <CHEdgeData>(), tagsIndex);
                var targetData = new CHEdgeGraphOsmStreamTarget(
                    memoryData, interpreter, tagsIndex, Vehicle.Car);
                var dataProcessorSource = new XmlOsmStreamSource(
                    Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedString));
                var sorter = new OsmStreamFilterSort();
                sorter.RegisterSource(dataProcessorSource);
                targetData.RegisterSource(sorter);
                targetData.Pull();

                data = memoryData;
                StaticDictionary.Add <IRoutingAlgorithmData <CHEdgeData> >(key, data);
            }
            return(data);
        }
Example #2
0
        /// <summary>
        /// Tests preprocessing data from a PBF file.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pbfFile"></param>
        public static void TestPreprocessing(string name, string pbfFile)
        {
            FileInfo testFile = new FileInfo(string.Format(@".\TestFiles\{0}", pbfFile));
            Stream   stream   = testFile.OpenRead();
            var      progress = new OsmStreamFilterProgress();

            progress.RegisterSource(new PBFOsmStreamSource(stream));

            var performanceInfo = new PerformanceInfoConsumer("PreProcessor", 20000);

            performanceInfo.Start();
            performanceInfo.Report("Pulling from {0}...", testFile.Name);

            var tagsIndex = new TagsIndex(); // creates a tagged index.

            // read from the OSM-stream.
            var memoryData = new RouterDataSource <Edge>(new Graph <Edge>(), tagsIndex);
            var targetData = new GraphOsmStreamTarget(memoryData, new OsmRoutingInterpreter(), tagsIndex);

            targetData.RegisterSource(progress);
            targetData.Pull();

            stream.Dispose();

            performanceInfo.Stop();
            // make sure the router is still here after GC to note the memory difference.
            OsmSharp.Logging.Log.TraceEvent("PreProcessor", Logging.TraceEventType.Information, memoryData.ToString());
            memoryData = null;

            GC.Collect();
        }
        /// <summary>
        /// Returns a new router.
        /// </summary>
        /// <param name="interpreter"></param>
        /// <param name="embeddedName"></param>
        /// <returns></returns>
        public override Router BuildRouter(IOsmRoutingInterpreter interpreter, string embeddedName)
        {
            if (_data == null)
            {
                _data = new Dictionary<string, RouterDataSource<CHEdgeData>>();
            }
            RouterDataSource<CHEdgeData> data = null;
            if (!_data.TryGetValue(embeddedName, out data))
            {
                var tagsIndex = new TagsIndex();

                // do the data processing.
                data = new RouterDataSource<CHEdgeData>(new DirectedGraph<CHEdgeData>(), tagsIndex);
                var targetData = new CHEdgeGraphOsmStreamTarget(
                    data, interpreter, tagsIndex, Vehicle.Car);
                var dataProcessorSource = new XmlOsmStreamSource(
                    Assembly.GetExecutingAssembly().GetManifestResourceStream(string.Format(
                    "OsmSharp.Test.Unittests.{0}", embeddedName)));
                var sorter = new OsmStreamFilterSort();
                sorter.RegisterSource(dataProcessorSource);
                targetData.RegisterSource(sorter);
                targetData.Pull();

                _data[embeddedName] = data;
            }
            return Router.CreateCHFrom(data, new CHRouter(), interpreter);
        }
        /// <summary>
        /// Executes the CH contractions while verifying each step.
        /// </summary>
        /// <param name="stream"></param>
        public void DoTestCHEdgeDifferenceVerifiedContraction(Stream stream)
        {
            _interpreter = new OsmRoutingInterpreter();

            var tagsIndex = new TagsIndex();

            // do the data processing.
            _data = new RouterDataSource <CHEdgeData>(new DirectedGraph <CHEdgeData>(), tagsIndex);
            var targetData = new CHEdgeGraphOsmStreamTarget(
                _data, _interpreter, tagsIndex, Vehicle.Car);
            var dataProcessorSource = new XmlOsmStreamSource(stream);
            var sorter = new OsmStreamFilterSort();

            sorter.RegisterSource(dataProcessorSource);
            targetData.RegisterSource(sorter);
            targetData.Pull();

            // do the pre-processing part.
            var witnessCalculator = new DykstraWitnessCalculator();
            var preProcessor      = new CHPreprocessor(_data,
                                                       new EdgeDifferenceContractedSearchSpace(_data, witnessCalculator), witnessCalculator);

            preProcessor.OnBeforeContractionEvent +=
                new CHPreprocessor.VertexDelegate(pre_processor_OnBeforeContractionEvent);
            preProcessor.OnAfterContractionEvent +=
                new CHPreprocessor.VertexDelegate(pre_processor_OnAfterContractionEvent);
            preProcessor.Start();
        }
Example #5
0
        /// <summary>
        /// Tests routing from a serialized file.
        /// </summary>
        /// <param name="stream"></param>
        public static void TestSerialized(Stream stream, bool lazy = true)
        {
            var routingSerializer = new RoutingDataSourceSerializer();
            var data = routingSerializer.Deserialize(stream, lazy);

            uint vertex = 1;
            uint significantVertices = 0;

            while (vertex < data.VertexCount)
            {
                var edges = data.GetEdges(vertex).ToKeyValuePairs();
                if (edges.Length > 2)
                {
                    significantVertices++;
                }
                vertex++;
            }

            data.SortHilbert(1000);

            // copy.
            var graphCopy = new Graph <Edge>();

            graphCopy.CopyFrom(data);
            var dataCopy = new RouterDataSource <Edge>(graphCopy, data.TagsIndex);

            RoutingTest.Test(dataCopy, Vehicle.Pedestrian, 50);
        }
        public void RoutingRegressionTest1()
        {
            var interpreter = new OsmRoutingInterpreter();
            var tagsIndex = new TagsIndex();

            // do the data processing.
            var memoryData = new RouterDataSource<Edge>(new Graph<Edge>(), tagsIndex);
            var targetData = new GraphOsmStreamTarget(memoryData, interpreter, tagsIndex);
            var dataProcessorSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Routing.Test.data.test_routing_regression1.osm"));
            var sorter = new OsmStreamFilterSort();
            sorter.RegisterSource(dataProcessorSource);
            targetData.RegisterSource(sorter);
            targetData.Pull();

            var basicRouter = new Dykstra();
            var router = Router.CreateFrom(memoryData, basicRouter, interpreter);

            // resolve the three points in question.
            var point35 = new GeoCoordinate(51.01257, 4.000753);
            var point35resolved = router.Resolve(Vehicle.Car, point35);
            var point45 = new GeoCoordinate(51.01315, 3.999588);
            var point45resolved = router.Resolve(Vehicle.Car, point45);

            // route between 35 and 45.
            var routebefore = router.Calculate(Vehicle.Car, point35resolved, point45resolved);

            // route between 35 and 45.
            var routeafter = router.Calculate(Vehicle.Car, point35resolved, point45resolved);
            Assert.AreEqual(routebefore.TotalDistance, routeafter.TotalDistance);
        }
        /// <summary>
        /// Returns a new router.
        /// </summary>
        /// <param name="interpreter"></param>
        /// <param name="embeddedName"></param>
        /// <returns></returns>
        public override Router BuildRouter(IOsmRoutingInterpreter interpreter, string embeddedName)
        {
            if (_data == null)
            {
                _data = new Dictionary <string, RouterDataSource <CHEdgeData> >();
            }
            RouterDataSource <CHEdgeData> data = null;

            if (!_data.TryGetValue(embeddedName, out data))
            {
                var tagsIndex = new TagsIndex();

                // do the data processing.
                data = new RouterDataSource <CHEdgeData>(new DirectedGraph <CHEdgeData>(), tagsIndex);
                var targetData = new CHEdgeGraphOsmStreamTarget(
                    data, interpreter, tagsIndex, Vehicle.Car);
                var dataProcessorSource = new XmlOsmStreamSource(
                    Assembly.GetExecutingAssembly().GetManifestResourceStream(string.Format(
                                                                                  "OsmSharp.Test.Unittests.{0}", embeddedName)));
                var sorter = new OsmStreamFilterSort();
                sorter.RegisterSource(dataProcessorSource);
                targetData.RegisterSource(sorter);
                targetData.Pull();

                _data[embeddedName] = data;
            }
            return(Router.CreateCHFrom(data, new CHRouter(), interpreter));
        }
        public static Stream TestSerialization(string name, string pbfFile, RouterDataSource <CHEdgeData> data)
        {
            var testOutputFile = new FileInfo(@"test.routing");

            testOutputFile.Delete();
            var writeStream = testOutputFile.OpenWrite();

            var performanceInfo = new PerformanceInfoConsumer("CHSerializer");

            performanceInfo.Start();
            performanceInfo.Report("Writing to {0}...", testOutputFile.Name);

            TagsCollectionBase metaData = new TagsCollection();

            metaData.Add("some_key", "some_value");
            var routingSerializer = new CHEdgeSerializer();

            routingSerializer.Serialize(writeStream, data, metaData);

            writeStream.Dispose();

            OsmSharp.Logging.Log.TraceEvent("CHSerializer", OsmSharp.Logging.TraceEventType.Information,
                                            string.Format("Serialized file: {0}KB", testOutputFile.Length / 1024));

            performanceInfo.Stop();

            return(testOutputFile.OpenRead());
        }
        public void RoutingRegressionTest1()
        {
            var interpreter = new OsmRoutingInterpreter();
            var tagsIndex   = new TagsIndex();

            // do the data processing.
            var memoryData          = new RouterDataSource <Edge>(new Graph <Edge>(), tagsIndex);
            var targetData          = new GraphOsmStreamTarget(memoryData, interpreter, tagsIndex);
            var dataProcessorSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Routing.Test.data.test_routing_regression1.osm"));
            var sorter = new OsmStreamFilterSort();

            sorter.RegisterSource(dataProcessorSource);
            targetData.RegisterSource(sorter);
            targetData.Pull();

            var basicRouter = new Dykstra();
            var router      = Router.CreateFrom(memoryData, basicRouter, interpreter);

            // resolve the three points in question.
            var point35         = new GeoCoordinate(51.01257, 4.000753);
            var point35resolved = router.Resolve(Vehicle.Car, point35);
            var point45         = new GeoCoordinate(51.01315, 3.999588);
            var point45resolved = router.Resolve(Vehicle.Car, point45);

            // route between 35 and 45.
            var routebefore = router.Calculate(Vehicle.Car, point35resolved, point45resolved);

            // route between 35 and 45.
            var routeafter = router.Calculate(Vehicle.Car, point35resolved, point45resolved);

            Assert.AreEqual(routebefore.TotalDistance, routeafter.TotalDistance);
        }
        /// <summary>
        /// Creates a router.
        /// </summary>
        /// <param name="interpreter"></param>
        /// <param name="manifestResourceName"></param>
        /// <returns></returns>
        protected override Router CreateRouter(IOsmRoutingInterpreter interpreter, string manifestResourceName)
        {
            TagsIndex tagsIndex = new TagsIndex();

            // do the data processing.
            var data       = new RouterDataSource <CHEdgeData>(new DirectedGraph <CHEdgeData>(), tagsIndex);
            var targetData = new CHEdgeGraphOsmStreamTarget(
                data, interpreter, tagsIndex, Vehicle.Car);
            var dataProcessorSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(manifestResourceName));
            var sorter = new OsmStreamFilterSort();

            sorter.RegisterSource(dataProcessorSource);
            targetData.RegisterSource(sorter);
            targetData.Pull();

            // do the pre-processing part.
            var witnessCalculator = new DykstraWitnessCalculator();
            var preProcessor      = new CHPreprocessor(data,
                                                       new EdgeDifferenceContractedSearchSpace(data, witnessCalculator), witnessCalculator);

            preProcessor.Start();

            return(Router.CreateCHFrom(data, new CHRouter(), interpreter));
        }
        /// <summary>
        /// Serializes the given graph.
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="graph"></param>
        /// <param name="metaTags"></param>
        public void Serialize(Stream stream, RouterDataSource <TEdgeData> graph, TagsCollectionBase metaTags)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (graph == null)
            {
                throw new ArgumentNullException("graph");
            }

            // write the header.
            this.WriteVersionHeader(stream);

            // write the vehicles.
            this.WriteVehicleProfiles(stream, graph.GetSupportedProfiles());

            // write the meta-data.
            this.WriteMeta(stream, metaTags);

            // wrap the stream.
            var routingSerializerStream = new LimitedStream(stream);

            // do the version-specific serialization.
            this.DoSerialize(routingSerializerStream, graph);
        }
Example #12
0
        /// <summary>
        /// Tests preprocessing data from a PBF file.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pbfFile"></param>
        public static void TestPreprocessing(string name, string pbfFile)
        {
            FileInfo testFile = new FileInfo(string.Format(@".\TestFiles\{0}", pbfFile));
            Stream stream = testFile.OpenRead();
            var progress = new OsmStreamFilterProgress();
            progress.RegisterSource(new PBFOsmStreamSource(stream));

            var performanceInfo = new PerformanceInfoConsumer("PreProcessor", 20000);
            performanceInfo.Start();
            performanceInfo.Report("Pulling from {0}...", testFile.Name);

            var tagsIndex = new TagsIndex(); // creates a tagged index.

            // read from the OSM-stream.
            var memoryData = new RouterDataSource<Edge>(new Graph<Edge>(), tagsIndex);
            var targetData = new GraphOsmStreamTarget(memoryData, new OsmRoutingInterpreter(), tagsIndex);
            targetData.RegisterSource(progress);
            targetData.Pull();

            stream.Dispose();

            performanceInfo.Stop();
            // make sure the router is still here after GC to note the memory difference.
            OsmSharp.Logging.Log.TraceEvent("PreProcessor", Logging.TraceEventType.Information, memoryData.ToString());
            memoryData = null;

            GC.Collect();
        }
        /// <summary>
        /// Preprocesses the data from the given OsmStreamReader and converts it directly to a routable data source.
        /// </summary>
        /// <param name="source">The source stream.</param>
        /// <param name="tagsIndex">The tags index.</param>
        /// <param name="interpreter">The routing interpreter.</param>
        /// <returns></returns>
        public static RouterDataSource <Edge> Preprocess(OsmStreamSource source, ITagsIndex tagsIndex, IOsmRoutingInterpreter interpreter)
        {
            var routerDataSource =
                new RouterDataSource <Edge>(new Graph <Edge>(), tagsIndex);
            var targetData = new GraphOsmStreamTarget(routerDataSource, interpreter,
                                                      tagsIndex);

            targetData.RegisterSource(source);
            targetData.Pull();

            return(routerDataSource);
        }
        /// <summary>
        /// Preprocesses the data from the given OsmStreamReader and converts it directly to a routable data source.
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="tagsIndex"></param>
        /// <param name="interpreter"></param>
        /// <param name="vehicle"></param>
        /// <returns></returns>
        public static RouterDataSource <CHEdgeData> Preprocess(OsmStreamSource reader,
                                                               ITagsIndex tagsIndex, IOsmRoutingInterpreter interpreter, Vehicle vehicle)
        {
            // pull in the data.
            var graph      = new RouterDataSource <CHEdgeData>(new DirectedGraph <CHEdgeData>(), tagsIndex);
            var targetData = new CHEdgeGraphOsmStreamTarget(
                graph, interpreter, tagsIndex, vehicle);

            targetData.RegisterSource(reader);
            targetData.Pull();

            return(graph);
        }
        public void RoutingRegressionTest9ResolvingReverse()
        {
            // build a graph to encode from.
            var tags            = new TagsIndex();
            var graphDataSource = new RouterDataSource <Edge>(new Graph <Edge>(), tags);
            var vertex1         = graphDataSource.AddVertex(51.05849821468899f, 3.7240000000000000f);
            var vertex2         = graphDataSource.AddVertex(51.05849821468899f, 3.7254400000000000f);
            var vertex3         = graphDataSource.AddVertex(51.05849821468899f, 3.7225627899169926f);
            var edge            = new Edge() // all edges are identical.
            {
                Distance = 100,
                Forward  = true,
                Tags     = tags.Add(new TagsCollection(
                                        Tag.Create("highway", "tertiary"),
                                        Tag.Create("oneway", "yes")))
            };

            graphDataSource.AddEdge(vertex1, vertex2, edge, null);
            graphDataSource.AddEdge(vertex3, vertex1, edge, null);

            // {RectF:[(3,71326552867889,51,048498214689),(3,73326552867889,51,068498214689)]}
            var edges = graphDataSource.GetEdges(new GeoCoordinateBox(
                                                     new GeoCoordinate(51.068498214689, 3.73326552867889),
                                                     new GeoCoordinate(51.048498214689, 3.71326552867889)));

            while (edges.MoveNext())
            {
                if (edges.Vertex1 == 1 &&
                    edges.Vertex2 == 2)
                {
                    Assert.IsTrue(edges.EdgeData.Forward);
                }
                else if (edges.Vertex1 == 2 &&
                         edges.Vertex2 == 1)
                {
                    Assert.IsFalse(edges.EdgeData.Forward);
                }
                if (edges.Vertex1 == 1 &&
                    edges.Vertex2 == 3)
                {
                    Assert.IsFalse(edges.EdgeData.Forward);
                }
                else if (edges.Vertex1 == 3 &&
                         edges.Vertex2 == 1)
                {
                    Assert.IsTrue(edges.EdgeData.Forward);
                }
            }
        }
Example #16
0
        /// <summary>
        /// Creates a router using interpreted edges.
        /// </summary>
        /// <param name="reader">The OSM-stream reader.</param>
        /// <param name="interpreter">The routing interpreter.</param>
        /// <returns></returns>
        public static Router CreateFrom(OsmStreamSource reader, IOsmRoutingInterpreter interpreter)
        {
            var tagsIndex = new TagsIndex(); // creates a tagged index.

            // read from the OSM-stream.
            var memoryData = new RouterDataSource<Edge>(new Graph<Edge>(), tagsIndex);
            var targetData = new GraphOsmStreamTarget(memoryData, interpreter, tagsIndex);
            targetData.RegisterSource(reader);
            targetData.Pull();

            // creates the edge router.
            var typedRouter = new TypedRouterEdge(
                memoryData, interpreter, new Dykstra());

            return new Router(typedRouter); // create the actual router.
        }
Example #17
0
        /// <summary>
        /// Creates a router using interpreted edges.
        /// </summary>
        /// <param name="reader">The OSM-stream reader.</param>
        /// <param name="interpreter">The routing interpreter.</param>
        /// <returns></returns>
        public static Router CreateFrom(OsmStreamSource reader, IOsmRoutingInterpreter interpreter)
        {
            var tagsIndex = new TagsIndex(); // creates a tagged index.

            // read from the OSM-stream.
            var memoryData = new RouterDataSource <Edge>(new Graph <Edge>(), tagsIndex);
            var targetData = new GraphOsmStreamTarget(memoryData, interpreter, tagsIndex);

            targetData.RegisterSource(reader);
            targetData.Pull();

            // creates the edge router.
            var typedRouter = new TypedRouterEdge(
                memoryData, interpreter, new Dykstra());

            return(new Router(typedRouter)); // create the actual router.
        }
Example #18
0
        public static void TestResolved(RouterDataSource <CHEdgeData> data, int testCount, GeoCoordinateBox box)
        {
            var router = Router.CreateCHFrom(data, new CHRouter(), new OsmRoutingInterpreter());

            var performanceInfo = new PerformanceInfoConsumer("CHRouting");

            performanceInfo.Start();
            performanceInfo.Report("Routing {0} routes...", testCount);

            var successCount   = 0;
            var totalCount     = testCount;
            var latestProgress = -1.0f;

            while (testCount > 0)
            {
                var from = box.GenerateRandomIn();
                var to   = box.GenerateRandomIn();

                var fromPoint = router.Resolve(Vehicle.Car, from);
                var toPoint   = router.Resolve(Vehicle.Car, to);

                if (fromPoint != null && toPoint != null)
                {
                    var route = router.Calculate(Vehicle.Car, fromPoint, toPoint);
                    if (route != null)
                    {
                        successCount++;
                    }
                }
                testCount--;

                // report progress.
                var progress = (float)System.Math.Round(((double)(totalCount - testCount) / (double)totalCount) * 100);
                if (progress != latestProgress)
                {
                    OsmSharp.Logging.Log.TraceEvent("CHRouting", TraceEventType.Information,
                                                    "Routing... {0}%", progress);
                    latestProgress = progress;
                }
            }
            performanceInfo.Stop();

            OsmSharp.Logging.Log.TraceEvent("CHRouting", OsmSharp.Logging.TraceEventType.Information,
                                            string.Format("{0}/{1} routes successfull!", successCount, totalCount));
        }
        /// <summary>
        /// Returns a new router.
        /// </summary>
        /// <returns></returns>
        public override Router BuildRouter(IOsmRoutingInterpreter interpreter, string embeddedName)
        {
            var tagsIndex = new TagsIndex();

            // do the data processing.
            var data = new RouterDataSource<Edge>(new Graph<Edge>(), tagsIndex);
            var targetData = new GraphOsmStreamTarget(
                data, interpreter, tagsIndex, new Vehicle[] { Vehicle.Car }, false);
            var dataProcessorSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(string.Format(
                "OsmSharp.Routing.Test.data.{0}", embeddedName)));
            var sorter = new OsmStreamFilterSort();
            sorter.RegisterSource(dataProcessorSource);
            targetData.RegisterSource(sorter);
            targetData.Pull();

            return Router.CreateFrom(data, new Dykstra(), interpreter);
        }
Example #20
0
        /// <summary>
        /// Builds data source.
        /// </summary>
        /// <param name="interpreter"></param>
        /// <param name="embeddedString"></param>
        /// <returns></returns>
        public override IRoutingAlgorithmData <Edge> BuildData(IOsmRoutingInterpreter interpreter,
                                                               string embeddedString)
        {
            var tagsIndex = new TagsIndex();

            // do the data processing.
            var memoryData          = new RouterDataSource <Edge>(new Graph <Edge>(), tagsIndex);
            var targetData          = new GraphOsmStreamTarget(memoryData, interpreter, tagsIndex, null, false);
            var dataProcessorSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedString));
            var sorter = new OsmStreamFilterSort();

            sorter.RegisterSource(dataProcessorSource);
            targetData.RegisterSource(sorter);
            targetData.Pull();

            return(memoryData);
        }
Example #21
0
        public void TestGraphSerialize3()
        {
            const string embeddedString = "OsmSharp.Test.Unittests.test_network_real1.osm";

            // creates a new interpreter.
            var interpreter = new OsmRoutingInterpreter();

            // do the data processing.
            var graph = GraphOsmStreamTarget.Preprocess(new XmlOsmStreamSource(
                                                            Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedString)),
                                                        new TagsIndex(new MemoryMappedStream(new MemoryStream())), interpreter);

            // serialize.
            using (var stream = new MemoryStream())
            {
                graph.Serialize(stream, Edge.SizeUints, Edge.MapFromDelegate, Edge.MapToDelegate);

                // deserialize.
                stream.Seek(0, SeekOrigin.Begin);
                var graphDeserialized = RouterDataSource <Edge> .Deserialize(stream, Edge.SizeUints, Edge.MapFromDelegate, Edge.MapToDelegate, false);

                // compare.
                Assert.AreEqual(graph.VertexCount, graphDeserialized.VertexCount);
                for (uint vertex = 1; vertex <= graph.VertexCount; vertex++)
                {
                    float latitude1, longitude1, latitude2, longitude2;
                    if (graph.GetVertex(vertex, out latitude1, out longitude1) &&
                        graphDeserialized.GetVertex(vertex, out latitude2, out longitude2))
                    {
                        Assert.AreEqual(latitude1, latitude2, 0.000001);
                        Assert.AreEqual(longitude1, longitude2, 0.000001);
                    }
                    var edges             = graph.GetEdges(vertex).ToKeyValuePairs();
                    var edgesDeserialized = graphDeserialized.GetEdges(vertex).ToKeyValuePairs();
                    Assert.AreEqual(edges.Length, edgesDeserialized.Length);
                    for (int idx = 0; idx < edges.Length; idx++)
                    {
                        Assert.AreEqual(edges[idx].Value.Distance, edgesDeserialized[idx].Value.Distance);
                        Assert.AreEqual(edges[idx].Value.Tags, edgesDeserialized[idx].Value.Tags);
                        Assert.AreEqual(edges[idx].Value.Forward, edgesDeserialized[idx].Value.Forward);
                    }
                }
            }
        }
        /// <summary>
        /// Creates a router.
        /// </summary>
        /// <param name="interpreter"></param>
        /// <param name="manifestResourceName"></param>
        /// <returns></returns>
        protected override Router CreateRouter(IOsmRoutingInterpreter interpreter, string manifestResourceName)
        {
            TagsIndex tagsIndex = new TagsIndex();

            // do the data processing.
            var memoryData =
                new RouterDataSource<Edge>(new Graph<Edge>(), tagsIndex);
            var targetData = new GraphOsmStreamTarget(
                memoryData, interpreter, tagsIndex, null, false);
            var dataProcessorSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(manifestResourceName));
            var sorter = new OsmStreamFilterSort();
            sorter.RegisterSource(dataProcessorSource);
            targetData.RegisterSource(sorter);
            targetData.Pull();

            IRoutingAlgorithm<Edge> basicRouter = new Dykstra();
            return Router.CreateFrom(memoryData, basicRouter, interpreter);
        }
        /// <summary>
        /// Returns a new router.
        /// </summary>
        /// <returns></returns>
        public override Router BuildRouter(IOsmRoutingInterpreter interpreter, string embeddedName)
        {
            var tagsIndex = new TagsIndex();

            // do the data processing.
            var data       = new RouterDataSource <Edge>(new Graph <Edge>(), tagsIndex);
            var targetData = new GraphOsmStreamTarget(
                data, interpreter, tagsIndex, new Vehicle[] { Vehicle.Car }, false);
            var dataProcessorSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(string.Format(
                                                                              "OsmSharp.Routing.Test.data.{0}", embeddedName)));
            var sorter = new OsmStreamFilterSort();

            sorter.RegisterSource(dataProcessorSource);
            targetData.RegisterSource(sorter);
            targetData.Pull();

            return(Router.CreateFrom(data, new Dykstra(), interpreter));
        }
Example #24
0
        /// <summary>
        /// Deserializes the given stream into a routable graph.
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="lazy"></param>
        /// <param name="vehicles"></param>
        /// <returns></returns>
        protected override RouterDataSource <CHEdgeData> DoDeserialize(LimitedStream stream, bool lazy, IEnumerable <string> vehicles)
        {
            var routerDataSource = RouterDataSource <CHEdgeData> .Deserialize(stream, CHEdgeData.SizeUints, CHEdgeData.MapFromDelegate, CHEdgeData.MapToDelegate, !lazy);

            if (vehicles != null)
            {
                foreach (var vehicleName in vehicles)
                {
                    Vehicle vehicle;
                    if (!Vehicle.TryGetByUniqueName(vehicleName, out vehicle))
                    {
                        OsmSharp.Logging.Log.TraceEvent("CHEdgeSerializer", Logging.TraceEventType.Information,
                                                        string.Format("Vehicle profile {0} not found during serialization. It won't be supported by the router.", vehicleName));
                    }
                    routerDataSource.AddSupportedProfile(vehicle);
                }
            }
            return(routerDataSource);
        }
        /// <summary>
        /// Builds a raw router to compare against.
        /// </summary>
        /// <returns></returns>
        public void BuildDykstraRouter(string embeddedName,
                                       IOsmRoutingInterpreter interpreter)
        {
            var tagsIndex = new TagsIndex();

            // do the data processing.
            var data       = new RouterDataSource <Edge>(new Graph <Edge>(), tagsIndex);
            var targetData = new GraphOsmStreamTarget(
                data, interpreter, tagsIndex, new Vehicle[] { Vehicle.Car });
            var dataProcessorSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedName));
            var sorter = new OsmStreamFilterSort();

            sorter.RegisterSource(dataProcessorSource);
            targetData.RegisterSource(sorter);
            targetData.Pull();

            // initialize the router.
            _referenceRouter = Router.CreateFrom(data, new Dykstra(), interpreter);
        }
Example #26
0
        /// <summary>
        /// Tests routing from a serialized routing file.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="stream"></param>
        /// <param name="testCount"></param>
        public static void Test(string name, Stream stream, int testCount)
        {
            var vehicle = Vehicle.Pedestrian;

            var tagsIndex = new TagsIndex(); // creates a tagged index.

            // read from the OSM-stream.
            var reader      = new OsmSharp.Osm.PBF.Streams.PBFOsmStreamSource(stream);
            var interpreter = new OsmRoutingInterpreter();
            var data        = new RouterDataSource <Edge>(new Graph <Edge>(), tagsIndex);

            data.DropVertexIndex();
            var targetData = new GraphOsmStreamTarget(data, interpreter, tagsIndex);

            targetData.RegisterSource(reader);
            targetData.Pull();
            data.RebuildVertexIndex();

            RoutingTest.Test(data, vehicle, testCount);
        }
        /// <summary>
        /// Builds a raw data source.
        /// </summary>
        /// <returns></returns>
        public RouterDataSource <Edge> BuildDykstraDataSource(
            IOsmRoutingInterpreter interpreter, string embeddedName)
        {
            var tagsIndex = new TagsIndex();

            // do the data processing.
            var data       = new RouterDataSource <Edge>(new Graph <Edge>(), tagsIndex);
            var targetData = new ReferenceGraphTarget(
                data, interpreter, tagsIndex, new Vehicle[] { Vehicle.Car });
            var dataProcessorSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(string.Format(
                                                                              "OsmSharp.Test.Unittests.{0}", embeddedName)));
            var sorter = new OsmStreamFilterSort();

            sorter.RegisterSource(dataProcessorSource);
            targetData.RegisterSource(sorter);
            targetData.Pull();

            return(data);
        }
        /// <summary>
        /// Creates a router based on the resource.
        /// </summary>
        /// <param name="interpreter"></param>
        /// <param name="manifestResourceName"></param>
        /// <returns></returns>
        protected Router CreateReferenceRouter(IOsmRoutingInterpreter interpreter, string manifestResourceName)
        {
            TagsIndex tagsIndex = new TagsIndex();

            // do the data processing.
            var memoryData =
                new RouterDataSource <Edge>(new Graph <Edge>(), tagsIndex);
            var targetData = new GraphOsmStreamTarget(
                memoryData, interpreter, tagsIndex, null, false);
            var dataProcessorSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(manifestResourceName));
            var sorter = new OsmStreamFilterSort();

            sorter.RegisterSource(dataProcessorSource);
            targetData.RegisterSource(sorter);
            targetData.Pull();

            IRoutingAlgorithm <Edge> basicRouter = new Dykstra();

            return(Router.CreateFrom(memoryData, basicRouter, interpreter));
        }
Example #29
0
        /// <summary>
        /// Tests routing from a serialized routing file.
        /// </summary>
        /// <param name="data"></param>
        /// <param name="testCount"></param>
        public static void Test(RouterDataSource <CHEdgeData> data, int testCount)
        {
            var router = new CHRouter();

            var performanceInfo = new PerformanceInfoConsumer("CHRouting");

            performanceInfo.Start();
            performanceInfo.Report("Routing {0} routes...", testCount);

            var successCount   = 0;
            var totalCount     = testCount;
            var latestProgress = -1.0f;

            while (testCount > 0)
            {
                var from = (uint)OsmSharp.Math.Random.StaticRandomGenerator.Get().Generate(data.VertexCount - 1) + 1;
                var to   = (uint)OsmSharp.Math.Random.StaticRandomGenerator.Get().Generate(data.VertexCount - 1) + 1;

                var route = router.Calculate(data, from, to);

                if (route != null)
                {
                    successCount++;
                }
                testCount--;

                // report progress.
                var progress = (float)System.Math.Round(((double)(totalCount - testCount) / (double)totalCount) * 100);
                if (progress != latestProgress)
                {
                    OsmSharp.Logging.Log.TraceEvent("CHRouting", TraceEventType.Information,
                                                    "Routing... {0}%", progress);
                    latestProgress = progress;
                }
            }
            performanceInfo.Stop();

            OsmSharp.Logging.Log.TraceEvent("CHRouting", OsmSharp.Logging.TraceEventType.Information,
                                            string.Format("{0}/{1} routes successfull!", successCount, totalCount));
        }
Example #30
0
        /// <summary>
        /// Tests routing from a serialized routing file.
        /// </summary>
        /// <param name="data"></param>
        /// <param name="testCount"></param>
        public static void Test(RouterDataSource<CHEdgeData> data, int testCount)
        {
            var router = new CHRouter();

            var performanceInfo = new PerformanceInfoConsumer("CHRouting");
            performanceInfo.Start();
            performanceInfo.Report("Routing {0} routes...", testCount);

            var successCount = 0;
            var totalCount = testCount;
            var latestProgress = -1.0f;
            while (testCount > 0)
            {
                var from = (uint)OsmSharp.Math.Random.StaticRandomGenerator.Get().Generate(data.VertexCount - 1) + 1;
                var to = (uint)OsmSharp.Math.Random.StaticRandomGenerator.Get().Generate(data.VertexCount - 1) + 1;

                var route = router.Calculate(data, from, to);

                if (route != null)
                {
                    successCount++;
                }
                testCount--;

                // report progress.
                var progress = (float)System.Math.Round(((double)(totalCount - testCount) / (double)totalCount) * 100);
                if (progress != latestProgress)
                {
                    OsmSharp.Logging.Log.TraceEvent("CHRouting", TraceEventType.Information,
                        "Routing... {0}%", progress);
                    latestProgress = progress;
                }
            }
            performanceInfo.Stop();

            OsmSharp.Logging.Log.TraceEvent("CHRouting", OsmSharp.Logging.TraceEventType.Information,
                string.Format("{0}/{1} routes successfull!", successCount, totalCount));
        }
        /// <summary>
        /// Creates a router.
        /// </summary>
        /// <param name="interpreter"></param>
        /// <param name="manifestResourceName"></param>
        /// <returns></returns>
        protected override Router CreateRouter(IOsmRoutingInterpreter interpreter, string manifestResourceName)
        {
            TagsIndex tagsIndex = new TagsIndex();

            // do the data processing.
            var data = new RouterDataSource<CHEdgeData>(new DirectedGraph<CHEdgeData>(), tagsIndex);
            var targetData = new CHEdgeGraphOsmStreamTarget(
                data, interpreter, tagsIndex, Vehicle.Car);
            var dataProcessorSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(manifestResourceName));
            var sorter = new OsmStreamFilterSort();
            sorter.RegisterSource(dataProcessorSource);
            targetData.RegisterSource(sorter);
            targetData.Pull();

            // do the pre-processing part.
            var witnessCalculator = new DykstraWitnessCalculator();
            var preProcessor = new CHPreprocessor(data,
                new EdgeDifferenceContractedSearchSpace(data, witnessCalculator), witnessCalculator);
            preProcessor.Start();

            return Router.CreateCHFrom(data, new CHRouter(), interpreter);
        }
Example #32
0
        /// <summary>
        /// Tests routing from a serialized routing file.
        /// </summary>
        /// <param name="data"></param>
        /// <param name="box"></param>
        /// <param name="testCount"></param>
        public static void TestSerializedResolved(RouterDataSource <CHEdgeData> data,
                                                  GeoCoordinateBox box, int testCount = 100)
        {
            var successCount = 0;
            var totalCount   = testCount;

            var router = Router.CreateCHFrom(data, new CHRouter(), new OsmRoutingInterpreter());

            var performanceInfo = new PerformanceInfoConsumer("CHRouting");

            performanceInfo.Start();
            performanceInfo.Report("Routing {0} routes...", testCount);

            while (testCount > 0)
            {
                var point1 = router.Resolve(Vehicle.Car, box.GenerateRandomIn());
                var point2 = router.Resolve(Vehicle.Car, box.GenerateRandomIn());

                Route route = null;
                if (point1 != null && point2 != null)
                {
                    route = router.Calculate(Vehicle.Car, point1, point2);
                }

                if (route != null)
                {
                    successCount++;
                }
                testCount--;
            }

            performanceInfo.Stop();

            OsmSharp.Logging.Log.TraceEvent("CHRouting", OsmSharp.Logging.TraceEventType.Information,
                                            string.Format("{0}/{1} routes successfull!", successCount, totalCount));
        }
        public static Stream TestSerialization(string name, string pbfFile, RouterDataSource<CHEdgeData> data)
        {
            var testOutputFile = new FileInfo(@"test.routing");
            testOutputFile.Delete();
            var writeStream = testOutputFile.OpenWrite();

            var performanceInfo = new PerformanceInfoConsumer("CHSerializer");
            performanceInfo.Start();
            performanceInfo.Report("Writing to {0}...", testOutputFile.Name);

            TagsCollectionBase metaData = new TagsCollection();
            metaData.Add("some_key", "some_value");
            var routingSerializer = new CHEdgeSerializer();
            routingSerializer.Serialize(writeStream, data, metaData);

            writeStream.Dispose();

            OsmSharp.Logging.Log.TraceEvent("CHSerializer", OsmSharp.Logging.TraceEventType.Information,
                string.Format("Serialized file: {0}KB", testOutputFile.Length / 1024));

            performanceInfo.Stop();

            return testOutputFile.OpenRead();
        }
        public void RoutingRegressionTest4()
        {
            var interpreter = new OsmRoutingInterpreter();
            var tagsIndex   = new TagsIndex();

            // do the data processing.
            var memoryData          = new RouterDataSource <Edge>(new Graph <Edge>(), tagsIndex);
            var targetData          = new GraphOsmStreamTarget(memoryData, interpreter, tagsIndex);
            var dataProcessorSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Routing.Test.data.test_routing_regression1.osm"));
            var sorter = new OsmStreamFilterSort();

            sorter.RegisterSource(dataProcessorSource);
            targetData.RegisterSource(sorter);
            targetData.Pull();

            var basicRouter = new Dykstra();
            var router      = Router.CreateFrom(memoryData, basicRouter, interpreter);

            // resolve the three points in question.
            var point35                = new GeoCoordinate(51.01257, 4.000753);
            var point35ResolvedCar     = router.Resolve(Vehicle.Car, point35);
            var point35ResolvedBicycle = router.Resolve(Vehicle.Bicycle, point35);
        }
 /// <summary>
 /// Serializes the given graph.
 /// </summary>
 /// <param name="stream"></param>
 /// <param name="graph"></param>
 /// <param name="metaTags"></param>
 public void Serialize(Stream stream, RouterDataSource <TEdgeData> graph)
 {
     this.Serialize(stream, graph, new TagsCollection());
 }
Example #36
0
        /// <summary>
        /// Tests routing from a serialized file.
        /// </summary>
        /// <param name="stream"></param>
        public static void TestSerialized(Stream stream, bool lazy = true)
        {
            var routingSerializer = new RoutingDataSourceSerializer();
            var data = routingSerializer.Deserialize(stream, lazy);

            uint vertex = 1;
            uint significantVertices = 0;
            while(vertex < data.VertexCount)
            {
                var edges =  data.GetEdges(vertex).ToKeyValuePairs();
                if(edges.Length > 2)
                {
                    significantVertices++;
                }
                vertex++;
            }

            data.SortHilbert(1000);

            // copy.
            var graphCopy = new Graph<Edge>();
            graphCopy.CopyFrom(data);
            var dataCopy = new RouterDataSource<Edge>(graphCopy, data.TagsIndex);

            RoutingTest.Test(dataCopy, Vehicle.Pedestrian, 50);
        }
        public void RoutingSerializationRoutingTest()
        {
            const string embeddedString = "OsmSharp.Test.Unittests.test_network.osm";

            // create the tags index (and make sure it's serializable).
            var tagsIndex = new TagsIndex(new MemoryMappedStream(new MemoryStream()));

            // creates a new interpreter.
            var interpreter = new OsmRoutingInterpreter();

            // do the data processing.
            var original =
                new RouterDataSource <Edge>(new Graph <Edge>(), tagsIndex);
            var targetData = new GraphOsmStreamTarget(
                original, interpreter, tagsIndex, null, false);
            var dataProcessorSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedString));

            targetData.RegisterSource(dataProcessorSource);
            targetData.Pull();

            // create serializer.
            var routingSerializer = new RoutingDataSourceSerializer();

            // serialize/deserialize.
            TagsCollectionBase metaData = new TagsCollection();

            metaData.Add("some_key", "some_value");
            byte[] byteArray;
            using (var stream = new MemoryStream())
            {
                try
                {
                    routingSerializer.Serialize(stream, original, metaData);
                    byteArray = stream.ToArray();
                }
                catch (Exception)
                {
                    if (Debugger.IsAttached)
                    {
                        Debugger.Break();
                    }
                    throw;
                }
            }

            var deserializedVersion = routingSerializer.Deserialize(new MemoryStream(byteArray), out metaData);

            Assert.AreEqual(original.TagsIndex.Get(0), deserializedVersion.TagsIndex.Get(0));

            // try to do some routing on the deserialized version.
            var basicRouter = new Dykstra();
            var router      = Router.CreateFrom(deserializedVersion, basicRouter, interpreter);
            var source      = router.Resolve(Vehicle.Car,
                                             new GeoCoordinate(51.0578532, 3.7192229));
            var target = router.Resolve(Vehicle.Car,
                                        new GeoCoordinate(51.0576193, 3.7191801));

            // calculate the route.
            var route = router.Calculate(Vehicle.Car, source, target);

            Assert.IsNotNull(route);
            Assert.AreEqual(5, route.Segments.Length);

            float latitude, longitude;

            //deserializedVersion.GetVertex(20, out latitude, out longitude);
            Assert.AreEqual(51.0578537, route.Segments[0].Latitude, 0.00001);
            Assert.AreEqual(3.71922255, route.Segments[0].Longitude, 0.00001);
            Assert.AreEqual(RouteSegmentType.Start, route.Segments[0].Type);

            //deserializedVersion.GetVertex(21, out latitude, out longitude);
            Assert.AreEqual(51.0578537, route.Segments[1].Latitude, 0.00001);
            Assert.AreEqual(3.71956515, route.Segments[1].Longitude, 0.00001);
            Assert.AreEqual(RouteSegmentType.Along, route.Segments[1].Type);

            //deserializedVersion.GetVertex(16, out latitude, out longitude);
            Assert.AreEqual(51.05773, route.Segments[2].Latitude, 0.00001);
            Assert.AreEqual(3.719745, route.Segments[2].Longitude, 0.00001);
            Assert.AreEqual(RouteSegmentType.Along, route.Segments[2].Type);

            //deserializedVersion.GetVertex(22, out latitude, out longitude);
            Assert.AreEqual(51.05762, route.Segments[3].Latitude, 0.00001);
            Assert.AreEqual(3.71965766, route.Segments[3].Longitude, 0.00001);
            Assert.AreEqual(RouteSegmentType.Along, route.Segments[3].Type);

            deserializedVersion.GetVertex(23, out latitude, out longitude);
            Assert.AreEqual(51.05762, route.Segments[4].Latitude, 0.00001);
            Assert.AreEqual(3.71917963, route.Segments[4].Longitude, 0.00001);
            Assert.AreEqual(RouteSegmentType.Stop, route.Segments[4].Type);
        }
Example #38
0
        /// <summary>
        /// Tests routing from a serialized routing file.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="stream"></param>
        /// <param name="testCount"></param>
        public static void Test(string name, Stream stream, int testCount)
        {
            var vehicle = Vehicle.Pedestrian;

            var tagsIndex = new TagsIndex(); // creates a tagged index.

            // read from the OSM-stream.
            var reader = new OsmSharp.Osm.PBF.Streams.PBFOsmStreamSource(stream);
            var interpreter = new OsmRoutingInterpreter();
            var data = new RouterDataSource<Edge>(new Graph<Edge>(), tagsIndex);
            data.DropVertexIndex();
            var targetData = new GraphOsmStreamTarget(data, interpreter, tagsIndex);
            targetData.RegisterSource(reader);
            targetData.Pull();
            data.RebuildVertexIndex();

            RoutingTest.Test(data, vehicle, testCount);
        }
        /// <summary>
        /// Builds a raw router to compare against.
        /// </summary>
        /// <returns></returns>
        public void BuildDykstraRouter(string embeddedName,
            IOsmRoutingInterpreter interpreter)
        {
            var tagsIndex = new TagsIndex();

            // do the data processing.
            var data = new RouterDataSource<Edge>(new Graph<Edge>(), tagsIndex);
            var targetData = new GraphOsmStreamTarget(
                data, interpreter, tagsIndex, new Vehicle[] { Vehicle.Car });
            var dataProcessorSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedName));
            var sorter = new OsmStreamFilterSort();
            sorter.RegisterSource(dataProcessorSource);
            targetData.RegisterSource(sorter);
            targetData.Pull();

            // initialize the router.
            _referenceRouter = Router.CreateFrom(data, new Dykstra(), interpreter);
        }
Example #40
0
        /// <summary>
        /// Called after all data has been read.
        /// </summary>
        public override void OnAfterPull()
        {
            base.OnAfterPull();

            RouterDataSource<CHEdgeData> copy = null;
            if(_memoryMappedStream == null)
            {
                copy = new RouterDataSource<CHEdgeData>(new DirectedGraph<CHEdgeData>(),
                    (this.Graph as RouterDataSource<CHEdgeData>).TagsIndex);
            }
            else
            {
                copy = new RouterDataSource<CHEdgeData>(new DirectedGraph<CHEdgeData>(_memoryMappedStream, this.Graph.VertexCount,
                    CHEdgeData.MapFromDelegate, CHEdgeData.MapToDelegate, CHEdgeData.SizeUints),
                        (this.Graph as RouterDataSource<CHEdgeData>).TagsIndex);
            }
            copy.CopyFrom(this.Graph);
            copy.Trim();
            copy.Compress();

            var serializer = new CHEdgeSerializer();
            serializer.Serialize(_stream, copy as RouterDataSource<CHEdgeData>, new TagsCollection());
            _stream.Flush();
        }
Example #41
0
        /// <summary>
        /// Tests the edge matcher in combination with dykstra routing.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="highway"></param>
        /// <param name="vehicle"></param>
        /// <param name="matcher"></param>
        /// <param name="pointName"></param>
        /// <param name="notFound"></param>
        private void TestResolveOnEdgeSingle(string name, string highway,
                                             Vehicle vehicle, IEdgeMatcher matcher,
                                             string pointName, bool notFound)
        {
            var fromName = new GeoCoordinate(51.0003, 4.0007);
            var toName   = new GeoCoordinate(51.0003, 4.0008);

            var fromNoname = new GeoCoordinate(51.0, 4.0007);
            var toNoname   = new GeoCoordinate(51.0, 4.0008);

            TagsCollectionBase pointTags = new TagsCollection();

            pointTags["name"] = pointName;

            TagsCollectionBase tags = new TagsCollection();

            tags["highway"] = highway;
            //tags["name"] = name;

            var tagsIndex = new TagsIndex();

            // do the data processing.
            var  data          = new RouterDataSource <Edge>(new Graph <Edge>(), tagsIndex);
            uint vertexNoname1 = data.AddVertex((float)fromNoname.Latitude, (float)fromNoname.Longitude);
            uint vertexNoname2 = data.AddVertex((float)toNoname.Latitude, (float)toNoname.Longitude);

            data.AddEdge(vertexNoname1, vertexNoname2, new Edge()
            {
                Forward = true,
                Tags    = tagsIndex.Add(tags)
            }, null);
            tags            = new TagsCollection();
            tags["highway"] = highway;
            tags["name"]    = name;
            uint vertexName1 = data.AddVertex((float)fromName.Latitude, (float)fromName.Longitude);
            uint vertexName2 = data.AddVertex((float)toName.Latitude, (float)toName.Longitude);

            data.AddEdge(vertexName1, vertexName2, new Edge()
            {
                Forward = true,
                Tags    = tagsIndex.Add(tags)
            }, null);

            IRoutingInterpreter interpreter = new OsmRoutingInterpreter();

            // creates the data.
            IRoutingAlgorithm <Edge> router = new Dykstra();

            var nonameLocation = new GeoCoordinate(
                (fromNoname.Latitude + toNoname.Latitude) / 2.0,
                (fromNoname.Longitude + toNoname.Longitude) / 2.0);
//            var nameLocation = new GeoCoordinate(
//                (fromName.Latitude + toName.Latitude) / 2.0,
//                (fromName.Longitude + toName.Longitude) / 2.0);

            const float delta  = 0.01f;
            var         result = router.SearchClosest(data, interpreter, vehicle, nonameLocation, delta, matcher, pointTags, null);

            if (result.Distance < double.MaxValue)
            { // there is a result.
                Assert.IsFalse(notFound, "A result was found but was supposed not to  be found!");

                if (name == pointName)
                { // the name location was supposed to be found!
                    Assert.IsTrue(result.Vertex1 == vertexName1 || result.Vertex1 == vertexName2);
                    Assert.IsTrue(result.Vertex2 == vertexName1 || result.Vertex2 == vertexName2);
                }
                else
                { // the noname location was supposed to be found!
                    Assert.IsTrue(result.Vertex1 == vertexNoname1 || result.Vertex1 == vertexNoname2);
                    Assert.IsTrue(result.Vertex2 == vertexNoname1 || result.Vertex2 == vertexNoname2);
                }
                return;
            }
            Assert.IsTrue(notFound, "A result was not found but was supposed to be found!");
        }
        /// <summary>
        /// Tests preprocessing data from a PBF file.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pbfFile"></param>
        public static void TestSerialization(string name, string pbfFile)
        {
            var testFile = new FileInfo(string.Format(@".\TestFiles\{0}", pbfFile));

            var performanceInfo = new PerformanceInfoConsumer("SerializerFlatFile.Serialize", 2000);
            performanceInfo.Start();
            performanceInfo.Report("Pulling from {0}...", testFile.Name);

            var stream = testFile.OpenRead();
            var source = new PBFOsmStreamSource(stream);
            var progress = new OsmStreamFilterProgress();
            progress.RegisterSource(source);

            var testOutputFile = new FileInfo(@"test.routing");
            testOutputFile.Delete();
            var writeStream = testOutputFile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite);

            var tagsIndex = new TagsIndex();
            var interpreter = new OsmRoutingInterpreter();
            var graph = new RouterDataSource<Edge>(new Graph<Edge>(), tagsIndex);
            var routingSerializer = new RoutingDataSourceSerializer();

            var memoryMappedGraph = new Graph<Edge>(1024);
            var coordinates = new HugeCoordinateIndex(1024);
            var memoryData = new RouterDataSource<Edge>(memoryMappedGraph, tagsIndex);
            var targetData = new GraphOsmStreamTarget(memoryData, new OsmRoutingInterpreter(), tagsIndex, coordinates);
            targetData.RegisterSource(progress);
            targetData.Pull();

            performanceInfo.Stop();

            memoryData.Compress();

            performanceInfo = new PerformanceInfoConsumer("SerializerFlatFile.Serialize", 100000);
            performanceInfo.Start();
            performanceInfo.Report("Writing file for {0}...", testFile.Name);

            var metaData = new TagsCollection();
            metaData.Add("some_key", "some_value");
            routingSerializer.Serialize(writeStream, memoryData, metaData);
            stream.Dispose();
            writeStream.Dispose();

            OsmSharp.Logging.Log.TraceEvent("SerializerFlatFile", OsmSharp.Logging.TraceEventType.Information,
                string.Format("Serialized file: {0}KB", testOutputFile.Length / 1024));
            performanceInfo.Stop();

            ////performanceInfo = new PerformanceInfoConsumer("SerializerFlatFile.Serialize", 100000);
            ////performanceInfo.Start();
            ////performanceInfo.Report("Reading file for {0}...", testFile.Name);

            //var testInputFile = new FileInfo(@"test.routing");
            //var readStream = testInputFile.OpenRead();

            //RoutingTest.TestSerialized(readStream);

            ////var deserializedGraph = routingSerializer.Deserialize(readStream, false);

            ////readStream.Dispose();

            ////OsmSharp.Logging.Log.TraceEvent("SerializerFlatFile", OsmSharp.Logging.TraceEventType.Information,
            ////    string.Format("Read: {0}KB", testInputFile.Length / 1024));

            ////OsmSharp.Logging.Log.TraceEvent("SerializerFlatFile", Logging.TraceEventType.Information, deserializedGraph.ToInvariantString());

            ////performanceInfo.Stop();
        }
        /// <summary>
        /// Executes the CH contractions while verifying each step.
        /// </summary>
        /// <param name="stream"></param>
        public void DoTestCHSparseVerifiedContraction(Stream stream)
        {
            _pathsBeforeContraction = new Dictionary<uint, Dictionary<uint, Dictionary<uint, PathSegment<long>>>>();
            _interpreter = new OsmRoutingInterpreter();

            var tagsIndex = new TagsIndex();

            // do the data processing.
            _data = new RouterDataSource<CHEdgeData>(new DirectedGraph<CHEdgeData>(), tagsIndex);
            var targetData = new CHEdgeGraphOsmStreamTarget(
                _data, _interpreter, tagsIndex, Vehicle.Car);
            var dataProcessorSource = new XmlOsmStreamSource(stream);
            var sorter = new OsmStreamFilterSort();
            sorter.RegisterSource(dataProcessorSource);
            targetData.RegisterSource(sorter);
            targetData.Pull();

            //// do the pre-processing part.
            //var witnessCalculator = new DykstraWitnessCalculator();
            //var preProcessor = new CHPreProcessor(_data,
            //    new EdgeDifferenceContractedSearchSpace(_data, witnessCalculator), witnessCalculator);
            //preProcessor.OnBeforeContractionEvent += new CHPreProcessor.VertexDelegate(pre_processor_OnBeforeContractionEvent);
            //preProcessor.OnAfterContractionEvent += new CHPreProcessor.VertexDelegate(pre_processor_OnAfterContractionEvent);
            //preProcessor.Start();
        }
Example #44
0
        /// <summary>
        /// Tests the edge matcher in combination with dykstra routing.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="highway"></param>
        /// <param name="vehicle"></param>
        /// <param name="matcher"></param>
        /// <param name="pointName"></param>
        /// <param name="notFound"></param>
        private void TestResolveOnEdgeSingle(string name, string highway, 
            Vehicle vehicle, IEdgeMatcher matcher, 
            string pointName, bool notFound)
        {
            var fromName = new GeoCoordinate(51.0003, 4.0007);
            var toName = new GeoCoordinate(51.0003, 4.0008);

            var fromNoname = new GeoCoordinate(51.0, 4.0007);
            var toNoname = new GeoCoordinate(51.0, 4.0008);

            TagsCollectionBase pointTags = new TagsCollection();
            pointTags["name"] = pointName;

            TagsCollectionBase tags = new TagsCollection();
            tags["highway"] = highway;
            //tags["name"] = name;

            var tagsIndex = new TagsIndex();

            // do the data processing.
            var data = new RouterDataSource<Edge>(new Graph<Edge>(), tagsIndex);
            uint vertexNoname1 = data.AddVertex((float)fromNoname.Latitude, (float)fromNoname.Longitude);
            uint vertexNoname2 = data.AddVertex((float)toNoname.Latitude, (float)toNoname.Longitude);
            data.AddEdge(vertexNoname1, vertexNoname2, new Edge()
            {
                Forward = true,
                Tags = tagsIndex.Add(tags)
            }, null);
            tags = new TagsCollection();
            tags["highway"] = highway;
            tags["name"] = name;
            uint vertexName1 = data.AddVertex((float)fromName.Latitude, (float)fromName.Longitude);
            uint vertexName2 = data.AddVertex((float)toName.Latitude, (float)toName.Longitude);
            data.AddEdge(vertexName1, vertexName2, new Edge()
            {
                Forward = true,
                Tags = tagsIndex.Add(tags)
            }, null);

            IRoutingInterpreter interpreter = new OsmRoutingInterpreter();

            // creates the data.
            IRoutingAlgorithm<Edge> router = new Dykstra();

            var nonameLocation = new GeoCoordinate(
                (fromNoname.Latitude + toNoname.Latitude) / 2.0,
                (fromNoname.Longitude + toNoname.Longitude) / 2.0);
//            var nameLocation = new GeoCoordinate(
//                (fromName.Latitude + toName.Latitude) / 2.0,
//                (fromName.Longitude + toName.Longitude) / 2.0);

            const float delta = 0.01f;
            var result = router.SearchClosest(data, interpreter, vehicle, nonameLocation, delta, matcher, pointTags, null);
            if (result.Distance < double.MaxValue)
            { // there is a result.
                Assert.IsFalse(notFound, "A result was found but was supposed not to  be found!");

                if (name == pointName)
                { // the name location was supposed to be found!
                    Assert.IsTrue(result.Vertex1 == vertexName1 || result.Vertex1 == vertexName2);
                    Assert.IsTrue(result.Vertex2 == vertexName1 || result.Vertex2 == vertexName2);
                }
                else
                { // the noname location was supposed to be found!
                    Assert.IsTrue(result.Vertex1 == vertexNoname1 || result.Vertex1 == vertexNoname2);
                    Assert.IsTrue(result.Vertex2 == vertexNoname1 || result.Vertex2 == vertexNoname2);
                }
                return;
            }
            Assert.IsTrue(notFound, "A result was not found but was supposed to be found!");
        }
        public void RoutingSerializationRoutingTest()
        {
            const string embeddedString = "OsmSharp.Test.Unittests.test_network.osm";

            // create the tags index (and make sure it's serializable).
            var tagsIndex = new TagsIndex(new MemoryMappedStream(new MemoryStream()));

            // creates a new interpreter.
            var interpreter = new OsmRoutingInterpreter();

            // do the data processing.
            var original =
                new RouterDataSource<Edge>(new Graph<Edge>(), tagsIndex);
            var targetData = new GraphOsmStreamTarget(
                original, interpreter, tagsIndex, null, false);
            var dataProcessorSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedString));
            targetData.RegisterSource(dataProcessorSource);
            targetData.Pull();

            // create serializer.
            var routingSerializer = new RoutingDataSourceSerializer();

            // serialize/deserialize.
            TagsCollectionBase metaData = new TagsCollection();
            metaData.Add("some_key", "some_value");
            byte[] byteArray;
            using (var stream = new MemoryStream())
            {
                try
                {
                    routingSerializer.Serialize(stream, original, metaData);
                    byteArray = stream.ToArray();
                }
                catch (Exception)
                {
                    if (Debugger.IsAttached)
                    {
                        Debugger.Break();
                    }
                    throw;
                }
            }

            var deserializedVersion = routingSerializer.Deserialize(new MemoryStream(byteArray), out metaData);
            Assert.AreEqual(original.TagsIndex.Get(0), deserializedVersion.TagsIndex.Get(0));

            // try to do some routing on the deserialized version.
            var basicRouter = new Dykstra();
            var router = Router.CreateFrom(deserializedVersion, basicRouter, interpreter);
            var source = router.Resolve(Vehicle.Car,
                new GeoCoordinate(51.0578532, 3.7192229));
            var target = router.Resolve(Vehicle.Car,
                new GeoCoordinate(51.0576193, 3.7191801));

            // calculate the route.
            var route = router.Calculate(Vehicle.Car, source, target);
            Assert.IsNotNull(route);
            Assert.AreEqual(5, route.Segments.Length);

            float latitude, longitude;
            //deserializedVersion.GetVertex(20, out latitude, out longitude);
            Assert.AreEqual(51.0578537, route.Segments[0].Latitude, 0.00001);
            Assert.AreEqual(3.71922255, route.Segments[0].Longitude, 0.00001);
            Assert.AreEqual(RouteSegmentType.Start, route.Segments[0].Type);

            //deserializedVersion.GetVertex(21, out latitude, out longitude);
            Assert.AreEqual(51.0578537, route.Segments[1].Latitude, 0.00001);
            Assert.AreEqual(3.71956515, route.Segments[1].Longitude, 0.00001);
            Assert.AreEqual(RouteSegmentType.Along, route.Segments[1].Type);

            //deserializedVersion.GetVertex(16, out latitude, out longitude);
            Assert.AreEqual(51.05773, route.Segments[2].Latitude, 0.00001);
            Assert.AreEqual(3.719745, route.Segments[2].Longitude, 0.00001);
            Assert.AreEqual(RouteSegmentType.Along, route.Segments[2].Type);

            //deserializedVersion.GetVertex(22, out latitude, out longitude);
            Assert.AreEqual(51.05762, route.Segments[3].Latitude, 0.00001);
            Assert.AreEqual(3.71965766, route.Segments[3].Longitude, 0.00001);
            Assert.AreEqual(RouteSegmentType.Along, route.Segments[3].Type);

            deserializedVersion.GetVertex(23, out latitude, out longitude);
            Assert.AreEqual(51.05762, route.Segments[4].Latitude, 0.00001);
            Assert.AreEqual(3.71917963, route.Segments[4].Longitude, 0.00001);
            Assert.AreEqual(RouteSegmentType.Stop, route.Segments[4].Type);
        }
        public void RoutingRegressionTest10ResolvingReverse()
        {
            // build a graph to encode from.
            var tags = new TagsIndex();
            var graphDataSource = new RouterDataSource<Edge>(new Graph<Edge>(), tags);
            var vertex1 = graphDataSource.AddVertex(51.05849821468899f, 3.7240000000000000f);
            var vertex2 = graphDataSource.AddVertex(51.05849821468899f, 3.7254400000000000f);
            var vertex3 = graphDataSource.AddVertex(51.05849821468899f, 3.7225627899169926f);
            var edge = new Edge() // all edges are identical.
            {
                Distance = 100,
                Forward = true,
                Tags = tags.Add(new TagsCollection(
                    Tag.Create("highway", "tertiary"),
                    Tag.Create("oneway", "yes")))
            };
            var shape1 = new CoordinateArrayCollection<OsmSharp.Math.Geo.Simple.GeoCoordinateSimple>(
                new OsmSharp.Math.Geo.Simple.GeoCoordinateSimple[] {
                    new OsmSharp.Math.Geo.Simple.GeoCoordinateSimple()
                    {
                        Latitude = 1,
                        Longitude = 1
                    },
                    new OsmSharp.Math.Geo.Simple.GeoCoordinateSimple()
                    {
                        Latitude = 2,
                        Longitude = 2
                    }
                });
            var shape2 = new CoordinateArrayCollection<OsmSharp.Math.Geo.Simple.GeoCoordinateSimple>(
                new OsmSharp.Math.Geo.Simple.GeoCoordinateSimple[] {
                    new OsmSharp.Math.Geo.Simple.GeoCoordinateSimple()
                    {
                        Latitude = 3,
                        Longitude = 3
                    },
                    new OsmSharp.Math.Geo.Simple.GeoCoordinateSimple()
                    {
                        Latitude = 4,
                        Longitude = 4
                    }
                });
            graphDataSource.AddEdge(vertex1, vertex2, edge, shape1);
            graphDataSource.AddEdge(vertex3, vertex1, edge, shape2);

            // {RectF:[(3,71326552867889,51,048498214689),(3,73326552867889,51,068498214689)]}
            var edges =  graphDataSource.GetEdges(new GeoCoordinateBox(
                new GeoCoordinate(51.068498214689, 3.73326552867889),
                new GeoCoordinate(51.048498214689, 3.71326552867889)));

            while (edges.MoveNext())
            {
                if (edges.Vertex1 == 1 &&
                    edges.Vertex2 == 2)
                {
                    Assert.IsTrue(edges.EdgeData.Forward);
                    var shapes = edges.Intermediates.ToSimpleArray();
                    Assert.AreEqual(2, shapes.Length);
                    Assert.AreEqual(1, shapes[0].Latitude);
                    Assert.AreEqual(1, shapes[0].Longitude);
                    Assert.AreEqual(2, shapes[1].Latitude);
                    Assert.AreEqual(2, shapes[1].Longitude);
                }
                else if (edges.Vertex1 == 2 &&
                    edges.Vertex2 == 1)
                {
                    Assert.IsFalse(edges.EdgeData.Forward);
                    var shapes = edges.Intermediates.ToSimpleArray();
                    Assert.AreEqual(2, shapes.Length);
                    Assert.AreEqual(2, shapes[0].Latitude);
                    Assert.AreEqual(2, shapes[0].Longitude);
                    Assert.AreEqual(1, shapes[1].Latitude);
                    Assert.AreEqual(1, shapes[1].Longitude);
                }
                if (edges.Vertex1 == 1 &&
                    edges.Vertex2 == 3)
                {
                    Assert.IsFalse(edges.EdgeData.Forward);
                    var shapes = edges.Intermediates.ToSimpleArray();
                    Assert.AreEqual(2, shapes.Length);
                    Assert.AreEqual(4, shapes[0].Latitude);
                    Assert.AreEqual(4, shapes[0].Longitude);
                    Assert.AreEqual(3, shapes[1].Latitude);
                    Assert.AreEqual(3, shapes[1].Longitude);
                }
                else if (edges.Vertex1 == 3 &&
                    edges.Vertex2 == 1)
                {
                    Assert.IsTrue(edges.EdgeData.Forward);
                    var shapes = edges.Intermediates.ToSimpleArray();
                    Assert.AreEqual(2, shapes.Length);
                    Assert.AreEqual(3, shapes[0].Latitude);
                    Assert.AreEqual(3, shapes[0].Longitude);
                    Assert.AreEqual(4, shapes[1].Latitude);
                    Assert.AreEqual(4, shapes[1].Longitude);
                }
            }
        }
        public void RoutingRegressionTest9ResolvingReverse()
        {
            // build a graph to encode from.
            var tags = new TagsIndex();
            var graphDataSource = new RouterDataSource<Edge>(new Graph<Edge>(), tags);
            var vertex1 = graphDataSource.AddVertex(51.05849821468899f, 3.7240000000000000f);
            var vertex2 = graphDataSource.AddVertex(51.05849821468899f, 3.7254400000000000f);
            var vertex3 = graphDataSource.AddVertex(51.05849821468899f, 3.7225627899169926f);
            var edge = new Edge() // all edges are identical.
            {
                Distance = 100,
                Forward = true,
                Tags = tags.Add(new TagsCollection(
                    Tag.Create("highway", "tertiary"),
                    Tag.Create("oneway", "yes")))
            };
            graphDataSource.AddEdge(vertex1, vertex2, edge, null);
            graphDataSource.AddEdge(vertex3, vertex1, edge, null);

            // {RectF:[(3,71326552867889,51,048498214689),(3,73326552867889,51,068498214689)]}
            var edges =  graphDataSource.GetEdges(new GeoCoordinateBox(
                new GeoCoordinate(51.068498214689, 3.73326552867889),
                new GeoCoordinate(51.048498214689, 3.71326552867889)));

            while(edges.MoveNext())
            {
                if(edges.Vertex1 == 1 &&
                    edges.Vertex2 == 2)
                {
                    Assert.IsTrue(edges.EdgeData.Forward);
                }
                else if(edges.Vertex1 == 2 &&
                    edges.Vertex2 == 1)
                {
                    Assert.IsFalse(edges.EdgeData.Forward);
                }
                if (edges.Vertex1 == 1 &&
                    edges.Vertex2 == 3)
                {
                    Assert.IsFalse(edges.EdgeData.Forward);
                }
                else if (edges.Vertex1 == 3 &&
                    edges.Vertex2 == 1)
                {
                    Assert.IsTrue(edges.EdgeData.Forward);
                }
            }
        }
 /// <summary>
 /// Serializes the given graph and tags index to the given stream.
 /// </summary>
 /// <param name="stream"></param>
 /// <param name="graph"></param>
 protected abstract void DoSerialize(LimitedStream stream, RouterDataSource <TEdgeData> graph);
Example #49
0
        public static void TestResolved(RouterDataSource<CHEdgeData> data, int testCount, GeoCoordinateBox box)
        {
            var router = Router.CreateCHFrom(data, new CHRouter(), new OsmRoutingInterpreter());

            var performanceInfo = new PerformanceInfoConsumer("CHRouting");
            performanceInfo.Start();
            performanceInfo.Report("Routing {0} routes...", testCount);

            var successCount = 0;
            var totalCount = testCount;
            var latestProgress = -1.0f;
            while (testCount > 0)
            {
                var from = box.GenerateRandomIn();
                var to = box.GenerateRandomIn();

                var fromPoint = router.Resolve(Vehicle.Car, from);
                var toPoint = router.Resolve(Vehicle.Car, to);

                if (fromPoint != null && toPoint != null)
                {
                    var route = router.Calculate(Vehicle.Car, fromPoint, toPoint);
                    if (route != null)
                    {
                        successCount++;
                    }
                }
                testCount--;

                // report progress.
                var progress = (float)System.Math.Round(((double)(totalCount - testCount) / (double)totalCount) * 100);
                if (progress != latestProgress)
                {
                    OsmSharp.Logging.Log.TraceEvent("CHRouting", TraceEventType.Information,
                        "Routing... {0}%", progress);
                    latestProgress = progress;
                }
            }
            performanceInfo.Stop();

            OsmSharp.Logging.Log.TraceEvent("CHRouting", OsmSharp.Logging.TraceEventType.Information,
                string.Format("{0}/{1} routes successfull!", successCount, totalCount));
        }
Example #50
0
 /// <summary>
 /// Serializes the given graph and tags index to the given stream.
 /// </summary>
 /// <param name="stream"></param>
 /// <param name="graph"></param>
 protected override void DoSerialize(LimitedStream stream, RouterDataSource <CHEdgeData> graph)
 {
     graph.Serialize(stream, CHEdgeData.SizeUints, CHEdgeData.MapFromDelegate, CHEdgeData.MapToDelegate);
 }
Example #51
0
        /// <summary>
        /// Tests routing from a serialized routing file.
        /// </summary>
        /// <param name="data"></param>
        /// <param name="box"></param>
        /// <param name="testCount"></param>
        public static void TestSerializedResolved(RouterDataSource<CHEdgeData> data, 
			GeoCoordinateBox box, int testCount = 100)
        {
            var successCount = 0;
            var totalCount = testCount;

            var router = Router.CreateCHFrom(data, new CHRouter(), new OsmRoutingInterpreter());

            var performanceInfo = new PerformanceInfoConsumer("CHRouting");
            performanceInfo.Start();
            performanceInfo.Report("Routing {0} routes...", testCount);

            while (testCount > 0)
            {
                var point1 = router.Resolve(Vehicle.Car, box.GenerateRandomIn());
                var point2 = router.Resolve(Vehicle.Car, box.GenerateRandomIn());

                Route route = null;
                if (point1 != null && point2 != null)
                {
                    route = router.Calculate(Vehicle.Car, point1, point2);
                }

                if (route != null)
                {
                    successCount++;
                }
                testCount--;
            }

            performanceInfo.Stop();

            OsmSharp.Logging.Log.TraceEvent("CHRouting", OsmSharp.Logging.TraceEventType.Information,
                string.Format("{0}/{1} routes successfull!", successCount, totalCount));
        }
        public void RoutingRegressionTest2()
        {
            var interpreter = new OsmRoutingInterpreter();
            var tagsIndex = new TagsIndex();

            // do the data processing.
            var memoryData = new RouterDataSource<Edge>(new Graph<Edge>(), tagsIndex);
            var targetData = new GraphOsmStreamTarget(memoryData, interpreter, tagsIndex);
            var dataProcessorSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Routing.Test.data.test_network.osm"));
            var sorter = new OsmStreamFilterSort();
            sorter.RegisterSource(dataProcessorSource);
            targetData.RegisterSource(sorter);
            targetData.Pull();

            var basicRouter = new Dykstra();
            var router = Router.CreateFrom(memoryData, basicRouter, interpreter);

            // build coordinates list of resolved points.
            var testPoints = new List<GeoCoordinate>();
            testPoints.Add(new GeoCoordinate(51.0582204, 3.7193524));
            testPoints.Add(new GeoCoordinate(51.0582199, 3.7194002));

            testPoints.Add(new GeoCoordinate(51.0581727, 3.7195833));
            testPoints.Add(new GeoCoordinate(51.0581483, 3.7195553));

            testPoints.Add(new GeoCoordinate(51.0581883, 3.7196617));
            testPoints.Add(new GeoCoordinate(51.0581628, 3.7196889));

            // build a matrix of routes between all points.
            var referenceRoutes = new Route[testPoints.Count][];
            var permuationArray = new int[testPoints.Count];
            for (int fromIdx = 0; fromIdx < testPoints.Count; fromIdx++)
            {
                permuationArray[fromIdx] = fromIdx;
                referenceRoutes[fromIdx] = new Route[testPoints.Count];
                for (int toIdx = 0; toIdx < testPoints.Count; toIdx++)
                {
                    // create router from scratch.
                    router = Router.CreateFrom(
                        memoryData, basicRouter, interpreter);

                    // resolve points.
                    var from = router.Resolve(Vehicle.Car, testPoints[fromIdx]);
                    var to = router.Resolve(Vehicle.Car, testPoints[toIdx]);

                    // calculate route.
                    referenceRoutes[fromIdx][toIdx] = router.Calculate(Vehicle.Car, from, to);
                }
            }

            // resolve points in some order and compare the resulting routes.
            // they should be identical in length except for some numerical rounding errors.
            var enumerator = new PermutationEnumerable<int>(permuationArray);
            foreach (int[] permutation in enumerator)
            {
                // create router from scratch.
                router = Router.CreateFrom(memoryData, basicRouter, interpreter);

                // resolve in the order of the permutation.
                var resolvedPoints = new RouterPoint[permutation.Length];
                for (int idx = 0; idx < permutation.Length; idx++)
                {
                    resolvedPoints[permutation[idx]] = router.Resolve(Vehicle.Car, testPoints[permutation[idx]]);
                }

                for (int fromIdx = 0; fromIdx < testPoints.Count; fromIdx++)
                {
                    for (int toIdx = 0; toIdx < testPoints.Count; toIdx++)
                    {
                        // calculate route.
                        var route = router.Calculate(Vehicle.Car, resolvedPoints[fromIdx], resolvedPoints[toIdx]);

                        // TODO: changed the resolve accuracy to .5m. Make sure this is more accurate in the future.
                        Assert.AreEqual(referenceRoutes[fromIdx][toIdx].TotalDistance, route.TotalDistance, 1);
                    }
                }
            }
        }
        public void RoutingRegressionTest4()
        {
            var interpreter = new OsmRoutingInterpreter();
            var tagsIndex = new TagsIndex();

            // do the data processing.
            var memoryData = new RouterDataSource<Edge>(new Graph<Edge>(), tagsIndex);
            var targetData = new GraphOsmStreamTarget(memoryData, interpreter, tagsIndex);
            var dataProcessorSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Routing.Test.data.test_routing_regression1.osm"));
            var sorter = new OsmStreamFilterSort();
            sorter.RegisterSource(dataProcessorSource);
            targetData.RegisterSource(sorter);
            targetData.Pull();

            var basicRouter = new Dykstra();
            var router = Router.CreateFrom(memoryData, basicRouter, interpreter);

            // resolve the three points in question.
            var point35 = new GeoCoordinate(51.01257, 4.000753);
            var point35ResolvedCar = router.Resolve(Vehicle.Car, point35);
            var point35ResolvedBicycle = router.Resolve(Vehicle.Bicycle, point35);
        }
 /// <summary>
 /// Tests the CH serializer.
 /// </summary>
 /// <returns>A stream to the file that was serialized.</returns>
 public static Stream Test(RouterDataSource<CHEdgeData> data)
 {
     return CHEdgeGraphFileStreamTargetTests.TestSerialization("CHSerializer", "kempen-big.osm.pbf", data);
 }
        public void RoutingRegressionTest11ResolvingReverse()
        {
            // build a graph to encode from.
            var tags = new TagsIndex();
            var graphDataSource = new RouterDataSource<Edge>(new Graph<Edge>(), tags);
            var vertex1 = graphDataSource.AddVertex(51.05849821468899f, 3.7240000000000000f);
            var vertex2 = graphDataSource.AddVertex(51.05849821468899f, 3.7254400000000000f);
            var vertex3 = graphDataSource.AddVertex(51.05849821468899f, 3.7225627899169926f);
            var edgeData = new Edge() // all edges are identical.
            {
                Distance = 100,
                Forward = true,
                Tags = tags.Add(new TagsCollection(
                    Tag.Create("highway", "tertiary"),
                    Tag.Create("oneway", "yes")))
            };
            var shape1 = new CoordinateArrayCollection<OsmSharp.Math.Geo.Simple.GeoCoordinateSimple>(
                new OsmSharp.Math.Geo.Simple.GeoCoordinateSimple[] {
                    new OsmSharp.Math.Geo.Simple.GeoCoordinateSimple()
                    {
                        Latitude = 1,
                        Longitude = 1
                    },
                    new OsmSharp.Math.Geo.Simple.GeoCoordinateSimple()
                    {
                        Latitude = 2,
                        Longitude = 2
                    }
                });
            var shape2 = new CoordinateArrayCollection<OsmSharp.Math.Geo.Simple.GeoCoordinateSimple>(
                new OsmSharp.Math.Geo.Simple.GeoCoordinateSimple[] {
                    new OsmSharp.Math.Geo.Simple.GeoCoordinateSimple()
                    {
                        Latitude = 3,
                        Longitude = 3
                    },
                    new OsmSharp.Math.Geo.Simple.GeoCoordinateSimple()
                    {
                        Latitude = 4,
                        Longitude = 4
                    }
                });
            graphDataSource.AddEdge(vertex1, vertex2, edgeData, shape1);
            graphDataSource.AddEdge(vertex3, vertex1, edgeData, shape2);

            var edges =  new List<Edge<Edge>>(graphDataSource.GetEdges(1));
            Assert.AreEqual(2, edges.Count);
            foreach(var edge in edges)
            {
                if (edge.Neighbour == 2)
                {
                    Assert.AreEqual(true, edge.EdgeData.Forward);
                }
                else if(edge.Neighbour == 3)
                {
                    Assert.AreEqual(false, edge.EdgeData.Forward);
                }
            }

            edges = new List<Edge<Edge>>(graphDataSource.GetEdges(2));
            Assert.AreEqual(1, edges.Count);
            Assert.AreEqual(false, edges[0].EdgeData.Forward);

            edges = new List<Edge<Edge>>(graphDataSource.GetEdges(3));
            Assert.AreEqual(1, edges.Count);
            Assert.AreEqual(true, edges[0].EdgeData.Forward);
        }
        public void TestSparseRemoval1Routing()
        {
            // use one edge definition everywhere.
            var tagsIndex = new TagsIndex();
            var tags = new TagsCollection(new Tag("highway","residential"));
            var edge = new Edge();
            edge.Forward = true;
            edge.Tags = tagsIndex.Add(tags);

            var graph = new Graph<Edge>();
            uint vertex1 = graph.AddVertex(51.267797f, 4.8013623f);
            uint vertex2 = graph.AddVertex(51.267702f, 4.8013396f);
            uint vertex3 = graph.AddVertex(51.267592f, 4.8013024f);

            graph.AddEdge(vertex1, vertex2, edge, null);
            graph.AddEdge(vertex2, vertex3, edge, null);
            graph.AddEdge(vertex3, vertex2, edge, null);

            // save vertex coordinates for later use.
            float latitude, longitude;
            graph.GetVertex(vertex1, out latitude, out longitude);
            var vertex1Coordinate = new GeoCoordinate(latitude, longitude);
            graph.GetVertex(vertex2, out latitude, out longitude);
            var vertex2Coordinate = new GeoCoordinate(latitude, longitude);
            graph.GetVertex(vertex3, out latitude, out longitude);
            var vertex3Coordinate = new GeoCoordinate(latitude, longitude);

            // execute pre-processor.
            var preProcessor = new GraphSimplificationPreprocessor(graph);
            preProcessor.Start();

            // create router.
            var source = new RouterDataSource<Edge>(
                graph, tagsIndex);
            var router = Router.CreateFrom(source, new OsmRoutingInterpreter());

            // test some basic routing requests.
            // 1 -> 3: 1 -> 2 -> 3.
            var resolved1 = router.Resolve(Vehicle.Car, vertex1Coordinate);
            var resolved3 = router.Resolve(Vehicle.Car, vertex3Coordinate);
            var route = router.Calculate(Vehicle.Car, resolved1, resolved3);
            
            // verify the simple route result.
            Assert.IsNotNull(route);
            Assert.AreEqual(3, route.Segments.Length);
            Assert.AreEqual(vertex1Coordinate.Latitude, route.Segments[0].Latitude);
            Assert.AreEqual(vertex1Coordinate.Longitude, route.Segments[0].Longitude);
            Assert.AreEqual(vertex2Coordinate.Latitude, route.Segments[1].Latitude);
            Assert.AreEqual(vertex2Coordinate.Longitude, route.Segments[1].Longitude);
            Assert.AreEqual(vertex3Coordinate.Latitude, route.Segments[2].Latitude);
            Assert.AreEqual(vertex3Coordinate.Longitude, route.Segments[2].Longitude);

            // 1 -> 2: 1 -> 2.
            router = Router.CreateFrom(source, new OsmRoutingInterpreter());
            resolved1 = router.Resolve(Vehicle.Car, vertex1Coordinate);
            var resolved2 = router.Resolve(Vehicle.Car, vertex2Coordinate);
            route = router.Calculate(Vehicle.Car, resolved1, resolved2);

            // verify the simple route result.
            Assert.IsNotNull(route);
            Assert.AreEqual(2, route.Segments.Length);
            Assert.AreEqual(vertex1Coordinate.Latitude, route.Segments[0].Latitude);
            Assert.AreEqual(vertex1Coordinate.Longitude, route.Segments[0].Longitude);
            Assert.AreEqual(vertex2Coordinate.Latitude, route.Segments[1].Latitude);
            Assert.AreEqual(vertex2Coordinate.Longitude, route.Segments[1].Longitude);
        }
Example #57
0
        public void SortDirectedHilbertRealBigTest()
        {
            var embeddedString = "OsmSharp.Routing.Test.data.test_network_big.osm";
            var n = GraphExtensions.DefaultHilbertSteps;

            // do the data processing without preprocessing.
            var interpreter = new OsmRoutingInterpreter();
            var tagsIndex = new TagsIndex();
            var unsortedData = new RouterDataSource<CHEdgeData>(new DirectedGraph<CHEdgeData>(), tagsIndex);
            var targetData = new CHEdgeGraphOsmStreamTarget(unsortedData, interpreter, tagsIndex, OsmSharp.Routing.Vehicles.Vehicle.Car,
                (g) => { return null; });
            var dataProcessorSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedString));
            var sorter = new OsmStreamFilterSort();
            sorter.RegisterSource(dataProcessorSource);
            targetData.RegisterSource(sorter);
            targetData.Pull();

            // do the data processing with only hilbert sorting preprocessing.
            interpreter = new OsmRoutingInterpreter();
            tagsIndex = new TagsIndex();
            var data = new RouterDataSource<CHEdgeData>(new DirectedGraph<CHEdgeData>(), tagsIndex);
            targetData = new CHEdgeGraphOsmStreamTarget(data, interpreter, tagsIndex, OsmSharp.Routing.Vehicles.Vehicle.Car, (g) =>
            {
                return new HilbertSortingPreprocessor<CHEdgeData>(g);
            });
            dataProcessorSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedString));
            sorter = new OsmStreamFilterSort();
            sorter.RegisterSource(dataProcessorSource);
            targetData.RegisterSource(sorter);
            targetData.Pull();

            // test if sorted.
            for (uint sortedVertex = 1; sortedVertex < data.VertexCount; sortedVertex++)
            {
                var coordinate = data.GetLocation(sortedVertex);
                var neighbours = new Dictionary<GeoCoordinateSimple, CHEdgeData>();
                foreach (var edge in data.GetEdges(sortedVertex))
                {
                    neighbours[data.GetLocation(edge.Neighbour)] = edge.EdgeData;
                }

                for (uint unsortedVertex = 1; unsortedVertex < unsortedData.VertexCount; unsortedVertex++)
                {
                    var unsortedCoordinate = unsortedData.GetLocation(unsortedVertex);
                    if (coordinate.Latitude == unsortedCoordinate.Latitude &&
                        coordinate.Longitude == unsortedCoordinate.Longitude)
                    { // this is the same vertex, all vertices is the test network have different coordinates.
                        // compare their neighbours.
                        var unsortedNeighbours = new Dictionary<GeoCoordinateSimple, CHEdgeData>();
                        foreach (var edge in unsortedData.GetEdges(unsortedVertex))
                        {
                            unsortedNeighbours[unsortedData.GetLocation(edge.Neighbour)] = edge.EdgeData;
                        }
                        Assert.AreEqual(neighbours.Count, unsortedNeighbours.Count);
                        foreach (var neighbour in neighbours)
                        {
                            Assert.IsTrue(unsortedNeighbours.ContainsKey(neighbour.Key));
                            var value = unsortedNeighbours[neighbour.Key];
                            Assert.AreEqual(neighbour.Value.Weight, value.Weight);
                            Assert.AreEqual(neighbour.Value.Forward, value.Forward);
                            Assert.AreEqual(neighbour.Value.RepresentsNeighbourRelations, value.RepresentsNeighbourRelations);
                            Assert.AreEqual(neighbour.Value.Tags, value.Tags);
                        }
                        break;
                    }
                }
            }
        }