Beispiel #1
0
        /// <summary>
        /// Adds a contracted graph in the old (broken) way, to test backwards compat. with previous itinero versions.
        /// </summary>
        /// <param name="db"></param>
        /// <param name="profile"></param>
        public static void AddContractedOldEdgeBased(this RouterDb db, Profile profile)
        {
            var weightHandler = profile.DefaultWeightHandlerCached(db);

            var contracted           = new DirectedDynamicGraph(weightHandler.DynamicSize);
            var directedGraphBuilder = new Itinero.Algorithms.Contracted.EdgeBased.DirectedGraphBuilder <float>(db.Network.GeometricGraph.Graph, contracted,
                                                                                                                weightHandler);

            directedGraphBuilder.Run();

            // contract the graph.
            var priorityCalculator = new Itinero.Algorithms.Contracted.EdgeBased.EdgeDifferencePriorityCalculator <float>(contracted, weightHandler,
                                                                                                                          new Itinero.Algorithms.Contracted.EdgeBased.Witness.DykstraWitnessCalculator <float>(weightHandler, 4, 64));

            priorityCalculator.DifferenceFactor = 5;
            priorityCalculator.DepthFactor      = 5;
            priorityCalculator.ContractedFactor = 8;
            var hierarchyBuilder = new Itinero.Algorithms.Contracted.EdgeBased.HierarchyBuilder <float>(contracted, priorityCalculator,
                                                                                                        new Itinero.Algorithms.Contracted.EdgeBased.Witness.DykstraWitnessCalculator <float>(weightHandler, int.MaxValue, 64), weightHandler, db.GetGetRestrictions(profile, null));

            hierarchyBuilder.Run();

            var contractedDb = new ContractedDb(contracted);

            db.AddContracted(profile, contractedDb);
        }
Beispiel #2
0
        /// <summary>
        /// Deserializes contraction data from the given stream.
        /// </summary>
        public static ContractedDb Deserialize(Stream stream, ContractedDbProfile profile)
        {
            // read version # first:
            // 1: means regular non-edge contracted data.
            // 2: means regular edge contracted data.

            var version = stream.ReadByte();

            if (version == 1)
            {
                return(new ContractedDb(DirectedMetaGraph.Deserialize(stream, profile == null ? null : profile.NodeBasedProfile), false));
            }
            else if (version == 2)
            {
                return(new ContractedDb(DirectedDynamicGraph.Deserialize(stream, profile == null ? null : profile.EdgeBasedProfile)));
            }
            else if (version == 3)
            {
                return(new ContractedDb(DirectedMetaGraph.Deserialize(stream, profile == null ? null : profile.NodeBasedProfile), true));
            }
            else
            {
                throw new Exception(string.Format("Cannot deserialize contracted graph: Invalid version #: {0}.", version));
            }
        }
Beispiel #3
0
        public void Test3Vertices()
        {
            // build graph.
            var graph = new DirectedDynamicGraph(ContractedEdgeDataSerializer.DynamicFixedSize);

            graph.AddEdge(0, 1, 100, null);
            graph.AddEdge(1, 0, 100, null);
            graph.AddEdge(1, 2, 100, null);
            graph.AddEdge(2, 1, 100, null);
            graph.Compress();

            // contract graph.
            var hierarchyBuilder = new HierarchyBuilder(graph, new EdgeDifferencePriorityCalculator(graph, new DykstraWitnessCalculator(int.MaxValue)),
                                                        new DykstraWitnessCalculator(int.MaxValue), (i) => Enumerable.Empty <uint[]>());

            hierarchyBuilder.Run();

            // check edges.
            var edges01 = graph.GetEdgeEnumerator(0).FirstOrDefault(x => x.Neighbour == 1);

            Assert.IsNotNull(edges01);
            var edge10 = graph.GetEdgeEnumerator(1).FirstOrDefault(x => x.Neighbour == 0);

            Assert.IsNull(edge10);
            var edge12 = graph.GetEdgeEnumerator(1).FirstOrDefault(x => x.Neighbour == 0);

            Assert.IsNull(edge12);
            var edges21 = graph.GetEdgeEnumerator(2).FirstOrDefault(x => x.Neighbour == 1);

            Assert.IsNotNull(edges21);
        }
Beispiel #4
0
        public void TestRemoveEdge()
        {
            var graph = new DirectedDynamicGraph();

            graph.AddEdge(1, 2, 0102, 010200);
            graph.AddEdge(1, 3, 0103);

            Assert.AreEqual(1, graph.RemoveEdge(1, 2));

            Assert.AreEqual(1, graph.EdgeCount);
            var enumerator = graph.GetEdgeEnumerator();

            Assert.IsTrue(enumerator.MoveTo(1));
            Assert.IsTrue(enumerator.MoveNext());
            Assert.AreEqual(3, enumerator.Neighbour);
            Assert.AreEqual(0103, enumerator.Data0);

            graph = new DirectedDynamicGraph();
            graph.AddEdge(1, 2, 0102, 010200);
            graph.AddEdge(1, 3, 0103);
            graph.AddEdge(1, 4, 0104, 010400, 01040000);

            Assert.AreEqual(1, graph.RemoveEdge(1, 3));
            enumerator = graph.GetEdgeEnumerator();
            Assert.IsTrue(enumerator.MoveTo(1));
            Assert.IsTrue(enumerator.MoveNext());
            Assert.AreEqual(2, enumerator.Neighbour);
            Assert.AreEqual(0102, enumerator.Data0);
            Assert.AreEqual(010200, enumerator.DynamicData[0]);
            Assert.IsTrue(enumerator.MoveNext());
            Assert.AreEqual(4, enumerator.Neighbour);
            Assert.AreEqual(0104, enumerator.Data0);
            Assert.AreEqual(010400, enumerator.DynamicData[0]);
            Assert.AreEqual(01040000, enumerator.DynamicData[1]);
        }
