Пример #1
0
        /// <summary>
        /// Tests routing from a serialized file.
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="box"></param>
        /// <param name="lazy"></param>
        /// <param name="testCount"></param>
        public static void TestSerializedResolved(Stream stream, GeoCoordinateBox box, bool lazy = true, int testCount = 100)
        {
            var routingSerializer = new CHEdgeSerializer();
            var data = routingSerializer.Deserialize(stream, lazy);

            CHRoutingTest.TestResolved(data, testCount, box);
        }
Пример #2
0
        /// <summary>
        /// Tests routing from a serialized routing file.
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="testCount"></param>
        public static void TestSerializedResolved(Stream stream, bool lazy = true, int testCount = 100)
        {
            var routingSerializer = new CHEdgeSerializer();
            var data = routingSerializer.Deserialize(stream, lazy);

            CHRoutingTest.TestSerializedResolved(data, new GeoCoordinateBox(new GeoCoordinate(51.20190, 4.66540),
                                                                            new GeoCoordinate(51.30720, 4.89820)), testCount);
        }
        /// <summary>
        /// Tests preprocessing data from a PBF file.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pbfFile"></param>
        public static RouterDataSource <CHEdgeData> TestSerialization(string name, string pbfFile)
        {
            var testFilePath = Path.Combine(
                Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
                "TestFiles", pbfFile);
            //var testFilePath = @"/Users/xivk/work/OSM/bin/africa-latest.osm.pbf";
            var testFile = new FileInfo(testFilePath);
            var stream   = testFile.OpenRead();
            var source   = new OsmSharp.Osm.Streams.Filters.OsmStreamFilterProgress();

            source.RegisterSource(new PBFOsmStreamSource(stream));

            var testOutputFile = new FileInfo(@"test.routing");

            testOutputFile.Delete();
            Stream writeStream = testOutputFile.Open(FileMode.CreateNew, FileAccess.ReadWrite);

            var performanceInfo = new PerformanceInfoConsumer("CHSerializerFlatFile.Serialize");

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

            var data = CHEdgeGraphOsmStreamTarget.Preprocess(
                source, new TagsIndex(new MemoryMappedStream(new MemoryStream())),
                new OsmRoutingInterpreter(), Vehicle.Car);

            (data.Graph as DirectedGraph <CHEdgeData>).Compress(true);

            //var graphCopy = new DirectedGraph<CHEdgeData>();
            //graphCopy.CopyFrom(data);
            //data = new RouterDataSource<CHEdgeData>(graphCopy, data.TagsIndex);

            var metaData = new TagsCollection();

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

            routingSerializer.Serialize(writeStream, data, metaData);

            stream.Dispose();
            writeStream.Dispose();

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

            performanceInfo.Stop();

            performanceInfo = new PerformanceInfoConsumer("CHSerializerFlatFile.Deserialize");
            performanceInfo.Start();
            performanceInfo.Report("Deserializing again...");

            // open file again and read.
            writeStream = testOutputFile.OpenRead();
            var deserializedGraph = routingSerializer.Deserialize(writeStream, false);

            performanceInfo.Stop();
            return(data);
        }
Пример #4
0
        /// <summary>
        /// Tests routing from a serialized file.
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="lazy"></param>
        /// <param name="testCount"></param>
        public static void TestSerialized(Stream stream, bool lazy = true, int testCount = 100)
        {
            var routingSerializer = new CHEdgeSerializer();
            var data = routingSerializer.Deserialize(stream, lazy);

            //data.SortHilbert(1000);

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

            CHRoutingTest.Test(data, testCount);
        }
Пример #5
0
        /// <summary>
        /// Tests routing from a serialized routing file.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="stream"></param>
        /// <param name="box"></param>
        /// <param name="testCount"></param>
        public static void TestSerializedRouting(string name, Stream stream,
                                                 GeoCoordinateBox box, int testCount)
        {
            TagsCollectionBase metaData = null;
            var routingSerializer       = new CHEdgeSerializer();
            var graphDeserialized       = routingSerializer.Deserialize(
                stream, out metaData, false);

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

            CHSerializedRoutingTest.TestRouting(router, box, testCount);
        }