Beispiel #5
0
        /// <summary>
        /// Adds a new edge with the given direction and weight.
        /// </summary>
        public sealed override void AddEdge(DirectedDynamicGraph graph, uint vertex1, uint vertex2, bool?direction, float weight)
        {
            var data = Data.Contracted.Edges.ContractedEdgeDataSerializer.Serialize(
                weight, direction);

            graph.AddEdge(vertex1, vertex2, data);
        }
Beispiel #6
0
        public void TestTwoEdgeInfiniteHops()
        {
            // build graph.
            var graph = new DirectedDynamicGraph(ContractedEdgeDataSerializer.DynamicFixedSize);

            graph.AddEdge(0, 1, 100, null);
            graph.AddEdge(1, 2, 100, null);

            var witnessCalculator = new DykstraWitnessCalculator(int.MaxValue);

            // calculate witness for weight of 200.
            var forwardWitnesses  = new EdgePath <float> [1];
            var backwardWitnesses = new EdgePath <float> [1];

            witnessCalculator.Calculate(graph, (i) => null, 0, new List <uint>(new uint[] { 2 }), new List <float>(new float[] { 1000 }),
                                        ref forwardWitnesses, ref backwardWitnesses, uint.MaxValue);
            Assert.AreEqual(2, forwardWitnesses[0].Vertex);
            Assert.AreEqual(2, backwardWitnesses[0].Vertex);

            // calculate witness for weight of 50.
            forwardWitnesses  = new EdgePath <float> [1];
            backwardWitnesses = new EdgePath <float> [1];
            witnessCalculator.Calculate(graph, (i) => null, 0, new List <uint>(new uint[] { 2 }), new List <float>(new float[] { 50 }),
                                        ref forwardWitnesses, ref backwardWitnesses, uint.MaxValue);
            Assert.AreEqual(Constants.NO_VERTEX, forwardWitnesses[0].Vertex);
            Assert.AreEqual(Constants.NO_VERTEX, backwardWitnesses[0].Vertex);
        }
Beispiel #7
0
        public void TestQuadrilateralOneWay()
        {
            // build graph.
            var graph = new DirectedDynamicGraph(ContractedEdgeDataSerializer.DynamicFixedSize);

            graph.AddEdge(0, 2, 100, true);
            graph.AddEdge(2, 0, 100, false);
            graph.AddEdge(0, 3, 10, false);
            graph.AddEdge(3, 0, 10, true);
            graph.AddEdge(1, 2, 1000, false);
            graph.AddEdge(2, 1, 1000, true);
            graph.AddEdge(1, 3, 10000, true);
            graph.AddEdge(3, 1, 10000, false);
            graph.Compress();

            // create a witness calculator and the priority calculator.
            var contractedFlags    = new BitArray32(graph.VertexCount);
            var priorityCalculator = new EdgeDifferencePriorityCalculator(graph,
                                                                          new Itinero.Algorithms.Contracted.EdgeBased.Witness.DykstraWitnessCalculator(10));

            //var priorityCalculator = new EdgeDifferencePriorityCalculator(graph,
            //    new WitnessCalculatorMock(new uint[][]
            //        {
            //            new uint[] { 1, 3, 2, 1 },
            //            new uint[] { 3, 0, 1, 1 }
            //        }));

            Assert.AreEqual(0, priorityCalculator.Calculate(contractedFlags, (i) => null, 0));
            Assert.AreEqual(0, priorityCalculator.Calculate(contractedFlags, (i) => null, 1));
            Assert.AreEqual(0, priorityCalculator.Calculate(contractedFlags, (i) => null, 2));
            Assert.AreEqual(0, priorityCalculator.Calculate(contractedFlags, (i) => null, 3));
        }
Beispiel #8
0
        /// <summary>
        /// Creates a new algorithm.
        /// </summary>
        public ManyToManyWeightsBidirectionalDykstra(RouterDb routerDb, Profile profile, WeightHandler <T> weightHandler, RouterPoint[] sources,
                                                     RouterPoint[] targets, T max)
        {
            _routerDb      = routerDb;
            _weightHandler = weightHandler;
            _sources       = sources;
            _targets       = targets;
            _profile       = profile;
            _max           = max;

            ContractedDb contractedDb;

            if (!_routerDb.TryGetContracted(profile, out contractedDb))
            {
                throw new NotSupportedException(
                          "Contraction-based many-to-many calculates are not supported in the given router db for the given profile.");
            }
            if (!contractedDb.HasEdgeBasedGraph)
            {
                throw new NotSupportedException(
                          "Contraction-based edge-based many-to-many calculates are not supported in the given router db for the given profile.");
            }
            _graph = contractedDb.EdgeBasedGraph;
            weightHandler.CheckCanUse(contractedDb);

            _buckets = new Dictionary <uint, Dictionary <int, T> >();
        }