Пример #6
0
        /// <summary>
        /// Tests routing between two points and the associated instructions.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="stream"></param>
        /// <param name="from"></param>
        /// <param name="to"></param>
        public static void TestSerializeRoutingInstrictions(string name, Stream stream,
                                                            GeoCoordinate from, GeoCoordinate to)
        {
            PerformanceInfoConsumer performanceInfo = new PerformanceInfoConsumer("CHSerializedRouting");

            performanceInfo.Start();
            performanceInfo.Report("Routing & generating instructions...");

            TagsCollectionBase metaData = null;
            var routingSerializer       = new CHEdgeSerializer();
            var graphDeserialized       = routingSerializer.Deserialize(
                stream, out metaData, true);

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

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

            var instructions = new List <Instruction>();

            if (fromPoint != null && toPoint != null)
            {
                Route route = router.Calculate(Vehicle.Car, fromPoint, toPoint);
                if (route != null)
                {
                    instructions = InstructionGenerator.Generate(route, interpreter);
                }
            }

            performanceInfo.Stop();

            if (instructions.Count == 0)
            {
                OsmSharp.Logging.Log.TraceEvent("CHSerializedRouting", OsmSharp.Logging.TraceEventType.Information,
                                                "Routing unsuccesfull!");
            }
            else
            {
                foreach (Instruction instruction in instructions)
                {
                    OsmSharp.Logging.Log.TraceEvent("CHSerializedRouting", OsmSharp.Logging.TraceEventType.Information,
                                                    instruction.Text);
                }
            }
        }