Beispiel #9
0
        public void TestVertexCountAndTrim()
        {
            var graph = new DirectedDynamicGraph(10, 1);

            // add edge.
            graph.AddEdge(0, 1, 1);

            // trim.
            graph.Trim();
            Assert.AreEqual(2, graph.VertexCount);

            graph = new DirectedDynamicGraph(10, 1);

            // add edge.
            graph.AddEdge(0, 1, 1);
            graph.AddEdge(0, 11001, 1);

            // trim.
            graph.Trim();
            Assert.AreEqual(11002, graph.VertexCount);

            graph = new DirectedDynamicGraph(10, 1);

            // trim.
            graph.Trim(); // keep minimum one vertex.
            Assert.AreEqual(1, graph.VertexCount);
        }
Beispiel #10
0
        /// <summary>
        /// Creates a new weight-matrix algorithm.
        /// </summary>
        public DirectedWeightMatrixAlgorithm(RouterBase router, IProfileInstance profile, WeightHandler <T> weightHandler, IMassResolvingAlgorithm massResolver, T?max = null)
        {
            _router        = router;
            _profile       = profile;
            _weightHandler = weightHandler;
            _massResolver  = massResolver;

            ContractedDb contractedDb;

            if (!router.Db.TryGetContracted(profile.Profile, out contractedDb))
            {
                throw new NotSupportedException(
                          "Contraction-based many-to-many calculates are not supported in the given router db for the given profile.");
            }
            if (!contractedDb.HasEdgeBasedGraph)
            {
                throw new NotSupportedException(
                          "Contraction-based edge-based many-to-many calculates are not supported in the given router db for the given profile.");
            }
            _graph = contractedDb.EdgeBasedGraph;
            weightHandler.CheckCanUse(contractedDb);
            if (max.HasValue)
            {
                _max = max.Value;
            }
            else
            {
                _max = weightHandler.Infinite;
            }

            _buckets = new Dictionary <uint, Dictionary <int, LinkedEdgePath <T> > >();
        }
Beispiel #11
0
 public void Calculate(DirectedDynamicGraph graph, Func <uint, IEnumerable <uint[]> > getRestrictions, uint source, List <uint> targets, List <float> weights,
                       ref EdgePath <float>[] forwardWitness, ref EdgePath <float>[] backwardWitness, uint vertexToSkip)
 {
     for (var i = 0; i < forwardWitness.Length; i++)
     {
         if (forwardWitness[i] == null)
         {
             forwardWitness[i] = new EdgePath <float>();
         }
         if (backwardWitness[i] == null)
         {
             backwardWitness[i] = new EdgePath <float>();
         }
     }
     if (_witnesses != null)
     {
         for (var i = 0; i < targets.Count; i++)
         {
             var target    = targets[i];
             var witnesses = _witnesses(source, target);
             if (witnesses != null)
             {
                 forwardWitness[i]  = witnesses.Item1;
                 backwardWitness[i] = witnesses.Item2;
             }
         }
     }
 }
Beispiel #12
0
        /// <summary>
        /// Creates a new contracted graph and adds it to the router db for the given profile.
        /// </summary>
        public static void AddEdgeBasedContractedForTesting <T>(this RouterDb db, Profile profile, WeightHandler <T> weightHandler)
            where T : struct
        {
            // create the raw directed graph.
            ContractedDb contractedDb = null;

            var contracted           = new DirectedDynamicGraph(weightHandler.DynamicSize);
            var directedGraphBuilder = new Itinero.Algorithms.Contracted.EdgeBased.DirectedGraphBuilder <T>(db.Network.GeometricGraph.Graph, contracted,
                                                                                                            weightHandler);

            directedGraphBuilder.Run();

            // contract the graph.
            var priorityCalculator = new Itinero.Algorithms.Contracted.EdgeBased.EdgeDifferencePriorityCalculator <T>(contracted, weightHandler,
                                                                                                                      new Itinero.Algorithms.Contracted.EdgeBased.Witness.DykstraWitnessCalculator <T>(weightHandler, 4, 64));

            priorityCalculator.DifferenceFactor = 5;
            priorityCalculator.DepthFactor      = 5;
            priorityCalculator.ContractedFactor = 8;
            var hierarchyBuilder = new Itinero.Algorithms.Contracted.EdgeBased.HierarchyBuilder <T>(contracted, priorityCalculator,
                                                                                                    new Itinero.Algorithms.Contracted.EdgeBased.Witness.DykstraWitnessCalculator <T>(weightHandler, int.MaxValue, 64), weightHandler, db.GetGetRestrictions(profile, null));

            hierarchyBuilder.Run();

            contractedDb = new ContractedDb(contracted);

            // add the graph.
            db.AddContracted(profile, contractedDb);
        }
Beispiel #13
0
        public void TestDoubleContractionOneway()
        {
            // build graph.
            var graph = new DirectedDynamicGraph(ContractedEdgeDataSerializer.DynamicFixedSize);

            graph.AddEdge(0, 1, 100, null);
            graph.AddEdge(1, 0, 100, null);
            graph.AddEdge(1, 2, 100, null);
            graph.AddEdge(2, 1, 100, null);
            graph.AddEdge(1, 3, 10, null);
            graph.AddEdge(3, 1, 10, null);
            graph.AddEdge(3, 2, 10, null);
            graph.AddEdge(2, 3, 10, null);
            graph.Compress();

            // contract graph.
            var priorities = new Dictionary <uint, float>();

            priorities.Add(1, 0);
            priorities.Add(0, 1);
            priorities.Add(2, 2);
            priorities.Add(3, 3);
            var hierarchyBuilder = new HierarchyBuilder(graph,
                                                        new MockPriorityCalculator(priorities),
                                                        new DykstraWitnessCalculator(int.MaxValue), (i) => Enumerable.Empty <uint[]>());

            hierarchyBuilder.Run();

            // edges 1->2 and 2->1 should have been removed.
            var edge = graph.GetEdgeEnumerator(0).FirstOrDefault(x => x.Neighbour == 3);

            Assert.IsNotNull(edge);
            var edgeData = ContractedEdgeDataSerializer.Deserialize(edge.Data[0], Constants.NO_VERTEX);

            Assert.AreEqual(110, edgeData.Weight);
            Assert.AreEqual(null, edgeData.Direction);
            Assert.AreEqual(1, edge.GetContracted());

            edge = graph.GetEdgeEnumerator(1).FirstOrDefault(x => x.Neighbour == 0);
            Assert.IsNotNull(edge);
            edgeData = ContractedEdgeDataSerializer.Deserialize(edge.Data[0], Constants.NO_VERTEX);
            Assert.AreEqual(100, edgeData.Weight);
            Assert.AreEqual(null, edgeData.Direction);
            Assert.AreEqual(Constants.NO_VERTEX, edgeData.ContractedId);

            edge = graph.GetEdgeEnumerator(1).FirstOrDefault(x => x.Neighbour == 3);
            Assert.IsNotNull(edge);
            edgeData = ContractedEdgeDataSerializer.Deserialize(edge.Data[0], Constants.NO_VERTEX);
            Assert.AreEqual(10, edgeData.Weight);
            Assert.AreEqual(null, edgeData.Direction);
            Assert.AreEqual(Constants.NO_VERTEX, edgeData.ContractedId);

            edge = graph.GetEdgeEnumerator(2).FirstOrDefault(x => x.Neighbour == 3);
            Assert.IsNotNull(edge);
            edgeData = ContractedEdgeDataSerializer.Deserialize(edge.Data[0], Constants.NO_VERTEX);
            Assert.AreEqual(10, edgeData.Weight);
            Assert.AreEqual(null, edgeData.Direction);
            Assert.AreEqual(Constants.NO_VERTEX, edgeData.ContractedId);
        }
Beispiel #14
0
        /// <summary>
        /// Creates a new graph builder.
        /// </summary>
        public DirectedGraphBuilder(Itinero.Graphs.Graph source, DirectedDynamicGraph target, WeightHandler <T> weightHandler)
        {
            weightHandler.CheckCanUse(target);

            _source        = source;
            _target        = target;
            _weightHandler = weightHandler;
        }
        public void TestOneEdgeAugmented()
        {
            // build graph.
            var graph = new Itinero.Graphs.Graph(EdgeDataSerializer.Size);

            graph.AddVertex(0);
            graph.AddVertex(1);
            graph.AddEdge(0, 1, EdgeDataSerializer.Serialize(new EdgeData()
            {
                Distance = 100,
                Profile  = 1
            }));

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

            // convert graph.
            var directedGraph = new DirectedDynamicGraph(ContractedEdgeDataSerializer.DynamicAugmentedFixedSize);
            var algorithm     = new DirectedGraphBuilder <Weight>(graph, directedGraph, new WeightHandler(getFactor));

            algorithm.Run();

            // check result.
            Assert.IsTrue(algorithm.HasRun);
            Assert.IsTrue(algorithm.HasSucceeded);

            directedGraph.Compress();
            Assert.AreEqual(2, directedGraph.VertexCount);
            Assert.AreEqual(2, directedGraph.EdgeCount);

            // verify all edges.
            var edges = directedGraph.GetEdgeEnumerator(0);

            Assert.AreEqual(1, edges.Count());
            var data = ContractedEdgeDataSerializer.SerializeDynamicAugmented(100 * getFactor(1).Value, null, 100, 100 * getFactor(1).Value);

            Assert.AreEqual(data[0], edges.First().Data[0]);
            Assert.AreEqual(data[1], edges.First().Data[1]);
            Assert.AreEqual(data[2], edges.First().Data[2]);
            Assert.AreEqual(1, edges.First().Neighbour);

            edges = directedGraph.GetEdgeEnumerator(1);
            Assert.AreEqual(1, edges.Count());
            data = ContractedEdgeDataSerializer.SerializeDynamicAugmented(100 * getFactor(1).Value, null, 100, 100 * getFactor(1).Value);
            Assert.AreEqual(data[0], edges.First().Data[0]);
            Assert.AreEqual(data[1], edges.First().Data[1]);
            Assert.AreEqual(data[2], edges.First().Data[2]);
            Assert.AreEqual(0, edges.First().Neighbour);
        }