Пример #7
0
        public void RoutingSerializationCHEdgeData()
        {
            const string embeddedString = "OsmSharp.Test.Unittests.test_network_real1.osm";

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

            // load the network.
            var referenceNetwork = CHEdgeGraphOsmStreamTarget.Preprocess(new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedString)), tagsIndex,
                new OsmRoutingInterpreter(), Vehicle.Car);

            // serialize network.
            var routingSerializer = new CHEdgeSerializer();
            TagsCollectionBase metaData = new TagsCollection();
            metaData.Add("some_key", "some_value");
            using (var stream = new MemoryStream())
            {
                routingSerializer.Serialize(stream, referenceNetwork, metaData);

                var network = routingSerializer.Deserialize(stream, out metaData);
                // compare networks.
                Assert.IsNotNull(network);
                Assert.AreEqual(referenceNetwork.VertexCount, network.VertexCount);
                for (uint vertex = 1; vertex < referenceNetwork.VertexCount; vertex++)
                {
                    float referenceLatitude, referenceLongitude, latitude, longitude;
                    Assert.IsTrue(referenceNetwork.GetVertex(vertex, out referenceLatitude, out referenceLongitude));
                    Assert.IsTrue(network.GetVertex(vertex, out latitude, out longitude));
                    Assert.AreEqual(referenceLatitude, latitude);
                    Assert.AreEqual(referenceLongitude, longitude);

                    var referenceEdges = referenceNetwork.GetEdges(vertex).ToKeyValuePairsAndShapes();
                    var edges =  network.GetEdges(vertex).ToKeyValuePairsAndShapes();
                    Assert.AreEqual(referenceEdges.Length, edges.Length);
                    for (int idx = 0; idx < referenceEdges.Length; idx++)
                    {
                        var referenceEdge = referenceEdges[idx];
                        // find the same edge in the new arcs.
                        var edge = edges.First((x) => { return x.Key == referenceEdges[idx].Key && x.Value.Key.Equals(referenceEdges[idx].Value.Key); });

                        Assert.AreEqual(referenceEdge.Key, edge.Key);
                        Assert.AreEqual(referenceEdge.Value.Key.Meta, edge.Value.Key.Meta);
                        Assert.AreEqual(referenceEdge.Value.Key.Value, edge.Value.Key.Value);
                        Assert.AreEqual(referenceEdge.Value.Key.Weight, edge.Value.Key.Weight);
                        Assert.AreEqual(referenceEdge.Value.Key.RepresentsNeighbourRelations, edge.Value.Key.RepresentsNeighbourRelations);
                        Assert.AreEqual(referenceEdge.Value.Key.Tags, edge.Value.Key.Tags);
                        var referenceCoordinates = referenceEdge.Value.Value;
                        var coordinates = edge.Value.Value;

                        if (referenceCoordinates == null)
                        { // reference shape is null, shape is null.
                            Assert.IsNull(coordinates);
                        }
                        else
                        { // reference shape is not null compare them.
                            Assert.IsNotNull(coordinates);
                            referenceCoordinates.Reset();
                            coordinates.Reset();
                            while (referenceCoordinates.MoveNext())
                            {
                                Assert.IsTrue(coordinates.MoveNext());

                                Assert.AreEqual(referenceCoordinates.Latitude, coordinates.Latitude);
                                Assert.AreEqual(referenceCoordinates.Longitude, coordinates.Longitude);
                            }
                            Assert.IsFalse(coordinates.MoveNext());
                        }

                        // check tags.
                        if (!referenceEdge.Value.Key.IsContracted)
                        {
                            var referenceTags = referenceNetwork.TagsIndex.Get(referenceEdge.Value.Key.Tags);
                            var tags = network.TagsIndex.Get(edge.Value.Key.Tags);
                            if (referenceTags == null)
                            { // other tags also have to be null.
                                Assert.IsNull(tags);
                            }
                            else
                            { // contents need to be the same.
                                Assert.AreEqual(referenceTags.Count, tags.Count);
                                foreach (var referenceTag in referenceTags)
                                {
                                    Assert.IsTrue(tags.ContainsKeyValue(referenceTag.Key, referenceTag.Value));
                                }
                            }
                        }
                    }
                }
            }
        }
        public void RoutingSerializationCHEdgeData()
        {
            const string embeddedString = "OsmSharp.Test.Unittests.test_network_real1.osm";

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

            // load the network.
            var referenceNetwork = CHEdgeGraphOsmStreamTarget.Preprocess(new XmlOsmStreamSource(
                                                                             Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedString)), tagsIndex,
                                                                         new OsmRoutingInterpreter(), Vehicle.Car);

            // serialize network.
            var routingSerializer       = new CHEdgeSerializer();
            TagsCollectionBase metaData = new TagsCollection();

            metaData.Add("some_key", "some_value");
            using (var stream = new MemoryStream())
            {
                routingSerializer.Serialize(stream, referenceNetwork, metaData);

                var network = routingSerializer.Deserialize(stream, out metaData);
                // compare networks.
                Assert.IsNotNull(network);
                Assert.AreEqual(referenceNetwork.VertexCount, network.VertexCount);
                for (uint vertex = 1; vertex < referenceNetwork.VertexCount; vertex++)
                {
                    float referenceLatitude, referenceLongitude, latitude, longitude;
                    Assert.IsTrue(referenceNetwork.GetVertex(vertex, out referenceLatitude, out referenceLongitude));
                    Assert.IsTrue(network.GetVertex(vertex, out latitude, out longitude));
                    Assert.AreEqual(referenceLatitude, latitude);
                    Assert.AreEqual(referenceLongitude, longitude);

                    var referenceEdges = referenceNetwork.GetEdges(vertex).ToKeyValuePairsAndShapes();
                    var edges          = network.GetEdges(vertex).ToKeyValuePairsAndShapes();
                    Assert.AreEqual(referenceEdges.Length, edges.Length);
                    for (int idx = 0; idx < referenceEdges.Length; idx++)
                    {
                        var referenceEdge = referenceEdges[idx];
                        // find the same edge in the new arcs.
                        var edge = edges.First((x) => { return(x.Key == referenceEdges[idx].Key && x.Value.Key.Equals(referenceEdges[idx].Value.Key)); });

                        Assert.AreEqual(referenceEdge.Key, edge.Key);
                        Assert.AreEqual(referenceEdge.Value.Key.Meta, edge.Value.Key.Meta);
                        Assert.AreEqual(referenceEdge.Value.Key.Value, edge.Value.Key.Value);
                        Assert.AreEqual(referenceEdge.Value.Key.Weight, edge.Value.Key.Weight);
                        Assert.AreEqual(referenceEdge.Value.Key.RepresentsNeighbourRelations, edge.Value.Key.RepresentsNeighbourRelations);
                        Assert.AreEqual(referenceEdge.Value.Key.Tags, edge.Value.Key.Tags);
                        var referenceCoordinates = referenceEdge.Value.Value;
                        var coordinates          = edge.Value.Value;

                        if (referenceCoordinates == null)
                        { // reference shape is null, shape is null.
                            Assert.IsNull(coordinates);
                        }
                        else
                        { // reference shape is not null compare them.
                            Assert.IsNotNull(coordinates);
                            referenceCoordinates.Reset();
                            coordinates.Reset();
                            while (referenceCoordinates.MoveNext())
                            {
                                Assert.IsTrue(coordinates.MoveNext());

                                Assert.AreEqual(referenceCoordinates.Latitude, coordinates.Latitude);
                                Assert.AreEqual(referenceCoordinates.Longitude, coordinates.Longitude);
                            }
                            Assert.IsFalse(coordinates.MoveNext());
                        }

                        // check tags.
                        if (!referenceEdge.Value.Key.IsContracted)
                        {
                            var referenceTags = referenceNetwork.TagsIndex.Get(referenceEdge.Value.Key.Tags);
                            var tags          = network.TagsIndex.Get(edge.Value.Key.Tags);
                            if (referenceTags == null)
                            { // other tags also have to be null.
                                Assert.IsNull(tags);
                            }
                            else
                            { // contents need to be the same.
                                Assert.AreEqual(referenceTags.Count, tags.Count);
                                foreach (var referenceTag in referenceTags)
                                {
                                    Assert.IsTrue(tags.ContainsKeyValue(referenceTag.Key, referenceTag.Value));
                                }
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Tests preprocessing data from a PBF file.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pbfFile"></param>
        public static RouterDataSource<CHEdgeData> TestSerialization(string name, string pbfFile)
        {
            var testFilePath = Path.Combine (
                Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
                "TestFiles", pbfFile);
            //var testFilePath = @"/Users/xivk/work/OSM/bin/africa-latest.osm.pbf";
            var testFile = new FileInfo(testFilePath);
            var stream = testFile.OpenRead();
            var source = new OsmSharp.Osm.Streams.Filters.OsmStreamFilterProgress();
            source.RegisterSource(new PBFOsmStreamSource(stream));

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

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

            var data = CHEdgeGraphOsmStreamTarget.Preprocess(
                source, new TagsIndex(new MemoryMappedStream(new MemoryStream())),
                new OsmRoutingInterpreter(), Vehicle.Car);

            (data.Graph as DirectedGraph<CHEdgeData>).Compress(true);

            //var graphCopy = new DirectedGraph<CHEdgeData>();
            //graphCopy.CopyFrom(data);
            //data = new RouterDataSource<CHEdgeData>(graphCopy, data.TagsIndex);

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

            stream.Dispose();
            writeStream.Dispose();

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

            performanceInfo.Stop();

            performanceInfo = new PerformanceInfoConsumer("CHSerializerFlatFile.Deserialize");
            performanceInfo.Start();
            performanceInfo.Report("Deserializing again...");

            // open file again and read.
            writeStream = testOutputFile.OpenRead();
            var deserializedGraph = routingSerializer.Deserialize(writeStream, false);

            performanceInfo.Stop();
            return data;
        }
Пример #10
0
        /// <summary>
        /// Tests routing from a serialized file.
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="box"></param>
        /// <param name="lazy"></param>
        /// <param name="testCount"></param>
        public static void TestSerializedResolved(Stream stream, GeoCoordinateBox box, bool lazy = true, int testCount = 100)
        {
            var routingSerializer = new CHEdgeSerializer();
            var data = routingSerializer.Deserialize(stream, lazy);

            CHRoutingTest.TestResolved(data, testCount, box);
        }
Пример #11
0
        /// <summary>
        /// Tests routing from a serialized routing file.
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="testCount"></param>
        public static void TestSerializedResolved(Stream stream, bool lazy = true, int testCount = 100)
        {
            var routingSerializer = new CHEdgeSerializer();
            var data = routingSerializer.Deserialize(stream, lazy);

            CHRoutingTest.TestSerializedResolved(data, new GeoCoordinateBox(new GeoCoordinate(51.20190, 4.66540),
                new GeoCoordinate(51.30720, 4.89820)), testCount);
        }
Пример #12
0
        /// <summary>
        /// Tests routing from a serialized file.
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="lazy"></param>
        /// <param name="testCount"></param>
        public static void TestSerialized(Stream stream, bool lazy = true, int testCount = 100)
        {
            var routingSerializer = new CHEdgeSerializer();
            var data = routingSerializer.Deserialize(stream, lazy);

            //data.SortHilbert(1000);

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

            CHRoutingTest.Test(data, testCount);
        }
        /// <summary>
        /// Loads a new instance.
        /// </summary>
        /// <param name="apiConfiguration"></param>
        /// <param name="instanceConfiguration"></param>
        /// <returns></returns>
        private static bool LoadInstance(ApiConfiguration apiConfiguration, InstanceConfiguration instanceConfiguration)
        {
            try
            {
                // get graph configuration.
                var graph       = instanceConfiguration.Graph;
                var type        = instanceConfiguration.Type;
                var format      = instanceConfiguration.Format;
                var vehicleName = instanceConfiguration.Vehicle;

                try
                {
                    // create routing instance.
                    OsmSharp.Logging.Log.TraceEvent("Bootstrapper", OsmSharp.Logging.TraceEventType.Information,
                                                    string.Format("Creating {0} instance...", instanceConfiguration.Name));
                    Router router = null;
                    RouterDataSource <Edge> data = null;

                    var graphFile = new FileInfo(graph);
                    switch (type)
                    {
                    case "raw":
                        switch (format)
                        {
                        case "osm-xml":
                            using (var graphStream = graphFile.OpenRead())
                            {
                                data = OsmSharp.Routing.Osm.Streams.GraphOsmStreamTarget.Preprocess(
                                    new XmlOsmStreamSource(graphStream), new OsmRoutingInterpreter());
                                router = Router.CreateFrom(data, new OsmRoutingInterpreter());
                            }
                            break;

                        case "osm-pbf":
                            using (var graphStream = graphFile.OpenRead())
                            {
                                data = OsmSharp.Routing.Osm.Streams.GraphOsmStreamTarget.Preprocess(
                                    new PBFOsmStreamSource(graphStream), new OsmRoutingInterpreter());
                                router = Router.CreateFrom(data, new OsmRoutingInterpreter());
                            }
                            break;

                        default:
                            throw new Exception(string.Format("Invalid format {0} for type {1}.",
                                                              format, type));
                        }
                        break;

                    case "contracted":
                        // check for GTFS-feeds and give warning if they are there.
                        if (instanceConfiguration.Feeds != null && instanceConfiguration.Feeds.Count > 0)
                        {     // ... oeps a feed and a contracted network are not supported for now.
                            OsmSharp.Logging.Log.TraceEvent("ApiBootstrapper", OsmSharp.Logging.TraceEventType.Warning,
                                                            "NotSupported: GTFS and contracted graphs cannot (yet) be combined.");
                        }

                        switch (format)
                        {
                        case "osm-xml":
                            if (string.IsNullOrWhiteSpace(vehicleName))
                            {         // invalid configuration.
                                throw new Exception("Invalid configuration, a vehicle type is required when building contracted graphs on-the-fly.");
                            }
                            using (var graphStream = graphFile.OpenRead())
                            {
                                var graphSource = new XmlOsmStreamSource(graphStream);
                                router = Router.CreateCHFrom(graphSource, new OsmRoutingInterpreter(), Vehicle.GetByUniqueName(vehicleName));
                            }
                            break;

                        case "osm-pbf":
                            if (string.IsNullOrWhiteSpace(vehicleName))
                            {         // invalid configuration.
                                throw new Exception("Invalid configuration, a vehicle type is required when building contracted graphs on-the-fly.");
                            }
                            using (var graphStream = graphFile.OpenRead())
                            {
                                var graphSource = new PBFOsmStreamSource(graphStream);
                                router = Router.CreateCHFrom(graphSource, new OsmRoutingInterpreter(), Vehicle.GetByUniqueName(vehicleName));
                            }
                            break;

                        case "flat":
                            var mobileRoutingSerializer = new CHEdgeSerializer();
                            // keep this stream open, it is used while routing!
                            var mobileGraphInstance = mobileRoutingSerializer.Deserialize(graphFile.OpenRead(), false);
                            router = Router.CreateCHFrom(mobileGraphInstance, new CHRouter(), new OsmRoutingInterpreter());
                            break;

                        default:
                            throw new Exception(string.Format("Invalid format {0} for type {1}.",
                                                              format, type));
                        }
                        break;

                    case "simple":
                        switch (format)
                        {
                        case "flat":
                            using (var graphStream = graphFile.OpenRead())
                            {
                                var routingSerializer = new RoutingDataSourceSerializer();
                                data   = routingSerializer.Deserialize(graphStream);
                                router = Router.CreateFrom(data, new Dykstra(), new OsmRoutingInterpreter());
                            }
                            break;

                        default:
                            throw new Exception(string.Format("Invalid format {0} for type {1}.",
                                                              format, type));
                        }
                        break;
                    }

                    if (instanceConfiguration.Feeds != null && instanceConfiguration.Feeds.Count > 0)
                    {     // transit-data use the transit-api.
                        if (instanceConfiguration.Feeds.Count > 1)
                        { // for now only one feed at a time is supported.
                            OsmSharp.Logging.Log.TraceEvent("ApiBootstrapper", OsmSharp.Logging.TraceEventType.Warning,
                                                            "NotSupported: Only one GTFS-feed at a time is supported.");
                        }

                        var feed                    = instanceConfiguration.Feeds[0];
                        var reader                  = new GTFSReader <GTFSFeed>(false);
                        var gtfsFeed                = reader.Read <GTFSFeed>(new GTFSDirectorySource(feed.Path));
                        var connectionsDb           = new GTFSConnectionsDb(gtfsFeed);
                        var multimodalConnectionsDb = new MultimodalConnectionsDb(data, connectionsDb,
                                                                                  new OsmRoutingInterpreter(), Vehicle.Pedestrian);

                        lock (_sync)
                        {
                            OsmSharp.Service.Routing.ApiBootstrapper.AddOrUpdate(instanceConfiguration.Name,
                                                                                 new MultimodalApi(multimodalConnectionsDb));
                        }
                    }
                    else
                    { // no transit-data just use the regular routing api implementation.
                        lock (_sync)
                        {
                            OsmSharp.Service.Routing.ApiBootstrapper.AddOrUpdate(instanceConfiguration.Name, router);
                        }
                    }

                    OsmSharp.Logging.Log.TraceEvent("Bootstrapper", OsmSharp.Logging.TraceEventType.Information,
                                                    string.Format("Instance {0} created successfully!", instanceConfiguration.Name));
                }
                catch (Exception ex)
                {
                    OsmSharp.Logging.Log.TraceEvent("Bootstrapper", OsmSharp.Logging.TraceEventType.Error,
                                                    string.Format("Exception occured while creating instance {0}:{1}",
                                                                  instanceConfiguration.Name, ex.ToInvariantString()));
                    throw;
                }
                return(true);
            }
            catch
            {
                return(false);
            }
        }
        /// <summary>
        /// Loads a new instance.
        /// </summary>
        /// <param name="apiConfiguration"></param>
        /// <param name="instanceConfiguration"></param>
        /// <returns></returns>
        private static bool LoadInstance(ApiConfiguration apiConfiguration, InstanceConfiguration instanceConfiguration)
        {
            try
            {
                // get graph configuration.
                var graph = instanceConfiguration.Graph;
                var type = instanceConfiguration.Type;
                var format = instanceConfiguration.Format;
                var vehicleName = instanceConfiguration.Vehicle;

                try
                {
                    // create routing instance.
                    OsmSharp.Logging.Log.TraceEvent("Bootstrapper", OsmSharp.Logging.TraceEventType.Information,
                        string.Format("Creating {0} instance...", instanceConfiguration.Name));
                    Router router = null;
                    RouterDataSource<Edge> data = null;

                    var graphFile = new FileInfo(graph);
                    switch (type)
                    {
                        case "raw":
                            switch (format)
                            {
                                case "osm-xml":
                                    using(var graphStream = graphFile.OpenRead())
                                    {
                                        data = OsmSharp.Routing.Osm.Streams.GraphOsmStreamTarget.Preprocess(
                                            new XmlOsmStreamSource(graphStream), new OsmRoutingInterpreter());
                                        router = Router.CreateFrom(data, new OsmRoutingInterpreter());
                                    }
                                    break;
                                case "osm-pbf":
                                    using (var graphStream = graphFile.OpenRead())
                                    {
                                        data = OsmSharp.Routing.Osm.Streams.GraphOsmStreamTarget.Preprocess(
                                            new PBFOsmStreamSource(graphStream), new OsmRoutingInterpreter());
                                        router = Router.CreateFrom(data, new OsmRoutingInterpreter());
                                    }
                                    break;
                                default:
                                    throw new Exception(string.Format("Invalid format {0} for type {1}.",
                                        format, type));
                            }
                            break;
                        case "contracted":
                            // check for GTFS-feeds and give warning if they are there.
                            if(instanceConfiguration.Feeds != null && instanceConfiguration.Feeds.Count > 0)
                            { // ... oeps a feed and a contracted network are not supported for now.
                                OsmSharp.Logging.Log.TraceEvent("ApiBootstrapper", OsmSharp.Logging.TraceEventType.Warning,
                                    "NotSupported: GTFS and contracted graphs cannot (yet) be combined.");
                            }

                            switch(format)
                            {
                                case "osm-xml":
                                    if (string.IsNullOrWhiteSpace(vehicleName))
                                    { // invalid configuration.
                                        throw new Exception("Invalid configuration, a vehicle type is required when building contracted graphs on-the-fly.");
                                    }
                                    using (var graphStream = graphFile.OpenRead())
                                    {
                                        var graphSource = new XmlOsmStreamSource(graphStream);
                                        router = Router.CreateCHFrom(graphSource, new OsmRoutingInterpreter(), Vehicle.GetByUniqueName(vehicleName));
                                    }
                                    break;
                                case "osm-pbf":
                                    if (string.IsNullOrWhiteSpace(vehicleName))
                                    { // invalid configuration.
                                        throw new Exception("Invalid configuration, a vehicle type is required when building contracted graphs on-the-fly.");
                                    }
                                    using (var graphStream = graphFile.OpenRead())
                                    {
                                        var graphSource = new PBFOsmStreamSource(graphStream);
                                        router = Router.CreateCHFrom(graphSource, new OsmRoutingInterpreter(), Vehicle.GetByUniqueName(vehicleName));
                                    }
                                    break;
                                case "flat":
                                    var mobileRoutingSerializer = new CHEdgeSerializer();
                                    // keep this stream open, it is used while routing!
                                    var mobileGraphInstance = mobileRoutingSerializer.Deserialize(graphFile.OpenRead());
                                    router = Router.CreateCHFrom(mobileGraphInstance, new CHRouter(), new OsmRoutingInterpreter());
                                    break;
                                default:
                                    throw new Exception(string.Format("Invalid format {0} for type {1}.",
                                        format, type));
                            }
                            break;
                        case "simple":
                            switch (format)
                            {
                                case "flat":
                                    using (var graphStream = graphFile.OpenRead())
                                    {
                                        var routingSerializer = new RoutingDataSourceSerializer();
                                        data = routingSerializer.Deserialize(graphStream);
                                        router = Router.CreateFrom(data, new Dykstra(), new OsmRoutingInterpreter());
                                    }
                                    break;
                                default:
                                    throw new Exception(string.Format("Invalid format {0} for type {1}.",
                                        format, type));
                            }
                            break;
                    }

                    if(instanceConfiguration.Feeds != null && instanceConfiguration.Feeds.Count > 0)
                    { // transit-data use the transit-api.
                        if(instanceConfiguration.Feeds.Count > 1)
                        { // for now only one feed at a time is supported.
                            OsmSharp.Logging.Log.TraceEvent("ApiBootstrapper", OsmSharp.Logging.TraceEventType.Warning,
                                "NotSupported: Only one GTFS-feed at a time is supported.");
                        }

                        var feed = instanceConfiguration.Feeds[0];
                        var reader = new GTFSReader<GTFSFeed>(false);
                        var gtfsFeed = reader.Read<GTFSFeed>(new GTFSDirectorySource(feed.Path));
                        var connectionsDb = new GTFSConnectionsDb(gtfsFeed);
                        var multimodalConnectionsDb = new MultimodalConnectionsDb(data, connectionsDb,
                            new OsmRoutingInterpreter(), Vehicle.Pedestrian);

                        lock (_sync)
                        {
                            OsmSharp.Service.Routing.ApiBootstrapper.AddOrUpdate(instanceConfiguration.Name,
                                new MultimodalApi(multimodalConnectionsDb));
                        }
                    }
                    else
                    { // no transit-data just use the regular routing api implementation.
                        lock (_sync)
                        {
                            OsmSharp.Service.Routing.ApiBootstrapper.AddOrUpdate(instanceConfiguration.Name, router);
                        }
                    }

                    OsmSharp.Logging.Log.TraceEvent("Bootstrapper", OsmSharp.Logging.TraceEventType.Information,
                        string.Format("Instance {0} created successfully!", instanceConfiguration.Name));
                }
                catch(Exception ex)
                {
                    OsmSharp.Logging.Log.TraceEvent("Bootstrapper", OsmSharp.Logging.TraceEventType.Error,
                        string.Format("Exception occured while creating instance {0}:{1}", 
                        instanceConfiguration.Name, ex.ToInvariantString()));
                    throw;
                }
                return true;
            }
            catch
            {
                return false;
            }
        }