Beispiel #16
0
        public void TestTwoNeighboursOneWayOpposite()
        {
            // build graph.
            var graph = new DirectedDynamicGraph(ContractedEdgeDataSerializer.DynamicFixedSize);

            graph.AddEdge(0, 1, 100, true);
            graph.AddEdge(1, 0, 100, false);
            graph.AddEdge(0, 2, 100, true);
            graph.AddEdge(2, 0, 100, false);

            // create a witness calculator and the priority calculator.
            var priorityCalculator = new EdgeDifferencePriorityCalculator(graph,
                                                                          new WitnessCalculatorMock((source, target) =>
            {
                if (source == 0 && target == 1)
                {
                    return(new Tuple <EdgePath <float>, EdgePath <float> >(
                               new EdgePath <float>(0, 100, new EdgePath <float>(1)),
                               new EdgePath <float>()));
                }
                if (source == 0 && target == 2)
                {
                    return(new Tuple <EdgePath <float>, EdgePath <float> >(
                               new EdgePath <float>(0, 100, new EdgePath <float>(2)),
                               new EdgePath <float>()));
                }
                if (source == 1 && target == 0)
                {
                    return(new Tuple <EdgePath <float>, EdgePath <float> >(
                               new EdgePath <float>(),
                               new EdgePath <float>(0, 100, new EdgePath <float>(1))));
                }
                if (source == 2 && target == 0)
                {
                    return(new Tuple <EdgePath <float>, EdgePath <float> >(
                               new EdgePath <float>(),
                               new EdgePath <float>(0, 100, new EdgePath <float>(2))));
                }
                if (source == 1 && target == 2)
                {
                    return(new Tuple <EdgePath <float>, EdgePath <float> >(
                               new EdgePath <float>(),
                               new EdgePath <float>()));
                }
                if (source == 2 && target == 1)
                {
                    return(new Tuple <EdgePath <float>, EdgePath <float> >(
                               new EdgePath <float>(),
                               new EdgePath <float>()));
                }
                return(null);
            }));
            var priority = priorityCalculator.Calculate(new BitArray32(graph.VertexCount), (i) => null, 0);

            Assert.AreEqual(-2, priority);
        }
Beispiel #17
0
        /// <summary>
        /// Creates a new node-based contracted db.
        /// </summary>
        public ContractedDb(DirectedMetaGraph nodeBasedGraph)
        {
            if (nodeBasedGraph == null)
            {
                throw new ArgumentNullException("nodeBasedGraph");
            }

            _nodeBasedGraph = nodeBasedGraph;
            _edgeBasedGraph = null;
        }
Beispiel #18
0
        /// <summary>
        /// Creates a new edge-based contracted db.
        /// </summary>
        public ContractedDb(DirectedDynamicGraph edgeBasedGraph)
        {
            if (edgeBasedGraph == null)
            {
                throw new ArgumentNullException("edgeBasedGraph");
            }

            _nodeBasedGraph = null;
            _edgeBasedGraph = edgeBasedGraph;
        }
Beispiel #19
0
        /// <summary>
        /// Creates a new hierarchy builder.
        /// </summary>
        public HierarchyBuilder(DirectedDynamicGraph graph, IPriorityCalculator priorityCalculator, IWitnessCalculator <T> witnessCalculator,
                                WeightHandler <T> weightHandler, Func <uint, IEnumerable <uint[]> > getRestrictions)
        {
            weightHandler.CheckCanUse(graph);

            _graph = graph;
            _priorityCalculator = priorityCalculator;
            _witnessCalculator  = witnessCalculator;
            _getRestrictions    = getRestrictions;
            _weightHandler      = weightHandler;
        }
Beispiel #20
0
        public void TestDeserialize()
        {
            var graph = new DirectedDynamicGraph(10, 1);

            graph.AddEdge(0, 1, 1);

            // serialize.
            using (var stream = new System.IO.MemoryStream())
            {
                var size = graph.Serialize(stream);

                stream.Seek(0, System.IO.SeekOrigin.Begin);

                var deserializedGraph = DirectedDynamicGraph.Deserialize(stream, DirectedGraphProfile.Aggressive24);
                Assert.AreEqual(size, stream.Position);

                Assert.AreEqual(2, deserializedGraph.VertexCount);
                Assert.AreEqual(1, deserializedGraph.EdgeCount);

                // verify all edges.
                var edges = deserializedGraph.GetEdgeEnumerator(0);
                Assert.AreEqual(1, edges.Count());
                Assert.AreEqual(1, edges.First().Data[0]);
                Assert.AreEqual(1, edges.First().Neighbour);

                edges = deserializedGraph.GetEdgeEnumerator(1);
                Assert.IsFalse(edges.MoveNext());
            }

            graph = new DirectedDynamicGraph(10, 1);
            graph.AddEdge(0, 1, 1);
            graph.AddEdge(0, 2, 2);
            graph.AddEdge(0, 3, 3);
            graph.AddEdge(0, 4, 4);
            graph.AddEdge(5, 1, 5);
            graph.AddEdge(5, 2, 6);
            graph.AddEdge(5, 3, 7);
            graph.AddEdge(5, 4, 8);

            // serialize.
            using (var stream = new System.IO.MemoryStream())
            {
                var size = graph.Serialize(stream);

                stream.Seek(0, System.IO.SeekOrigin.Begin);

                var deserializedGraph = DirectedDynamicGraph.Deserialize(stream, DirectedGraphProfile.Aggressive24);
                Assert.AreEqual(size, stream.Position);

                Assert.AreEqual(6, deserializedGraph.VertexCount);
                Assert.AreEqual(8, deserializedGraph.EdgeCount);
            }
        }
Beispiel #21
0
        public void TestTwoEdgesMiddleHighest()
        {
            // build graph.
            var graph = new DirectedDynamicGraph(ContractedEdgeDataSerializer.DynamicFixedSize);

            graph.AddEdge(0, 1, 100, null);
            graph.AddEdge(2, 1, 100, null);

            // create algorithm and run.
            var algorithm = new Itinero.Algorithms.Contracted.EdgeBased.Dykstra(graph,
                                                                                new EdgePath <float>[] { new EdgePath <float>(0) },
                                                                                (v) => null, true);

            algorithm.Run();

            // check results.
            Assert.IsTrue(algorithm.HasRun);
            Assert.IsTrue(algorithm.HasSucceeded);

            EdgePath <float> visit;

            Assert.IsTrue(algorithm.TryGetVisit(0, out visit));
            Assert.AreEqual(0, visit.Weight);
            Assert.AreEqual(0, visit.Vertex);
            Assert.AreEqual(null, visit.From);
            Assert.IsTrue(algorithm.TryGetVisit(1, out visit));
            Assert.AreEqual(100, visit.Weight);
            Assert.AreEqual(1, visit.Vertex);
            Assert.IsNotNull(visit.From);
            Assert.AreEqual(0, visit.From.Vertex);
            Assert.IsFalse(algorithm.TryGetVisit(2, out visit));

            // create algorithm and run.
            algorithm = new Itinero.Algorithms.Contracted.EdgeBased.Dykstra(graph,
                                                                            new EdgePath <float>[] { new EdgePath <float>(0) },
                                                                            (v) => null, false);
            algorithm.Run();

            // check results.
            Assert.IsTrue(algorithm.HasRun);
            Assert.IsTrue(algorithm.HasSucceeded);

            Assert.IsTrue(algorithm.TryGetVisit(0, out visit));
            Assert.AreEqual(0, visit.Weight);
            Assert.AreEqual(0, visit.Vertex);
            Assert.AreEqual(null, visit.From);
            Assert.IsTrue(algorithm.TryGetVisit(1, out visit));
            Assert.AreEqual(100, visit.Weight);
            Assert.AreEqual(1, visit.Vertex);
            Assert.IsNotNull(visit.From);
            Assert.AreEqual(0, visit.From.Vertex);
            Assert.IsFalse(algorithm.TryGetVisit(2, out visit));
        }
Beispiel #22
0
        /// <summary>
        /// Creates a new contracted graph and adds it to the router db for the given profile.
        /// </summary>
        public static void AddContracted <T>(this RouterDb db, Profiles.Profile profile, WeightHandler <T> weightHandler, bool forceEdgeBased = false)
            where T : struct
        {
            // create the raw directed graph.
            ContractedDb contractedDb = null;

            lock (db)
            {
                if (forceEdgeBased)
                { // edge-based is needed when complex restrictions found.
                    var contracted           = new DirectedDynamicGraph(weightHandler.DynamicSize);
                    var directedGraphBuilder = new Itinero.Algorithms.Contracted.EdgeBased.DirectedGraphBuilder <T>(db.Network.GeometricGraph.Graph, contracted,
                                                                                                                    weightHandler);
                    directedGraphBuilder.Run();

                    // contract the graph.
                    var priorityCalculator = new Itinero.Algorithms.Contracted.EdgeBased.EdgeDifferencePriorityCalculator <T>(contracted, weightHandler,
                                                                                                                              new Itinero.Algorithms.Contracted.EdgeBased.Witness.DykstraWitnessCalculator <T>(weightHandler, int.MaxValue));
                    priorityCalculator.DifferenceFactor = 5;
                    priorityCalculator.DepthFactor      = 5;
                    priorityCalculator.ContractedFactor = 8;
                    var hierarchyBuilder = new Itinero.Algorithms.Contracted.EdgeBased.HierarchyBuilder <T>(contracted, priorityCalculator,
                                                                                                            new Itinero.Algorithms.Contracted.EdgeBased.Witness.DykstraWitnessCalculator <T>(weightHandler, int.MaxValue), weightHandler, db.GetGetRestrictions(profile, null));
                    hierarchyBuilder.Run();

                    contractedDb = new ContractedDb(contracted);
                }
                else
                { // vertex-based is ok when no complex restrictions found.
                    var contracted           = new DirectedMetaGraph(ContractedEdgeDataSerializer.Size, weightHandler.MetaSize);
                    var directedGraphBuilder = new DirectedGraphBuilder <T>(db.Network.GeometricGraph.Graph, contracted, weightHandler);
                    directedGraphBuilder.Run();

                    // contract the graph.
                    var priorityCalculator = new EdgeDifferencePriorityCalculator(contracted,
                                                                                  new DykstraWitnessCalculator(int.MaxValue));
                    priorityCalculator.DifferenceFactor = 5;
                    priorityCalculator.DepthFactor      = 5;
                    priorityCalculator.ContractedFactor = 8;
                    var hierarchyBuilder = new HierarchyBuilder <T>(contracted, priorityCalculator,
                                                                    new DykstraWitnessCalculator(int.MaxValue), weightHandler);
                    hierarchyBuilder.Run();

                    contractedDb = new ContractedDb(contracted);
                }
            }

            // add the graph.
            lock (db)
            {
                db.AddContracted(profile, contractedDb);
            }
        }
        /// <summary>
        /// Creates a new priority calculator.
        /// </summary>
        public EdgeDifferencePriorityCalculator(DirectedDynamicGraph graph, WeightHandler <T> weightHandler, IWitnessCalculator <T> witnessCalculator)
        {
            _graph             = graph;
            _witnessCalculator = witnessCalculator;
            _contractionCount  = new Dictionary <uint, int>();
            _depth             = new Dictionary <long, int>();
            _weightHandler     = weightHandler;

            this.DifferenceFactor = 1;
            this.DepthFactor      = 2;
            this.ContractedFactor = 1;
        }
Beispiel #24
0
        public void TestNoNeighbours()
        {
            // build graph.
            var graph = new DirectedDynamicGraph(ContractedEdgeDataSerializer.DynamicFixedSize);

            graph.AddEdge(1, 0, 100, null);

            // create a witness calculator and the priority calculator.
            var priorityCalculator = new EdgeDifferencePriorityCalculator(graph,
                                                                          new WitnessCalculatorMock());
            var priority = priorityCalculator.Calculate(new BitArray32(graph.VertexCount), (i) => null, 0);

            Assert.AreEqual(0, priority);
        }
Beispiel #25
0
        /// <summary>
        /// Creates a new routing algorithm instance.
        /// </summary>
        public Dykstra(DirectedDynamicGraph graph, WeightHandler <T> weightHandler, IEnumerable <EdgePath <T> > sources,
                       Func <uint, IEnumerable <uint[]> > getRestrictions, bool backward)
        {
            weightHandler.CheckCanUse(graph);

            _graph           = graph;
            _getRestrictions = getRestrictions;
            _sources         = sources.Select(x => {
                x.StripEdges();
                return(x);
            });
            _backward      = backward;
            _weightHandler = weightHandler;
        }
Beispiel #26
0
        public void TestDoubleContraction()
        {
            // build graph.
            var graph = new DirectedDynamicGraph(ContractedEdgeDataSerializer.DynamicFixedSize);

            graph.AddEdge(0, 2, 100, null);
            graph.AddEdge(2, 0, 100, null);
            graph.AddEdge(0, 3, 100, null);
            graph.AddEdge(3, 0, 100, null);
            graph.AddEdge(1, 2, 200, null);
            graph.AddEdge(2, 1, 200, null);
            graph.AddEdge(1, 3, 200, null);
            graph.AddEdge(3, 1, 200, null);
            graph.Compress();

            // contract graph.
            var priorityCalculator = new EdgeDifferencePriorityCalculator(graph, new DykstraWitnessCalculator(int.MaxValue));

            priorityCalculator.DepthFactor      = 0;
            priorityCalculator.ContractedFactor = 0;
            var hierarchyBuilder = new HierarchyBuilder(graph, priorityCalculator,
                                                        new DykstraWitnessCalculator(int.MaxValue), (i) => Enumerable.Empty <uint[]>());

            hierarchyBuilder.Run();

            // check edges.
            var edge = graph.GetEdgeEnumerator(0).FirstOrDefault(x => x.Neighbour == 2);

            Assert.IsNull(edge);
            edge = graph.GetEdgeEnumerator(2).FirstOrDefault(x => x.Neighbour == 0);
            Assert.IsNotNull(edge);

            edge = graph.GetEdgeEnumerator(0).FirstOrDefault(x => x.Neighbour == 3);
            Assert.IsNull(edge);
            edge = graph.GetEdgeEnumerator(3).FirstOrDefault(x => x.Neighbour == 0);
            Assert.IsNotNull(edge);

            edge = graph.GetEdgeEnumerator(2).FirstOrDefault(x => x.Neighbour == 1);
            Assert.IsNull(edge);
            edge = graph.GetEdgeEnumerator(1).FirstOrDefault(x => x.Neighbour == 2);
            Assert.IsNotNull(edge);

            edge = graph.GetEdgeEnumerator(3).FirstOrDefault(x => x.Neighbour == 1);
            Assert.IsNull(edge);
            edge = graph.GetEdgeEnumerator(1).FirstOrDefault(x => x.Neighbour == 3);
            Assert.IsNotNull(edge);
        }
Beispiel #27
0
        /// <summary>
        /// Creates a new contracted bidirectional router.
        /// </summary>
        public BidirectionalDykstra(DirectedDynamicGraph graph, WeightHandler <T> weightHandler, IEnumerable <EdgePath <T> > sources, IEnumerable <EdgePath <T> > targets,
                                    Func <uint, IEnumerable <uint[]> > getRestrictions)
        {
            weightHandler.CheckCanUse(graph);

            _graph         = graph;
            _weightHandler = weightHandler;
            _sources       = sources.Select(x => {
                x.StripEdges();
                return(x);
            });
            _targets = targets.Select(x => {
                x.StripEdges();
                return(x);
            });
            _getRestrictions = getRestrictions;
        }
Beispiel #28
0
        public void TestGetSequence2()
        {
            // build graph.
            var graph      = new DirectedDynamicGraph(ContractedEdgeDataSerializer.DynamicFixedSize);
            var e1         = graph.AddEdge(0, 1, 100, null);
            var e2         = graph.AddEdge(1, 2, 100, null);
            var e3         = graph.AddEdge(2, 6, 100, null, 4, new uint[] { 3 }, new uint[] { 5 });
            var e4         = graph.AddEdge(6, 16, 100, null, 11, new uint[] { 7, 8, 9, 10 }, new uint[] { 12, 13, 14, 15 });
            var enumerator = graph.GetEdgeEnumerator();

            // build and test getting sequences from paths.
            var path = new EdgePath <float>(0);
            var s    = path.GetSequence2(enumerator);

            Assert.IsNotNull(s);
            Assert.AreEqual(0, s.Length);

            path = new EdgePath <float>(1, 100, new EdgePath <float>(0));
            s    = path.GetSequence2(enumerator);
            Assert.IsNotNull(s);
            Assert.AreEqual(1, s.Length);
            Assert.AreEqual(0, s[0]);

            path = new EdgePath <float>(2, 200, e2 + 1, new EdgePath <float>(1, 100, new EdgePath <float>(0)));
            s    = path.GetSequence2(enumerator);
            Assert.IsNotNull(s);
            Assert.AreEqual(2, s.Length);
            Assert.AreEqual(0, s[0]);
            Assert.AreEqual(1, s[1]);

            path = new EdgePath <float>(6, 300, e3 + 1, new EdgePath <float>(2, 200, e2 + 1, new EdgePath <float>(1, 100, new EdgePath <float>(0))));
            s    = path.GetSequence2(enumerator);
            Assert.IsNotNull(s);
            Assert.AreEqual(1, s.Length);
            Assert.AreEqual(5, s[0]);

            path = new EdgePath <float>(16, 400, e4 + 1, new EdgePath <float>(6, 300, e3 + 1, new EdgePath <float>(2, 200, e2 + 1, new EdgePath <float>(1, 100, new EdgePath <float>(0)))));
            s    = path.GetSequence2(enumerator);
            Assert.IsNotNull(s);
            Assert.AreEqual(4, s.Length);
            Assert.AreEqual(12, s[0]);
            Assert.AreEqual(13, s[1]);
            Assert.AreEqual(14, s[2]);
            Assert.AreEqual(15, s[3]);
        }
Beispiel #29
0
        public void TestOneNeighboursContracted()
        {
            // build graph.
            var graph = new DirectedDynamicGraph(ContractedEdgeDataSerializer.DynamicFixedSize);

            graph.AddEdge(0, 1, 100, true);
            graph.AddEdge(1, 0, 100, false);

            // create a witness calculator and the priority calculator.
            var contractedFlags = new BitArray32(graph.VertexCount);

            contractedFlags[1] = true;
            var priorityCalculator = new EdgeDifferencePriorityCalculator(graph,
                                                                          new WitnessCalculatorMock());
            var priority = priorityCalculator.Calculate(contractedFlags, (i) => null, 0);

            Assert.AreEqual(-2, priority);
        }
Beispiel #30
0
        public void TestSerialize()
        {
            var graph = new DirectedDynamicGraph(10, 1);

            // add and compress.
            graph.AddEdge(0, 1, 1);
            graph.Compress();
            var expectedSize = 1 + 8 + 8 + 8 + 4 +         // the header: version byte two longs representing vertex, edge count and the size of the edge array and one int for minimum edge size.
                               graph.VertexCount * 1 * 4 + // the bytes for the vertex-index: 1 uint.
                               graph.EdgeCount * 2 * 4;    // the bytes for the edges: one edge 2 uint's.

            using (var stream = new System.IO.MemoryStream())
            {
                Assert.AreEqual(expectedSize, graph.Serialize(stream));
                Assert.AreEqual(expectedSize, stream.Position);
            }

            // verify all edges.
            var edges = graph.GetEdgeEnumerator(0);

            Assert.AreEqual(1, edges.Count());
            Assert.AreEqual(1, edges.First().Data[0]);
            Assert.AreEqual(1, edges.First().Neighbour);

            graph = new DirectedDynamicGraph(10, 1);

            // add and compress.
            graph.AddEdge(0, 1, 10);
            graph.AddEdge(1, 2, 20);
            graph.AddEdge(2, 3, 30);
            graph.AddEdge(3, 4, 40);
            graph.RemoveEdge(1, 2);
            graph.Compress();
            expectedSize = 1 + 8 + 8 + 8 + 4 +      // the header: version bytes, three longs representing vertex and edge count and the size of the edge array and one int for fixed edge size.
                           graph.VertexCount * 4 +  // the bytes for the vertex-index: 2 uint's.
                           graph.EdgeCount * 2 * 4; // the bytes for the edges: one edge 1 uint.
            using (var stream = new System.IO.MemoryStream())
            {
                Assert.AreEqual(expectedSize, graph.Serialize(stream));
                Assert.AreEqual(expectedSize, stream.Position);
            }
        }