Exemplo n.º 1
0
        public void GenerateDotFile()
        {
            var graph = new AdjacencyGraph<string, TaggedEdge<string, string>>();

            for (int i = 0; i < Math.Sqrt(Convert.ToDouble(m_Matrix.Length)); i++)
            {
                graph.AddVertex(String.Format("{0}", i));
            }
            for (int i = 0; i < Math.Sqrt(Convert.ToDouble(m_Matrix.Length)); i++)
            {
                for (int j = 0; j < Math.Sqrt(Convert.ToDouble(m_Matrix.Length)); j++)
                {
                    if ((m_Matrix[i, j] == true) & (i < j))
                    {
                        graph.AddEdge(new TaggedEdge<string, string>(String.Format("{0}", i), String.Format("{0}", j), String.Format("{0}", i)));
                    }
                }
            }

            var graphViz = new GraphvizAlgorithm<string, TaggedEdge<string, string>>(graph, @".\", QuickGraph.Graphviz.Dot.GraphvizImageType.Png);
            graphViz.FormatVertex += (sender, e) =>
            {
                e.VertexFormatter.Shape = QuickGraph.Graphviz.Dot.GraphvizVertexShape.Circle;
            };

            graphViz.FormatEdge += (sender, e) =>
            {
                e.EdgeFormatter.Dir = QuickGraph.Graphviz.Dot.GraphvizEdgeDirection.None;
            };

            graphViz.Generate(new FileDotEngine(), m_Name);
        }
 public void Simple()
 {
     AdjacencyGraph<string, Edge<string>> g = new AdjacencyGraph<string, Edge<string>>();
     GraphFactory.Simple(g);
     this.Compute(g);
     this.ComputeCriticalPath(g);
 }
Exemplo n.º 3
0
    	//DC this version was using the old QuickGraph MarkedEdge
        public static void createGraphWizDotFile(AdjacencyGraph<String, TaggedEdge<String, String>> gGraphWizToPopulate,
                                                 TreeNode tnTreeNode, bool bOrder, bool bFilterName, bool bFilterClass,
                                                 int iFilterClassLevel)
        {
            if (bFilterClass)
                tnTreeNode.Text = FilteredSignature.filterName(tnTreeNode.Text, false, false, true, 0, true, true,
                                                               iFilterClassLevel);
            TaggedEdge<String, string> meTemp;
            if (gGraphWizToPopulate.ContainsVertex(tnTreeNode.Text))
            {
            }
            else
                gGraphWizToPopulate.AddVertex(tnTreeNode.Text);

            foreach (TreeNode tnChild in tnTreeNode.Nodes)
            {
                if (bFilterClass)
                    tnChild.Text = FilteredSignature.filterName(tnChild.Text, false, false, true, 0, true, true,
                                                                iFilterClassLevel);
                createGraphWizDotFile(gGraphWizToPopulate, tnChild, bOrder, bFilterName, bFilterClass, iFilterClassLevel);
                if (bOrder)
                {
                    if (false == gGraphWizToPopulate.TryGetEdge(tnTreeNode.Text, tnChild.Text, out meTemp))
                        gGraphWizToPopulate.AddEdge(new TaggedEdge<String, string>(tnTreeNode.Text, tnChild.Text,
                                                                                   "marker"));
                }
                else if (false == gGraphWizToPopulate.TryGetEdge(tnChild.Text, tnTreeNode.Text, out meTemp))
                    gGraphWizToPopulate.AddEdge(new TaggedEdge<String, string>(tnChild.Text, tnTreeNode.Text, "marker"));

                //gGraphToPopulate.AddEdge(tnTreeNode.Text, tnChild.Text);
                //    gGraphToPopulate.AddEdge(Analysis_CallFlow.display.filterName(tnChild.Text, false, false, false), Analysis_CallFlow.display.filterName(tnTreeNode.Text, false, false, false));
                //else
            }
        }
Exemplo n.º 4
0
		public void Removing_Explicit_Edges_2()
		{
			var graph = new AdjacencyGraph<int, Edge<int>>();
			graph.AddVertex(1);
			graph.AddVertex(2);
			graph.AddVertex(3);
			graph.AddVertex(4);
			graph.AddVertex(5);
			graph.AddVertex(6);
			graph.AddVertex(7);
			graph.AddEdge(new Edge<int>(1, 3));
			graph.AddEdge(new Edge<int>(1, 4));
			graph.AddEdge(new Edge<int>(1, 6));
			graph.AddEdge(new Edge<int>(3, 6));
			graph.AddEdge(new Edge<int>(4, 6));
			graph.AddEdge(new Edge<int>(2, 4));
			graph.AddEdge(new Edge<int>(2, 5));
			graph.AddEdge(new Edge<int>(2, 7));
			graph.AddEdge(new Edge<int>(4, 7));
			graph.AddEdge(new Edge<int>(5, 7));

			GraphHelper.RemoveExplicitEdges(graph);

			Assert.AreEqual(8, graph.EdgeCount);
			Assert.IsTrue(graph.ContainsEdge(1, 3));
			Assert.IsTrue(graph.ContainsEdge(1, 4));
			Assert.IsTrue(graph.ContainsEdge(2, 4));
			Assert.IsTrue(graph.ContainsEdge(2, 5));
			Assert.IsTrue(graph.ContainsEdge(3, 6));
			Assert.IsTrue(graph.ContainsEdge(4, 6));
			Assert.IsTrue(graph.ContainsEdge(4, 7));
			Assert.IsTrue(graph.ContainsEdge(5, 7));
		}
Exemplo n.º 5
0
 public ParkingMap(string name, int width, int height)
 {
     Name = name;
     Width = width;
     Height = height;
     Graph = new AdjacencyGraph<Vertex, Edge<Vertex>>();
 }
Exemplo n.º 6
0
        public static AdjacencyGraph<PropertyInfo, STaggedEdge<PropertyInfo, string>> BuildDependencyGraph(Type viewModelType)
        {
            var directDependencies = ViewModelConventions.GetViewModelProperties(viewModelType).ToDictionary(p => p, GetDirectDependentProperties);

            var graph = new AdjacencyGraph<PropertyInfo, STaggedEdge<PropertyInfo, string>>();

            foreach (var directDependency in directDependencies)
            {
                var property = directDependency.Key;
                graph.AddVertex(property);

                foreach (var dependentProperty in directDependency.Value)
                {
                    var sub = dependentProperty.SubPath;
                    var propertyType = property.PropertyType;
                    if (GetCollectionType(propertyType) != null) propertyType = GetCollectionType(propertyType);

                    if (String.IsNullOrEmpty(sub) && ViewModelConventions.IsViewModel(propertyType))
                        sub = "*";

                    graph.AddEdge(new STaggedEdge<PropertyInfo, string>(property, dependentProperty.Property, sub));
                }
            }

            return graph;
        }
Exemplo n.º 7
0
        private static IVertexAndEdgeListGraph<PipeGraphVertex, Edge<PipeGraphVertex>> CreateGraphOfPipeSystem(PipeGraphVertex firstVertex)
        {
            var graph = new AdjacencyGraph<PipeGraphVertex, Edge<PipeGraphVertex>>(false);
            var verticesSeen = new HashSet<PipeGraphVertex>();
            var verticesToCheck = new Stack<PipeGraphVertex>();
            verticesToCheck.Push(firstVertex);

            while (verticesToCheck.Any())
            {
                var vertexToCheck = verticesToCheck.Pop();
                if (verticesSeen.Contains(vertexToCheck)) continue;

                var sendsTo = GetVerticesYouSendMessagesTo(vertexToCheck);
                var receivesFrom = GetVerticesYouReceiveMessagesFrom(vertexToCheck);

                foreach (var vertex in sendsTo) verticesToCheck.Push(vertex);
                foreach (var vertex in receivesFrom) verticesToCheck.Push(vertex);

                graph.AddVertex(vertexToCheck);

                graph.AddVerticesAndEdgeRange(sendsTo.Select(v => new Edge<PipeGraphVertex>(vertexToCheck, v)));
                graph.AddVerticesAndEdgeRange(receivesFrom.Select(v => new Edge<PipeGraphVertex>(v, vertexToCheck)));

                verticesSeen.Add(vertexToCheck);
            }

            return graph;
        }
Exemplo n.º 8
0
        public override void Render(Context context, TextWriter result)
        {
            // init modules context
            ModulesContext modules = DotLiquidModules.ContextExtractor.GetOrAddModulesContext(context);
            
            // allow module name to be supplied as a variable, makes sense when you supply modules in the Model
            object evalName = context[_moduleName];
            string modName = evalName != null ? Convert.ToString(evalName) : _moduleName;
            
            // remember modules that were already loaded
            Dictionary<string, bool> alreadyLoaded = new Dictionary<string, bool>();
            foreach (string moduleName in modules.ModuleIndex.Keys)
            {
                alreadyLoaded[moduleName] = true;
            }

            // add module to context, get its dependencies in graph
            AdjacencyGraph<Module, Edge<Module>> dependencyGraph = new AdjacencyGraph<Module, Edge<Module>>(true);
            AddModuleToContextByName(modName, modules, context, dependencyGraph);

            // add dependency tree into context's dependency list
            foreach (Module module in dependencyGraph.TopologicalSort())
            {
                if (!alreadyLoaded.ContainsKey(module.ModuleName))
                {
                    modules.DependencyOrder.Add(module);
                }
            }
        }
Exemplo n.º 9
0
		private static AdjacencyGraph<string, Edge<string>> BuildReferencesGraph(out Dictionary<string, string> servers)
		{
			servers = new Dictionary<string, string>();

			var graph = new AdjacencyGraph<string, Edge<string>>();
			foreach (var serverName in Args.ServerNames.Split('|'))
			{
				var projectsPath = Paths.ProjectsFolder(serverName);
				foreach (var projectFolder in Directory.GetDirectories(projectsPath))
				{
					var projectName = Path.GetFileName(projectFolder);
					var referencesFolder = Path.Combine(projectFolder, Args.ReferencesFolder);

					servers.Add(projectName, serverName);

					if (!Directory.Exists(referencesFolder))
						continue;

					var referenceFiles = Directory.GetFiles(referencesFolder).Select(Path.GetFileNameWithoutExtension);

					graph.AddVerticesAndEdgeRange(referenceFiles.Select(referenceName => new Edge<string>(referenceName, projectName)));
				}
			}

			return graph;
		}
        public void CheckPredecessorDoubleLineGraph()
        {
            AdjacencyGraph<int, Edge<int>> g = new AdjacencyGraph<int, Edge<int>>(true);
            g.AddVertex(1);
            g.AddVertex(2);
            g.AddVertex(3);

            Edge<int> e12 = new Edge<int>(1, 2); g.AddEdge(e12);
            Edge<int> e23 = new Edge<int>(2, 3); g.AddEdge(e23);
            Edge<int> e13 = new Edge<int>(1, 3); g.AddEdge(e13);

            var dij = new DijkstraShortestPathAlgorithm<int, Edge<int>>(g, e => 1);
            var vis = new VertexPredecessorRecorderObserver<int, Edge<int>>();
            using(vis.Attach(dij))
                dij.Compute(1);

            IEnumerable<Edge<int>> path;
            Assert.IsTrue(vis.TryGetPath(2, out path));
            var col = path.ToList();
            Assert.AreEqual(1, col.Count);
            Assert.AreEqual(e12, col[0]);

            Assert.IsTrue(vis.TryGetPath(3, out path));
            col = path.ToList();
            Assert.AreEqual(1, col.Count);
            Assert.AreEqual(e13, col[0]);
        }
        public void CheckPredecessorLineGraph()
        {
            AdjacencyGraph<int, Edge<int>> g = new AdjacencyGraph<int, Edge<int>>(true);
            g.AddVertex(1);
            g.AddVertex(2);
            g.AddVertex(3);

            Edge<int> e12 = new Edge<int>(1, 2); g.AddEdge(e12);
            Edge<int> e23 = new Edge<int>(2, 3); g.AddEdge(e23);

            Dictionary<Edge<int>, double> weights =
                DijkstraShortestPathAlgorithm<int, Edge<int>>.UnaryWeightsFromEdgeList(g);
            DijkstraShortestPathAlgorithm<int, Edge<int>> dij = new DijkstraShortestPathAlgorithm<int, Edge<int>>(g, weights);
            VertexPredecessorRecorderObserver<int, Edge<int>> vis = new VertexPredecessorRecorderObserver<int, Edge<int>>();
            vis.Attach(dij);
            dij.Compute(1);

            IList<Edge<int>> col = vis.Path(2);
            Assert.AreEqual(1, col.Count);
            Assert.AreEqual(e12, col[0]);

            col = vis.Path(3);
            Assert.AreEqual(2, col.Count);
            Assert.AreEqual(e12, col[0]);
            Assert.AreEqual(e23, col[1]);
        }
Exemplo n.º 12
0
        public QGPathFinder(FloorPlan floorPlan)
        {
            this.messages += "- Checking Floor Plan...\n";
            graph = new AdjacencyGraph<string, Edge<string>>(true);
            edgeCost = new Dictionary<Edge<string>, double>(graph.EdgeCount);
            this.fp = floorPlan;

            if (this.fp.getStartTile() != null)
            {
                this.messages += "    Start Point is OK...\n";
                startPoint = this.fp.getStartTile().Position.X + "_" + this.fp.getStartTile().Position.Y;
            }
            else
            {
                this.messages += "    Start Point is not valid...\n";
                startPoint = "4_4";
            }

            if (this.fp.getTargetTile() != null)
            {
                this.messages += "    Target Point is OK...\n";
                targetPoint = this.fp.getTargetTile().Position.X + "_" + this.fp.getTargetTile().Position.Y;
            }
            else
            {
                this.messages += "    Target Point is not valid...\n";
                targetPoint = "4_6";
            }

            buildGraph();
        }
Exemplo n.º 13
0
 public RouteFinder(IGameDataProvider gameDataProvider)
 {
     provider = gameDataProvider;
     logger = LogManager.GetCurrentClassLogger();
     graph = new AdjacencyGraph<StarSystem, Edge<StarSystem>>();
     weights = new Dictionary<Edge<StarSystem>, double>();
 }
 public void FileDependency()
 {
     AdjacencyGraph<string, Edge<string>> g = new AdjacencyGraph<string, Edge<string>>();
     GraphFactory.FileDependency(g);
     this.Compute(g);
     this.ComputeCriticalPath(g);
 }
Exemplo n.º 15
0
        public QGPathFinder(Status status, MainForm parent)
        {
            m_parent = parent;
            m_status = status;

            graph = new AdjacencyGraph<string, Edge<string>>(true);
            edgeCost = new Dictionary<Edge<string>, double>(graph.EdgeCount);
            this.fp = m_status.floorPlan;
            if (this.m_status.position != null)
            {
                startPoint = this.m_status.position.location.X + "_" + this.m_status.position.location.Y;
                m_parent.PostMessage("start: " + startPoint);
            }
            else
            {
                startPoint = "4_4";
            }
            if (this.m_status.endPoint!= null)
            {
                targetPoint = this.m_status.endPoint.X + "_" + this.m_status.endPoint.Y;
                m_parent.PostMessage("end: " + targetPoint);
            }
            else
            {
                targetPoint = "4_6";
            }

            buildGraph();
        }
Exemplo n.º 16
0
        /// <summary>
        /// Przerabia graf na string z odnalezionymi paternami
        /// </summary>
        /// <param name="g"></param>
        /// <returns></returns>
        public string FindAllPatterns(AdjacencyGraph<Node, Edge<Node>> g)
        {
            bool nodesStillInGraph = true;
            while (nodesStillInGraph)
            {
                var decisionNodes = g.Vertices.Where(x => x.Type == NodeType.DecisionNode).ToList();
                var forkNodes = g.Vertices.Where(x => x.Type == NodeType.ForkNode).ToList();
                if (decisionNodes.Count == 0 && forkNodes.Count == 0)
                {
                    nodesStillInGraph = false;
                    continue;
                }
                g = FindLoopPattern(g);
                g = FindSeqPattern(g);

                g = FindDecisionPattern(g);
                g = FindSeqPattern(g);

                g = FindParPattern(g);
                g = FindSeqPattern(g);
            }

            if (g.Vertices.Count() == 3 && g.Edges.Count() == 2)
            {
                var start = g.Vertices.Where(x => x.Type == NodeType.InitalNode).ToList().FirstOrDefault();
                var end = g.Vertices.Where(x => x.Type == NodeType.ActivityFinalNode).ToList().FirstOrDefault();
                var body = g.Vertices.Where(x => x != start && x != end).ToList().FirstOrDefault();
                return "seqseq(" + start.Name + "," + body.Name + "," + end.Name + ")";
            }
            return "ERROR";
        }
        public void IsolatedVertex()
        {
            AdjacencyGraph<int, Edge<int>> g = new AdjacencyGraph<int, Edge<int>>(true);
            g.AddVertex(0);

            target = new CyclePoppingRandomTreeAlgorithm<int, Edge<int>>(g);
            target.RandomTree();
        }
 public void EmptyGraph()
 {
     IVertexListGraph<string, Edge<string>> g = new AdjacencyGraph<string, Edge<string>>(true);
     StronglyConnectedComponentsAlgorithm<string, Edge<String>> strong = new StronglyConnectedComponentsAlgorithm<string, Edge<String>>(g);
     strong.Compute();
     Assert.AreEqual(0, strong.ComponentCount);
     checkStrong(strong);
 }
 public void Init()
 {
     this.parents = new Dictionary<int, int>();
     this.distances = new Dictionary<int, int>();
     this.currentDistance = 0;
     this.algo = null;
     this.g = null;
 }
        static AdjacencyGraph<Vertex, Edge<Vertex>> CreateAdjacencyGraph(StateMachineGraph data)
        {
            var graph = new AdjacencyGraph<Vertex, Edge<Vertex>>();

            graph.AddVertexRange(data.Vertices);
            graph.AddEdgeRange(data.Edges.Select(x => new Edge<Vertex>(x.From, x.To)));
            return graph;
        }
Exemplo n.º 21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GraphBuilder2"/> class.
        /// </summary>
        /// <param name="bidirectional">
        /// Specify if the graph must be build using both edges directions.
        /// </param>
        public PathFinder(bool bidirectional)
        {
            this.bidirectional = bidirectional;

            factory = null;
            strings = new List<ILineString>();
            graph   = new AdjacencyGraph<Coordinate, IEdge<Coordinate>>(true);
        }
        public void IsolatedVerticesWithRoot()
        {
            var g = new AdjacencyGraph<int, Edge<int>>(true);
            g.AddVertex(0);
            g.AddVertex(1);

            var target = new CyclePoppingRandomTreeAlgorithm<int, Edge<int>>(g);
            target.RandomTreeWithRoot(0);
        }
 public void OneTwo()
 {
     var graph = new AdjacencyGraph<int, Edge<int>>();
     graph.AddVertex(1);
     graph.AddVertex(2);
     graph.AddEdge(new Edge<int>(1, 2));
     var t = new TopologicalSortAlgorithm<int, Edge<int>>(graph);
     t.Compute();
 }
        public void OneVertex()
        {
            AdjacencyGraph<string, Edge<string>> g = new AdjacencyGraph<string, Edge<string>>(true);
            g.AddVertex("test");
            StronglyConnectedComponentsAlgorithm<string, Edge<String>> strong = new StronglyConnectedComponentsAlgorithm<string, Edge<String>>(g);
            strong.Compute();
            Assert.AreEqual(1, strong.ComponentCount);

            checkStrong(strong);
        }
Exemplo n.º 25
0
        //graph, tgraph, sourceNode, endNode, weight
        public static void AddEdgeToBoth(AdjacencyGraph<string, Edge<string>> graph, AdjacencyGraph<string, Edge<string>> tGraph, Dictionary<Edge<string>, double> edgeCost, Dictionary<Edge<string>, double> tEdgeCost, string sourceString, string endString, int weight)
        {
            Edge<string> curEdge = new Edge<string>(sourceString, endString);
            graph.AddEdge(curEdge);
            edgeCost.Add(curEdge, weight);

            Edge<string> transposeEdge = new Edge<string>(endString, sourceString);
            tGraph.AddEdge(transposeEdge);
            tEdgeCost.Add(transposeEdge, weight);
        }
        public void RootIsNotAccessible()
        {
            AdjacencyGraph<int, Edge<int>> g = new AdjacencyGraph<int, Edge<int>>(true);
            g.AddVertex(0);
            g.AddVertex(1);
            g.AddEdge(new Edge<int>(0, 1));

            target = new CyclePoppingRandomTreeAlgorithm<int, Edge<int>>(g);
            target.RandomTreeWithRoot(0);
        }
Exemplo n.º 27
0
 private static AdjacencyGraph<Node, Edge<Node>> ReadGraph(string filename)
 {
     var graph = new AdjacencyGraph<Node, Edge<Node>>();
     using (var reader = XmlReader.Create(filename))
     {
         graph.DeserializeFromGraphML(reader,
                 id => new Node(),
                 (source, target, id) => new Edge<Node>(source, target));
     }
     return graph;
 }
Exemplo n.º 28
0
        public DoorAndClueManager(MapCycleReducer reducedMap, int startVertex)
        {
            this.mapNoCycles = reducedMap;
            this.startVertex = startVertex;

            lockDependencyGraph = new AdjacencyGraph<int, Edge<int>>();
            doorMap = new Dictionary<int, Door>();
            clueMap = new Dictionary<int, List<Clue>>();
            objectiveMap = new Dictionary<int, Objective>();
            objectiveRoomMap = new Dictionary<int, List<Objective>>();
        }
        public void TwoVertexOnEdge()
        {
            AdjacencyGraph<string, Edge<string>> g = new AdjacencyGraph<string, Edge<string>>(true);
            g.AddVertex("v1");
            g.AddVertex("v2");
            g.AddEdge(new Edge<string>("v1", "v2"));
            StronglyConnectedComponentsAlgorithm<string, Edge<String>> strong = new StronglyConnectedComponentsAlgorithm<string, Edge<String>>(g);
            strong.Compute();
            Assert.AreEqual(2, strong.ComponentCount);

            checkStrong(strong);
        }
Exemplo n.º 30
0
        public IEnumerable<MapSolarSystemEdge> NearestRoute(long fromSolarSystemID, long toSolarSystemID, bool safeOnly = false)
        {
            eveGraph = new AdjacencyGraph<SolarSystem, Edge<SolarSystem>>(); // Eve universe
                getPathCache = new Dictionary<long, TryFunc<SolarSystem, IEnumerable<Edge<SolarSystem>>>>(); // function cache

                var dbResult = (from s in context.SolarSystems
                                from e in s.ToSolarSystems
                                where s.security >= (safeOnly ? 0.5 : -20)
                                select new { From = s, To = e }).AsEnumerable();

                var edges = dbResult.Select(a => new Edge<SolarSystem>(a.From, a.To)).OrderBy(e => e.Source.solarSystemID).ToList();
                var vertices = context.SolarSystems;

                eveGraph.AddVertexRange(vertices); // Fill Graph
                eveGraph.AddEdgeRange(edges); // Fill Graph

                var allPathes = new List<IEnumerable<Edge<SolarSystem>>>();
                var result = new List<MapSolarSystemEdge>();
                var from = context.SolarSystems.Where(m => m.solarSystemID == fromSolarSystemID).SingleOrDefault();
                var linkedSystems = from system in context.SolarSystems
                                    where system.solarSystemID == toSolarSystemID
                                    && system.security >= (safeOnly ? 0.5 : -20)
                                    select system;
                TryFunc<SolarSystem, IEnumerable<Edge<SolarSystem>>> tryGetPath;
                if (getPathCache.ContainsKey(from.solarSystemID))
                {
                    tryGetPath = getPathCache[from.solarSystemID];
                }
                else
                {
                    tryGetPath = eveGraph.ShortestPathsDijkstra(v => 1, from);
                    getPathCache[from.solarSystemID] = tryGetPath;
                }
                foreach (var s in linkedSystems)
                {
                    IEnumerable<Edge<SolarSystem>> path;

                    if (tryGetPath(s, out path))
                    {
                        allPathes.Add(path);
                    }
                }

                var shortestPath = allPathes.OrderBy(p => p.Count()).FirstOrDefault();
                if (shortestPath == null)
                    return null;
                foreach (var item in shortestPath)
                {
                    result.Add(new MapSolarSystemEdge() { From = item.Source.solarSystemID, To = item.Target.solarSystemID });
                }
                return result;
        }
Exemplo n.º 31
0
    public void setGraph()
    {
        listEdgeNotInShortestGraph = new List <Edge <node> >();
        myGraph  = new AdjacencyGraph <node, Edge <node> >();
        edgeCost = new Dictionary <Edge <node>, float>(myRoad.Count);
        foreach (node node in myNode)
        {
            myGraph.AddVertex(node);
        }
        foreach (Road road in myRoad)
        {
            node        n1   = myNode[road.node1 - 1];
            node        n2   = myNode[road.node2 - 1];
            Edge <node> edge = new Edge <node>(n1, n2);
            myGraph.AddEdge(edge);
            edgeCost.Add(edge, road.length);
            if (contains(listEdgeNotInShortestGraph, edge)[0] != 1)
            {
                listEdgeNotInShortestGraph.Add(edge);
            }
        }

        listEdgeShortestGraph = new List <Edge <node> >();
    }
Exemplo n.º 32
0
        public void Construction()
        {
            var graph1 = new AdjacencyGraph <int, Edge <int> >();
            var graph2 = new AdjacencyGraph <int, Edge <int> >();

            // Value type
            CheckEdge(
                new CondensedEdge <int, Edge <int>, AdjacencyGraph <int, Edge <int> > >(graph1, graph2),
                graph1,
                graph2);
            CheckEdge(
                new CondensedEdge <int, Edge <int>, AdjacencyGraph <int, Edge <int> > >(graph2, graph1),
                graph2,
                graph1);
            CheckEdge(
                new CondensedEdge <int, Edge <int>, AdjacencyGraph <int, Edge <int> > >(graph1, graph1),
                graph1,
                graph1);

            // Reference type
            var graph3 = new AdjacencyGraph <TestVertex, Edge <TestVertex> >();
            var graph4 = new AdjacencyGraph <TestVertex, Edge <TestVertex> >();

            CheckEdge(
                new CondensedEdge <TestVertex, Edge <TestVertex>, AdjacencyGraph <TestVertex, Edge <TestVertex> > >(graph3, graph4),
                graph3,
                graph4);
            CheckEdge(
                new CondensedEdge <TestVertex, Edge <TestVertex>, AdjacencyGraph <TestVertex, Edge <TestVertex> > >(graph4, graph3),
                graph4,
                graph3);
            CheckEdge(
                new CondensedEdge <TestVertex, Edge <TestVertex>, AdjacencyGraph <TestVertex, Edge <TestVertex> > >(graph3, graph3),
                graph3,
                graph3);
        }
Exemplo n.º 33
0
        public void Constructor()
        {
            var graph = new AdjacencyGraph <int, Edge <int> >();

            var algorithm = new EulerianTrailAlgorithm <int, Edge <int> >(graph);

            AssertAlgorithmProperties(algorithm, graph);

            algorithm = new EulerianTrailAlgorithm <int, Edge <int> >(null, graph);
            AssertAlgorithmProperties(algorithm, graph);

            #region Local function

            void AssertAlgorithmProperties <TVertex, TEdge>(
                EulerianTrailAlgorithm <TVertex, TEdge> algo,
                IMutableVertexAndEdgeListGraph <TVertex, TEdge> g)
                where TEdge : IEdge <TVertex>
            {
                AssertAlgorithmState(algo, g);
                CollectionAssert.IsEmpty(algo.Circuit);
            }

            #endregion
        }
Exemplo n.º 34
0
        public void OneWeaklyConnectedComponent()
        {
            var edge12 = new Edge<int>(1, 2);
            var edge13 = new Edge<int>(1, 3);
            var edge23 = new Edge<int>(2, 3);
            var edge42 = new Edge<int>(4, 2);
            var edge43 = new Edge<int>(4, 3);

            var edge45 = new Edge<int>(4, 5);

            var edge56 = new Edge<int>(5, 6);
            var edge57 = new Edge<int>(5, 7);
            var edge76 = new Edge<int>(7, 6);

            var edge71 = new Edge<int>(7, 1);

            var edge89 = new Edge<int>(8, 9);

            var edge82 = new Edge<int>(8, 2);

            var graph = new AdjacencyGraph<int, Edge<int>>();
            graph.AddVerticesAndEdgeRange(new[]
            {
                edge12, edge13, edge23, edge42, edge43, edge45,
                edge56, edge57, edge76, edge71, edge89, edge82
            });

            IMutableBidirectionalGraph<AdjacencyGraph<int, Edge<int>>, CondensedEdge<int, Edge<int>, AdjacencyGraph<int, Edge<int>>>> condensedGraph =
                graph.CondensateWeaklyConnected<int, Edge<int>, AdjacencyGraph<int, Edge<int>>>();

            Assert.IsNotNull(condensedGraph);
            Assert.AreEqual(1, condensedGraph.VertexCount);
            Assert.AreEqual(0, condensedGraph.EdgeCount);
            CollectionAssert.AreEquivalent(graph.Vertices, condensedGraph.Vertices.ElementAt(0).Vertices);
            CollectionAssert.AreEquivalent(graph.Edges, condensedGraph.Vertices.ElementAt(0).Edges);
        }
Exemplo n.º 35
0
        public void TryGetPath()
        {
            {
                var recorder = new VertexPredecessorRecorderObserver <int, Edge <int> >();

                var graph = new AdjacencyGraph <int, Edge <int> >();

                var dfs = new DepthFirstSearchAlgorithm <int, Edge <int> >(graph);
                using (recorder.Attach(dfs))
                {
                    dfs.Compute();

                    // Vertex not in the graph
                    Assert.IsFalse(recorder.TryGetPath(2, out _));
                }
            }

            {
                var recorder = new VertexPredecessorRecorderObserver <int, Edge <int> >();

                var graph = new AdjacencyGraph <int, Edge <int> >();
                graph.AddVertexRange(new[] { 1, 2 });

                var dfs = new DepthFirstSearchAlgorithm <int, Edge <int> >(graph);
                using (recorder.Attach(dfs))
                {
                    dfs.Compute();

                    Assert.IsFalse(recorder.TryGetPath(2, out _));
                }
            }

            {
                var recorder = new VertexPredecessorRecorderObserver <int, Edge <int> >();

                // Graph without cycle
                var edge12 = new Edge <int>(1, 2);
                var edge13 = new Edge <int>(1, 3);
                var edge14 = new Edge <int>(1, 4);
                var edge24 = new Edge <int>(2, 4);
                var edge31 = new Edge <int>(3, 1);
                var edge33 = new Edge <int>(3, 3);
                var edge34 = new Edge <int>(3, 4);
                var graph  = new AdjacencyGraph <int, Edge <int> >();
                graph.AddVerticesAndEdgeRange(new[]
                {
                    edge12, edge13, edge14, edge24, edge31, edge33, edge34
                });

                var dfs = new DepthFirstSearchAlgorithm <int, Edge <int> >(graph);
                using (recorder.Attach(dfs))
                {
                    dfs.Compute();

                    Assert.IsTrue(recorder.TryGetPath(4, out IEnumerable <Edge <int> > path));
                    CollectionAssert.AreEqual(new[] { edge12, edge24 }, path);
                }
            }

            {
                var recorder = new VertexPredecessorRecorderObserver <int, Edge <int> >();

                // Graph with cycle
                var edge12 = new Edge <int>(1, 2);
                var edge13 = new Edge <int>(1, 3);
                var edge14 = new Edge <int>(1, 4);
                var edge24 = new Edge <int>(2, 4);
                var edge31 = new Edge <int>(3, 1);
                var edge33 = new Edge <int>(3, 3);
                var edge34 = new Edge <int>(3, 4);
                var edge41 = new Edge <int>(4, 1);
                var graph  = new AdjacencyGraph <int, Edge <int> >();
                graph.AddVerticesAndEdgeRange(new[]
                {
                    edge12, edge13, edge14, edge24, edge31, edge33, edge34, edge41
                });

                var dfs = new DepthFirstSearchAlgorithm <int, Edge <int> >(graph);
                using (recorder.Attach(dfs))
                {
                    dfs.Compute();

                    Assert.IsTrue(recorder.TryGetPath(4, out IEnumerable <Edge <int> > path));
                    CollectionAssert.AreEqual(new[] { edge12, edge24 }, path);
                }
            }
        }
Exemplo n.º 36
0
        public void DeserializeFromGraphML_Throws()
        {
            // ReSharper disable AssignNullToNotNullAttribute
            // Filepath
            Assert.Throws <ArgumentNullException>(
                () => ((AdjacencyGraph <string, Edge <string> >)null).DeserializeFromGraphML(
                    GetGraphFilePath(TestGraphFileName),
                    id => id,
                    (source, target, id) => new Edge <string>(source, target)));

            var graph = new AdjacencyGraph <string, Edge <string> >();

            Assert.Throws <ArgumentException>(
                () => graph.DeserializeFromGraphML(
                    (string)null,
                    id => id,
                    (source, target, id) => new Edge <string>(source, target)));

            Assert.Throws <ArgumentException>(
                () => graph.DeserializeFromGraphML(
                    "",
                    id => id,
                    (source, target, id) => new Edge <string>(source, target)));

            Assert.Throws <ArgumentNullException>(
                () => graph.DeserializeFromGraphML <string, Edge <string>, AdjacencyGraph <string, Edge <string> > >(
                    GetGraphFilePath(TestGraphFileName),
                    null,
                    (source, target, id) => new Edge <string>(source, target)));

            Assert.Throws <ArgumentNullException>(
                () => graph.DeserializeFromGraphML <string, Edge <string>, AdjacencyGraph <string, Edge <string> > >(
                    GetGraphFilePath(TestGraphFileName),
                    id => id,
                    null));

            // Text reader
            Assert.Throws <ArgumentNullException>(
                () => graph.DeserializeFromGraphML(
                    (TextReader)null,
                    id => id,
                    (source, target, id) => new Edge <string>(source, target)));

            using (var reader = new StreamReader(GetGraphFilePath(TestGraphFileName)))
            {
                Assert.Throws <ArgumentNullException>(
                    () => ((AdjacencyGraph <string, Edge <string> >)null).DeserializeFromGraphML(
                        reader,
                        id => id,
                        (source, target, id) => new Edge <string>(source, target)));

                Assert.Throws <ArgumentNullException>(
                    () => graph.DeserializeFromGraphML <string, Edge <string>, AdjacencyGraph <string, Edge <string> > >(
                        reader,
                        null,
                        (source, target, id) => new Edge <string>(source, target)));

                Assert.Throws <ArgumentNullException>(
                    () => graph.DeserializeFromGraphML <string, Edge <string>, AdjacencyGraph <string, Edge <string> > >(
                        reader,
                        id => id,
                        null));
            }

            // XML reader
            Assert.Throws <ArgumentNullException>(
                () => graph.DeserializeFromGraphML(
                    (XmlReader)null,
                    id => id,
                    (source, target, id) => new Edge <string>(source, target)));

            using (XmlReader reader = XmlReader.Create(GetGraphFilePath(TestGraphFileName)))
            {
                Assert.Throws <ArgumentNullException>(
                    () => ((AdjacencyGraph <string, Edge <string> >)null).DeserializeFromGraphML(
                        reader,
                        id => id,
                        (source, target, id) => new Edge <string>(source, target)));

                Assert.Throws <ArgumentNullException>(
                    () => graph.DeserializeFromGraphML <string, Edge <string>, AdjacencyGraph <string, Edge <string> > >(
                        reader,
                        null,
                        (source, target, id) => new Edge <string>(source, target)));

                Assert.Throws <ArgumentNullException>(
                    () => graph.DeserializeFromGraphML <string, Edge <string>, AdjacencyGraph <string, Edge <string> > >(
                        reader,
                        id => id,
                        null));
            }
            // ReSharper restore AssignNullToNotNullAttribute
        }
Exemplo n.º 37
0
        static void Main(string[] args)
        {
            var graph = new AdjacencyGraph <int, Edge <int> >();

            graph.AddVertex(1);
            graph.AddVertex(2);
            graph.AddVertex(3);
            graph.AddVertex(4);

            //Console.WriteLine(graph.VertexCount);
            //var v = graph.Vertices.First();
            //Console.WriteLine(v);

            var e12 = new Edge <int>(1, 2);
            var e23 = new Edge <int>(2, 3);
            var e34 = new Edge <int>(3, 4);
            var e14 = new Edge <int>(1, 4);
            var e24 = new Edge <int>(2, 4);


            //var graph = new AdjacencyGraph<int, Edge<int>>();
            graph.AddEdge(e12);
            graph.AddEdge(e23);
            graph.AddEdge(e34);
            graph.AddEdge(e14);
            graph.AddEdge(e24);

            Console.WriteLine("Rzad grafu G wynosi: " + graph.VertexCount);

            Console.WriteLine("Rozmiar grafu G wynosi: " + graph.EdgeCount);

            for (int i = 0; i < graph.EdgeCount; i++)
            {
                Degree(graph.Edges.ToList()[i]);
            }

            for (int i = 1; i <= graphDegree.Count; i++)
            {
                Console.WriteLine("deg(" + i + "): " + graphDegree[i]);
            }
            Console.Write("Ciag stopni grafu G:  ");
            foreach (int d in graphDegree.Select(x => x.Value).OrderBy(x => x))
            {
                Console.Write(d + ", ");
            }



            //Dictionary<Edge<int>, double> edgeCost = new Dictionary<Edge<int>, double>(graph.EdgeCount);

            //DijkstraShortestPathAlgorithm<int, Edge<int>> dijkstra = new DijkstraShortestPathAlgorithm<int, Edge<int>>(graph, AlgorithmExtensions.GetIndexer<Edge<int>, double>(edgeCost));

            //// Attach a Vertex Predecessor Recorder Observer to give us the paths
            //QuickGraph.Algorithms.Observers.VertexPredecessorRecorderObserver<int, Edge<int>> predecessorObserver = new QuickGraph.Algorithms.Observers.VertexPredecessorRecorderObserver<int, Edge<int>>();
            //predecessorObserver.Attach(dijkstra);

            //// attach a distance observer to give us the shortest path distances
            //VertexDistanceRecorderObserver<int, Edge<int>> distObserver = new VertexDistanceRecorderObserver<int, Edge<int>>(AlgorithmExtensions.GetIndexer<Edge<int>, double>(edgeCost));
            //distObserver.Attach(dijkstra);

            //// Run the algorithm with A set to be the source
            //dijkstra.Compute(1);
            //Console.WriteLine(graph.(3));

            //foreach (var edges in graph.Edges)
            //    Console.WriteLine(edges);
            //// graph.AddEdge();
            //foreach (var vertex in graph.Vertices)
            //    foreach (var edge in graph.OutEdges(vertex))
            //        Console.WriteLine(edge);
            Console.ReadKey();
        }
Exemplo n.º 38
0
        public void BuildGraphAndSearchShortestPathUsingGeometryUnion()
        {
            IGeometry edges = a.Union(b).Union(c).Union(d).Union(e);

            Assert.IsNotNull(edges);
            Assert.IsTrue(edges.GetType() == typeof(MultiLineString));
            Assert.Greater(edges.NumGeometries, 0);
            foreach (IGeometry edge in ((GeometryCollection)edges).Geometries)
            {
                Assert.IsNotNull(edge);
                Assert.IsTrue(edge.GetType() == typeof(LineString));
                Debug.WriteLine(edge);
            }

            // Build graph
            IDictionary <IEdge <IGeometry>, double>        consts = new Dictionary <IEdge <IGeometry>, double>(edges.NumGeometries);
            AdjacencyGraph <IGeometry, IEdge <IGeometry> > graph  = new AdjacencyGraph <IGeometry, IEdge <IGeometry> >(true);

            foreach (ILineString str in ((GeometryCollection)edges).Geometries)
            {
                // Add vertex 1
                IGeometry vertex1 = str.StartPoint;
                Assert.IsNotNull(vertex1);
                if (!graph.ContainsVertex(vertex1))
                {
                    Debug.WriteLine(String.Format("Adding vertex {0} to the list", vertex1));
                    graph.AddVertex(vertex1);
                }
                else
                {
                    Debug.WriteLine(String.Format("Vertex {0} already present", vertex1));
                }

                // Add vertex 2
                IGeometry vertex2 = str.EndPoint;
                Assert.IsNotNull(vertex2);
                if (!graph.ContainsVertex(vertex2))
                {
                    Debug.WriteLine(String.Format("Adding vertex {0} to the list", vertex2));
                    graph.AddVertex(vertex2);
                }
                else
                {
                    Debug.WriteLine(String.Format("Vertex {0} already present", vertex2));
                }

                // Compute weight
                double weight = weightComputer(str);
                Assert.Greater(weight, 0.0);

                // Add edge for 1 => 2
                IEdge <IGeometry> edge1 = new Edge <IGeometry>(vertex1, vertex2);
                Assert.IsNotNull(edge1);
                graph.AddEdge(edge1);
                consts.Add(edge1, weight);

                // Add edge for 2 => 1
                IEdge <IGeometry> edge2 = new Edge <IGeometry>(vertex2, vertex1);
                Assert.IsNotNull(edge2);
                graph.AddEdge(edge2);
                consts.Add(edge2, weight);
            }

            // Perform DijkstraShortestPathAlgorithm
            DijkstraShortestPathAlgorithm <IGeometry, IEdge <IGeometry> > dijkstra =
                new DijkstraShortestPathAlgorithm <IGeometry, IEdge <IGeometry> >(graph, consts);

            // attach a distance observer to give us the shortest path distances
            VertexDistanceRecorderObserver <IGeometry, IEdge <IGeometry> > distObserver =
                new VertexDistanceRecorderObserver <IGeometry, IEdge <IGeometry> >();

            distObserver.Attach(dijkstra);

            // Attach a Vertex Predecessor Recorder Observer to give us the paths
            VertexPredecessorRecorderObserver <IGeometry, IEdge <IGeometry> > predecessorObserver =
                new VertexPredecessorRecorderObserver <IGeometry, IEdge <IGeometry> >();

            predecessorObserver.Attach(dijkstra);

            // Run the algorithm
            Debug.WriteLine(String.Format("Starting algorithm from root vertex {0}", start));
            dijkstra.Compute(start);

            foreach (KeyValuePair <IGeometry, int> kvp in distObserver.Distances)
            {
                Debug.WriteLine(String.Format("Distance from root to node {0} is {1}",
                                              kvp.Key, kvp.Value));
            }
            foreach (KeyValuePair <IGeometry, IEdge <IGeometry> > kvp in predecessorObserver.VertexPredecessors)
            {
                Debug.WriteLine(String.Format(
                                    "If you want to get to {0} you have to enter through the IN edge {1}", kvp.Key, kvp.Value));
            }
            Check(graph, consts, predecessorObserver);

            // Detach the observers
            distObserver.Detach(dijkstra);
            predecessorObserver.Detach(dijkstra);
        }
        public void FloydWarshall_Throws()
        {
            // Without negative cycle
            var edge12 = new Edge <int>(1, 2);
            var edge23 = new Edge <int>(2, 3);
            var edge34 = new Edge <int>(3, 4);

            var negativeWeightGraph = new AdjacencyGraph <int, Edge <int> >();

            negativeWeightGraph.AddVerticesAndEdgeRange(new[]
            {
                edge12, edge23, edge34
            });

            var algorithm = new FloydWarshallAllShortestPathAlgorithm <int, Edge <int> >(
                negativeWeightGraph,
                e =>
            {
                if (e == edge12)
                {
                    return(12.0);
                }
                if (e == edge23)
                {
                    return(-23.0);
                }
                if (e == edge34)
                {
                    return(-34.0);
                }
                return(1.0);
            });

            Assert.DoesNotThrow(() => algorithm.Compute());

            // With negative cycle
            var edge41 = new Edge <int>(4, 1);

            var negativeCycleGraph = new AdjacencyGraph <int, Edge <int> >();

            negativeCycleGraph.AddVerticesAndEdgeRange(new[]
            {
                edge12, edge23, edge34, edge41
            });

            algorithm = new FloydWarshallAllShortestPathAlgorithm <int, Edge <int> >(
                negativeCycleGraph,
                e =>
            {
                if (e == edge12)
                {
                    return(12.0);
                }
                if (e == edge23)
                {
                    return(-23.0);
                }
                if (e == edge34)
                {
                    return(-34.0);
                }
                if (e == edge41)
                {
                    return(41.0);
                }
                return(1.0);
            });
            Assert.Throws <NegativeCycleGraphException>(() => algorithm.Compute());
        }
Exemplo n.º 40
0
        public void Clone()
        {
            var wrappedGraph = new AdjacencyGraph <int, Edge <int> >();

            var graph = new ArrayAdjacencyGraph <int, Edge <int> >(wrappedGraph);

            AssertEmptyGraph(graph);

            var clonedGraph = graph.Clone();

            Assert.IsNotNull(clonedGraph);
            AssertEmptyGraph(clonedGraph);

            clonedGraph = (ArrayAdjacencyGraph <int, Edge <int> >)((ICloneable)graph).Clone();
            Assert.IsNotNull(clonedGraph);
            AssertEmptyGraph(clonedGraph);

            wrappedGraph.AddVertexRange(new[] { 1, 2, 3 });
            graph = new ArrayAdjacencyGraph <int, Edge <int> >(wrappedGraph);
            AssertHasVertices(graph, new[] { 1, 2, 3 });
            AssertNoEdge(graph);

            clonedGraph = graph.Clone();
            Assert.IsNotNull(clonedGraph);
            AssertHasVertices(clonedGraph, new[] { 1, 2, 3 });
            AssertNoEdge(clonedGraph);

            clonedGraph = (ArrayAdjacencyGraph <int, Edge <int> >)((ICloneable)graph).Clone();
            Assert.IsNotNull(clonedGraph);
            AssertHasVertices(clonedGraph, new[] { 1, 2, 3 });
            AssertNoEdge(clonedGraph);

            var edge1 = new Edge <int>(1, 2);
            var edge2 = new Edge <int>(1, 3);
            var edge3 = new Edge <int>(2, 3);

            wrappedGraph.AddVerticesAndEdgeRange(new[] { edge1, edge2, edge3 });

            graph = new ArrayAdjacencyGraph <int, Edge <int> >(wrappedGraph);
            AssertHasVertices(graph, new[] { 1, 2, 3 });
            AssertHasEdges(graph, new[] { edge1, edge2, edge3 });

            clonedGraph = graph.Clone();
            Assert.IsNotNull(clonedGraph);
            AssertHasVertices(clonedGraph, new[] { 1, 2, 3 });
            AssertHasEdges(clonedGraph, new[] { edge1, edge2, edge3 });

            clonedGraph = (ArrayAdjacencyGraph <int, Edge <int> >)((ICloneable)graph).Clone();
            Assert.IsNotNull(clonedGraph);
            AssertHasVertices(clonedGraph, new[] { 1, 2, 3 });
            AssertHasEdges(clonedGraph, new[] { edge1, edge2, edge3 });

            wrappedGraph.AddVertex(4);
            graph = new ArrayAdjacencyGraph <int, Edge <int> >(wrappedGraph);
            AssertHasVertices(graph, new[] { 1, 2, 3, 4 });
            AssertHasEdges(graph, new[] { edge1, edge2, edge3 });

            clonedGraph = graph.Clone();
            Assert.IsNotNull(clonedGraph);
            AssertHasVertices(clonedGraph, new[] { 1, 2, 3, 4 });
            AssertHasEdges(clonedGraph, new[] { edge1, edge2, edge3 });

            clonedGraph = (ArrayAdjacencyGraph <int, Edge <int> >)((ICloneable)graph).Clone();
            Assert.IsNotNull(clonedGraph);
            AssertHasVertices(clonedGraph, new[] { 1, 2, 3, 4 });
            AssertHasEdges(clonedGraph, new[] { edge1, edge2, edge3 });
        }
Exemplo n.º 41
0
 static IEnumerable <BagColor> ColorsFor(AdjacencyGraph <BagColor, BagEdge> graph, BagColor color) => graph
 .Edges
 .Where(e => e.Target == color)
 .Select(e => e.Source);
Exemplo n.º 42
0
        public void Create()
        {
            var graph = new AdjacencyGraph <int, EquatableEdge <int> >();

            // With self edge
            int v = 0;

            RandomGraphFactory.Create(
                graph,
                () => ++ v,
                (source, target) => new EquatableEdge <int>(source, target),
                new Random(123456),
                5,
                10,
                true);
            AssertHasVertices(graph, new[] { 1, 2, 3, 4, 5 });
            AssertHasEdges(
                graph,
                new[]
            {
                new EquatableEdge <int>(1, 2),
                new EquatableEdge <int>(1, 2),
                new EquatableEdge <int>(1, 2),
                new EquatableEdge <int>(2, 1),
                new EquatableEdge <int>(3, 5),
                new EquatableEdge <int>(3, 1),
                new EquatableEdge <int>(4, 5),
                new EquatableEdge <int>(4, 4),
                new EquatableEdge <int>(4, 1),
                new EquatableEdge <int>(5, 3)
            });

            // Without self edge
            graph.Clear();
            v = 0;
            RandomGraphFactory.Create(
                graph,
                () => ++ v,
                (source, target) => new EquatableEdge <int>(source, target),
                new Random(123456),
                5,
                10,
                false);
            AssertHasVertices(graph, new[] { 1, 2, 3, 4, 5 });
            AssertHasEdges(
                graph,
                new[]
            {
                new EquatableEdge <int>(1, 2),
                new EquatableEdge <int>(1, 2),
                new EquatableEdge <int>(1, 2),
                new EquatableEdge <int>(2, 1),
                new EquatableEdge <int>(3, 5),
                new EquatableEdge <int>(3, 1),
                new EquatableEdge <int>(3, 1),
                new EquatableEdge <int>(4, 5),
                new EquatableEdge <int>(4, 1),
                new EquatableEdge <int>(5, 3)
            });

            // Different seed change generated graph
            graph.Clear();
            v = 0;
            RandomGraphFactory.Create(
                graph,
                () => ++ v,
                (source, target) => new EquatableEdge <int>(source, target),
                new Random(456789),
                5,
                10,
                true);
            AssertHasVertices(graph, new[] { 1, 2, 3, 4, 5 });
            AssertHasEdges(
                graph,
                new[]
            {
                new EquatableEdge <int>(1, 2),
                new EquatableEdge <int>(2, 2),
                new EquatableEdge <int>(2, 5),
                new EquatableEdge <int>(3, 4),
                new EquatableEdge <int>(3, 2),
                new EquatableEdge <int>(4, 5),
                new EquatableEdge <int>(4, 2),
                new EquatableEdge <int>(4, 2),
                new EquatableEdge <int>(5, 2),
                new EquatableEdge <int>(5, 3)
            });

            // On non empty graph, keep existing stuff
            graph.Clear();
            graph.AddVerticesAndEdge(new EquatableEdge <int>(6, 7));
            v = 0;
            RandomGraphFactory.Create(
                graph,
                () => ++ v,
                (source, target) => new EquatableEdge <int>(source, target),
                new Random(123456),
                5,
                10,
                true);
            AssertHasVertices(graph, new[] { 1, 2, 3, 4, 5, 6, 7 });
            AssertHasEdges(
                graph,
                new[]
            {
                new EquatableEdge <int>(6, 7),
                new EquatableEdge <int>(1, 2),
                new EquatableEdge <int>(1, 2),
                new EquatableEdge <int>(1, 2),
                new EquatableEdge <int>(2, 1),
                new EquatableEdge <int>(3, 5),
                new EquatableEdge <int>(3, 1),
                new EquatableEdge <int>(4, 5),
                new EquatableEdge <int>(4, 4),
                new EquatableEdge <int>(4, 1),
                new EquatableEdge <int>(5, 3)
            });
        }
Exemplo n.º 43
0
        public void Create_Throws()
        {
            var graph  = new AdjacencyGraph <int, Edge <int> >();
            var random = new Random();

            // ReSharper disable AssignNullToNotNullAttribute
            Assert.Throws <ArgumentNullException>(
                () => RandomGraphFactory.Create(
                    (IMutableVertexAndEdgeListGraph <int, Edge <int> >)null,
                    () => 1,
                    (source, target) => new Edge <int>(source, target),
                    random,
                    1, 1, false));
            Assert.Throws <ArgumentNullException>(
                () => RandomGraphFactory.Create(
                    graph,
                    null,
                    (source, target) => new Edge <int>(source, target),
                    random,
                    1, 1, false));
            Assert.Throws <ArgumentNullException>(
                () => RandomGraphFactory.Create(
                    graph,
                    () => 1,
                    null,
                    random,
                    1, 1, false));
            Assert.Throws <ArgumentNullException>(
                () => RandomGraphFactory.Create(
                    graph,
                    () => 1,
                    (source, target) => new Edge <int>(source, target),
                    null,
                    1, 1, false));
            Assert.Throws <ArgumentNullException>(
                () => RandomGraphFactory.Create(
                    (IMutableVertexAndEdgeListGraph <int, Edge <int> >)null,
                    null,
                    (source, target) => new Edge <int>(source, target),
                    random,
                    1, 1, false));
            Assert.Throws <ArgumentNullException>(
                () => RandomGraphFactory.Create(
                    (IMutableVertexAndEdgeListGraph <int, Edge <int> >)null,
                    () => 1,
                    null,
                    random,
                    1, 1, false));
            Assert.Throws <ArgumentNullException>(
                () => RandomGraphFactory.Create(
                    (IMutableVertexAndEdgeListGraph <int, Edge <int> >)null,
                    () => 1,
                    (source, target) => new Edge <int>(source, target),
                    null,
                    1, 1, false));
            Assert.Throws <ArgumentNullException>(
                () => RandomGraphFactory.Create(
                    graph,
                    null,
                    null,
                    random,
                    1, 1, false));
            Assert.Throws <ArgumentNullException>(
                () => RandomGraphFactory.Create(
                    graph,
                    null,
                    (source, target) => new Edge <int>(source, target),
                    null,
                    1, 1, false));
            Assert.Throws <ArgumentNullException>(
                () => RandomGraphFactory.Create(
                    graph,
                    () => 1,
                    null,
                    null,
                    1, 1, false));
            Assert.Throws <ArgumentNullException>(
                () => RandomGraphFactory.Create(
                    graph,
                    null,
                    null,
                    null,
                    1, 1, false));
            Assert.Throws <ArgumentNullException>(
                () => RandomGraphFactory.Create(
                    (IMutableVertexAndEdgeListGraph <int, Edge <int> >)null,
                    () => 1,
                    null,
                    null,
                    1, 1, false));
            Assert.Throws <ArgumentNullException>(
                () => RandomGraphFactory.Create(
                    (IMutableVertexAndEdgeListGraph <int, Edge <int> >)null,
                    null,
                    (source, target) => new Edge <int>(source, target),
                    null,
                    1, 1, false));
            Assert.Throws <ArgumentNullException>(
                () => RandomGraphFactory.Create(
                    (IMutableVertexAndEdgeListGraph <int, Edge <int> >)null,
                    null,
                    null,
                    random,
                    1, 1, false));
            Assert.Throws <ArgumentNullException>(
                () => RandomGraphFactory.Create(
                    (IMutableVertexAndEdgeListGraph <int, Edge <int> >)null,
                    null,
                    null,
                    null,
                    1, 1, false));
            // ReSharper restore AssignNullToNotNullAttribute
            Assert.Throws <ArgumentOutOfRangeException>(
                () => RandomGraphFactory.Create(
                    graph,
                    () => 1,
                    (source, target) => new Edge <int>(source, target),
                    random,
                    -1, 1, false));
            Assert.Throws <ArgumentOutOfRangeException>(
                () => RandomGraphFactory.Create(
                    graph,
                    () => 1,
                    (source, target) => new Edge <int>(source, target),
                    random,
                    0, 1, false));
            Assert.Throws <ArgumentOutOfRangeException>(
                () => RandomGraphFactory.Create(
                    graph,
                    () => 1,
                    (source, target) => new Edge <int>(source, target),
                    random,
                    1, -1, false));
            Assert.Throws <ArgumentOutOfRangeException>(
                () => RandomGraphFactory.Create(
                    graph,
                    () => 1,
                    (source, target) => new Edge <int>(source, target),
                    random,
                    1, 0, false));
            Assert.Throws <ArgumentOutOfRangeException>(
                () => RandomGraphFactory.Create(
                    graph,
                    () => 1,
                    (source, target) => new Edge <int>(source, target),
                    random,
                    0, 0, false));
            Assert.Throws <ArgumentOutOfRangeException>(
                () => RandomGraphFactory.Create(
                    graph,
                    () => 1,
                    (source, target) => new Edge <int>(source, target),
                    random,
                    -1, -1, false));
        }
Exemplo n.º 44
0
        public static (double, BidirectionalGraph <string, EquatableEdge <string> >) Get(AdjacencyGraph <int, Edge <int> > graph)
        {
            var tsp = new tsp();

            foreach (var v in graph.Vertices)
            {
                tsp.AddVertex(v);
            }
            foreach (var e in graph.Edges)
            {
                tsp.AddDirectedEdge(e.Source, e.Target, 1.0);
            }

            var algorithm = new TSP <string, EquatableEdge <string>, BidirectionalGraph <string, EquatableEdge <string> > >(tsp.Graph, tsp.GetWeightsFunc());

            algorithm.Compute();
            return(algorithm.BestCost, algorithm.ResultPath);
        }
Exemplo n.º 45
0
        public static (double, BidirectionalGraph <string, TaggedEdge <string, string> >) Get(AdjacencyGraph <string, TaggedEdge <string, string> > graph)
        {
            var tsp = new tsp();

            foreach (var v in graph.Vertices)
            {
                tsp.AddVertex(v);
            }
            foreach (var e in graph.Edges)
            {
                tsp.AddDirectedEdge(e.Source, e.Target, double.Parse(e.Tag));
            }

            var weightFunc = tsp.GetWeightsFunc();
            var algorithm  = new TSP <string, EquatableEdge <string>, BidirectionalGraph <string, EquatableEdge <string> > >(tsp.Graph, weightFunc);

            algorithm.Compute();

            var path = algorithm.ResultPath;

            if (path != null)
            {
                var results = new results();
                foreach (var v in path.Vertices)
                {
                    results.AddVertex(v);
                }
                foreach (var e in path.Edges)
                {
                    results.AddDirectedEdge(e.Source, e.Target, weightFunc(e));
                }
                return(algorithm.BestCost, results.Graph);
            }
            else
            {
                return(algorithm.BestCost, null);
            }
        }
Exemplo n.º 46
0
        public void Constructor_Throws()
        {
            // ReSharper disable ObjectCreationAsStatement
            // ReSharper disable AssignNullToNotNullAttribute
            var graph = new AdjacencyGraph <int, Edge <int> >();

            Func <int, double>        Heuristic = v => 1.0;
            Func <Edge <int>, double> Weights   = e => 1.0;

            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, Weights, Heuristic));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(graph, null, Heuristic));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(graph, Weights, null));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(graph, null, null));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, null, Heuristic));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, Weights, null));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, null, Heuristic));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, null, null));

            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, Weights, Heuristic, DistanceRelaxers.CriticalDistance));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(graph, null, Heuristic, DistanceRelaxers.CriticalDistance));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(graph, Weights, null, DistanceRelaxers.CriticalDistance));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(graph, Weights, Heuristic, null));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(graph, Weights, null, null));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(graph, null, Heuristic, null));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(graph, null, null, DistanceRelaxers.CriticalDistance));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, Weights, Heuristic, null));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, Weights, null, DistanceRelaxers.CriticalDistance));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, null, Heuristic, DistanceRelaxers.CriticalDistance));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, Weights, null, null));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, null, Heuristic, null));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, null, null, DistanceRelaxers.CriticalDistance));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, null, null, null));

            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, null, Weights, Heuristic, DistanceRelaxers.CriticalDistance));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, graph, null, Heuristic, DistanceRelaxers.CriticalDistance));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, graph, Weights, null, DistanceRelaxers.CriticalDistance));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, graph, Weights, Heuristic, null));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, graph, Weights, null, null));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, graph, null, Heuristic, null));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, graph, null, null, DistanceRelaxers.CriticalDistance));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, null, Weights, Heuristic, null));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, null, Weights, null, DistanceRelaxers.CriticalDistance));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, null, null, Heuristic, DistanceRelaxers.CriticalDistance));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, null, Weights, null, null));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, null, null, Heuristic, null));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, null, null, null, DistanceRelaxers.CriticalDistance));
            Assert.Throws <ArgumentNullException>(
                () => new AStarShortestPathAlgorithm <int, Edge <int> >(null, null, null, null, null));
            // ReSharper restore AssignNullToNotNullAttribute
            // ReSharper restore ObjectCreationAsStatement
        }
        public void FacebookSeattleWordPuzzle()
        {
            /* A puzzle from Facebook Seattle opening party:
             * http://www.facebook.com/note.php?note_id=146727365346299
             * You are given a list of relationships between the letters in a single word, all of which are in the form:
             * "The first occurrence of A comes before N occurrences of B."
             * You can safely assume that you have all such relationships except for any in which N would be 0.
             * Determine the original word, then go to http://www.facebook.com/seattle/[insert-word-here] to find the second part of the puzzle.
             *
             * The first occurrence of 'e' comes before 1 occurrence of 's'.
             * The first occurrence of 'i' comes before 1 occurrence of 'n'.
             * The first occurrence of 'i' comes before 1 occurrence of 'i'.
             * The first occurrence of 'n' comes before 2 occurrences of 'e'.
             * The first occurrence of 'e' comes before 1 occurrence of 'e'.
             * The first occurrence of 'i' comes before 1 occurrence of 'v'.
             * The first occurrence of 'n' comes before 1 occurrence of 'i'.
             * The first occurrence of 'n' comes before 1 occurrence of 'v'.
             * The first occurrence of 'i' comes before 1 occurrence of 's'.
             * The first occurrence of 't' comes before 1 occurrence of 's'.
             * The first occurrence of 'v' comes before 1 occurrence of 's'.
             * The first occurrence of 'v' comes before 2 occurrences of 'e'.
             * The first occurrence of 't' comes before 2 occurrences of 'e'.
             * The first occurrence of 'i' comes before 2 occurrences of 'e'.
             * The first occurrence of 'v' comes before 1 occurrence of 't'.
             * The first occurrence of 'n' comes before 1 occurrence of 't'.
             * The first occurrence of 'v' comes before 1 occurrence of 'i'.
             * The first occurrence of 'i' comes before 1 occurrence of 't'.
             * The first occurrence of 'n' comes before 1 occurrence of 's'.
             */

            var graph = new AdjacencyGraph <Letter, Edge <Letter> >();

            // A more generalized algorithm would handle duplicate letters automatically.
            // This is the quick and dirty solution.
            var i1 = new Letter('i');
            var i2 = new Letter('i');
            var e1 = new Letter('e');
            var e2 = new Letter('e');

            var s = new Letter('s');
            var n = new Letter('n');
            var t = new Letter('t');
            var v = new Letter('v');

            graph.AddVertexRange(new List <Letter> {
                e1, e2, s, i1, i2, n, t, v
            });

            graph.AddEdge(new Edge <Letter>(e1, s));
            graph.AddEdge(new Edge <Letter>(i1, n));
            graph.AddEdge(new Edge <Letter>(i1, i2));
            graph.AddEdge(new Edge <Letter>(n, e1));
            graph.AddEdge(new Edge <Letter>(n, e2));
            graph.AddEdge(new Edge <Letter>(e1, e2));
            graph.AddEdge(new Edge <Letter>(i1, v));
            graph.AddEdge(new Edge <Letter>(n, e1));
            graph.AddEdge(new Edge <Letter>(n, v));
            graph.AddEdge(new Edge <Letter>(i1, s));
            graph.AddEdge(new Edge <Letter>(t, s));
            graph.AddEdge(new Edge <Letter>(v, s));
            graph.AddEdge(new Edge <Letter>(v, e1));
            graph.AddEdge(new Edge <Letter>(v, e2));
            graph.AddEdge(new Edge <Letter>(t, e1));
            graph.AddEdge(new Edge <Letter>(t, e2));
            graph.AddEdge(new Edge <Letter>(i1, e1));
            graph.AddEdge(new Edge <Letter>(i1, e2));
            graph.AddEdge(new Edge <Letter>(v, t));
            graph.AddEdge(new Edge <Letter>(n, t));
            graph.AddEdge(new Edge <Letter>(v, i2));
            graph.AddEdge(new Edge <Letter>(i1, t));
            graph.AddEdge(new Edge <Letter>(n, s));

            var sort = new TopologicalSortAlgorithm <Letter, Edge <Letter> >(graph);

            sort.Compute();

            var builder = new StringBuilder();

            foreach (Letter item in sort.SortedVertices)
            {
                builder.Append(item);
            }
            string word = builder.ToString();

            Assert.AreEqual("invitees", word);
        }
        public void TopologicalSort_DCT8()
        {
            AdjacencyGraph <string, Edge <string> > graph = TestGraphFactory.LoadGraph(GetGraphFilePath("DCT8.graphml"));

            RunTopologicalSortAndCheck(graph);
        }
Exemplo n.º 49
0
        public void Attach()
        {
            // DFS is used for tests but result may change if using another search algorithm
            // or another starting point
            {
                var recorder = new VertexPredecessorRecorderObserver <int, Edge <int> >();

                var graph = new AdjacencyGraph <int, Edge <int> >();

                var dfs = new DepthFirstSearchAlgorithm <int, Edge <int> >(graph);
                using (recorder.Attach(dfs))
                {
                    dfs.Compute();

                    CollectionAssert.IsEmpty(recorder.VerticesPredecessors);
                }
            }

            {
                var recorder = new VertexPredecessorRecorderObserver <int, Edge <int> >();

                var graph = new AdjacencyGraph <int, Edge <int> >();
                graph.AddVertexRange(new[] { 1, 2 });

                var dfs = new DepthFirstSearchAlgorithm <int, Edge <int> >(graph);
                using (recorder.Attach(dfs))
                {
                    dfs.Compute();

                    CollectionAssert.IsEmpty(recorder.VerticesPredecessors);
                }
            }

            {
                var recorder = new VertexPredecessorRecorderObserver <int, Edge <int> >();

                // Graph without cycle
                var edge12 = new Edge <int>(1, 2);
                var edge13 = new Edge <int>(1, 3);
                var edge14 = new Edge <int>(1, 4);
                var edge24 = new Edge <int>(2, 4);
                var edge31 = new Edge <int>(3, 1);
                var edge33 = new Edge <int>(3, 3);
                var edge34 = new Edge <int>(3, 4);
                var graph  = new AdjacencyGraph <int, Edge <int> >();
                graph.AddVerticesAndEdgeRange(new[]
                {
                    edge12, edge13, edge14, edge24, edge31, edge33, edge34
                });

                var dfs = new DepthFirstSearchAlgorithm <int, Edge <int> >(graph);
                using (recorder.Attach(dfs))
                {
                    dfs.Compute();

                    CollectionAssert.AreEqual(
                        new Dictionary <int, Edge <int> >
                    {
                        [2] = edge12,
                        [3] = edge13,
                        [4] = edge24
                    },
                        recorder.VerticesPredecessors);
                }
            }

            {
                var recorder = new VertexPredecessorRecorderObserver <int, Edge <int> >();

                // Graph with cycle
                var edge12 = new Edge <int>(1, 2);
                var edge13 = new Edge <int>(1, 3);
                var edge14 = new Edge <int>(1, 4);
                var edge24 = new Edge <int>(2, 4);
                var edge31 = new Edge <int>(3, 1);
                var edge33 = new Edge <int>(3, 3);
                var edge34 = new Edge <int>(3, 4);
                var edge41 = new Edge <int>(4, 1);
                var graph  = new AdjacencyGraph <int, Edge <int> >();
                graph.AddVerticesAndEdgeRange(new[]
                {
                    edge12, edge13, edge14, edge24, edge31, edge33, edge34, edge41
                });

                var dfs = new DepthFirstSearchAlgorithm <int, Edge <int> >(graph);
                using (recorder.Attach(dfs))
                {
                    dfs.Compute();

                    CollectionAssert.AreEqual(
                        new Dictionary <int, Edge <int> >
                    {
                        [2] = edge12,
                        [3] = edge13,
                        [4] = edge24
                    },
                        recorder.VerticesPredecessors);
                }
            }
        }
Exemplo n.º 50
0
 public void SortAll(AdjacencyGraph <string, Edge <string> > g)
 {
     this.Sort(g);
 }
Exemplo n.º 51
0
 public void AugmentAll(AdjacencyGraph <string, Edge <string> > g)
 {
     this.Augment(g);
 }
        public void IncrementalConnectedComponent()
        {
            var graph = new AdjacencyGraph <int, Edge <int> >();

            graph.AddVertexRange(new[] { 0, 1, 2, 3 });

            var algorithm = new IncrementalConnectedComponentsAlgorithm <int, Edge <int> >(graph);

            algorithm.Compute();

            Assert.AreEqual(4, algorithm.ComponentCount);
            Assert.AreEqual(4, algorithm.GetComponents().Key);
            CollectionAssert.AreEquivalent(
                new Dictionary <int, int>
            {
                [0] = 0,
                [1] = 1,
                [2] = 2,
                [3] = 3
            },
                algorithm.GetComponents().Value);

            graph.AddEdge(new Edge <int>(0, 1));
            Assert.AreEqual(3, algorithm.ComponentCount);
            Assert.AreEqual(3, algorithm.GetComponents().Key);
            CollectionAssert.AreEquivalent(
                new Dictionary <int, int>
            {
                [0] = 0,
                [1] = 0,
                [2] = 1,
                [3] = 2
            },
                algorithm.GetComponents().Value);

            graph.AddEdge(new Edge <int>(2, 3));
            Assert.AreEqual(2, algorithm.ComponentCount);
            Assert.AreEqual(2, algorithm.GetComponents().Key);
            CollectionAssert.AreEquivalent(
                new Dictionary <int, int>
            {
                [0] = 0,
                [1] = 0,
                [2] = 1,
                [3] = 1
            },
                algorithm.GetComponents().Value);

            graph.AddEdge(new Edge <int>(1, 3));
            Assert.AreEqual(1, algorithm.ComponentCount);
            Assert.AreEqual(1, algorithm.GetComponents().Key);
            CollectionAssert.AreEquivalent(
                new Dictionary <int, int>
            {
                [0] = 0,
                [1] = 0,
                [2] = 0,
                [3] = 0
            },
                algorithm.GetComponents().Value);

            graph.AddVerticesAndEdge(new Edge <int>(4, 5));
            Assert.AreEqual(2, algorithm.ComponentCount);
            Assert.AreEqual(2, algorithm.GetComponents().Key);
            CollectionAssert.AreEquivalent(
                new Dictionary <int, int>
            {
                [0] = 0,
                [1] = 0,
                [2] = 0,
                [3] = 0,
                [4] = 1,
                [5] = 1
            },
                algorithm.GetComponents().Value);

            graph.AddVertex(6);
            Assert.AreEqual(3, algorithm.ComponentCount);
            Assert.AreEqual(3, algorithm.GetComponents().Key);
            CollectionAssert.AreEquivalent(
                new Dictionary <int, int>
            {
                [0] = 0,
                [1] = 0,
                [2] = 0,
                [3] = 0,
                [4] = 1,
                [5] = 1,
                [6] = 2
            },
                algorithm.GetComponents().Value);
        }
        public void Scenario()
        {
            AdjacencyGraph <string, Edge <string> > graph = CreateGraph(out Dictionary <Edge <string>, double> edgeCosts);

            // Run Dijkstra on this graph
            var dijkstra = new DijkstraShortestPathAlgorithm <string, Edge <string> >(graph, e => edgeCosts[e]);

            // Attach a Vertex Predecessor Recorder Observer to give us the paths
            var predecessorObserver = new VertexPredecessorRecorderObserver <string, Edge <string> >();

            using (predecessorObserver.Attach(dijkstra))
            {
                // Run the algorithm with A as source
                dijkstra.Compute("A");
            }

            foreach (KeyValuePair <string, Edge <string> > pair in predecessorObserver.VerticesPredecessors)
            {
                Console.WriteLine($"If you want to get to {pair.Key} you have to enter through the in edge {pair.Value}.");
            }

            foreach (string vertex in graph.Vertices)
            {
                double distance = AlgorithmExtensions.ComputePredecessorCost(
                    predecessorObserver.VerticesPredecessors,
                    edgeCosts,
                    vertex);
                Console.WriteLine($"A -> {vertex}: {distance}");
            }

            #region Local function

            AdjacencyGraph <string, Edge <string> > CreateGraph(out Dictionary <Edge <string>, double> costs)
            {
                var g = new AdjacencyGraph <string, Edge <string> >(true);

                // Add some vertices to the graph
                g.AddVertex("A");
                g.AddVertex("B");
                g.AddVertex("C");
                g.AddVertex("D");
                g.AddVertex("E");
                g.AddVertex("F");
                g.AddVertex("G");
                g.AddVertex("H");
                g.AddVertex("I");
                g.AddVertex("J");

                // Create the edges
                // ReSharper disable InconsistentNaming
                var a_b = new Edge <string>("A", "B");
                var a_d = new Edge <string>("A", "D");
                var b_a = new Edge <string>("B", "A");
                var b_c = new Edge <string>("B", "C");
                var b_e = new Edge <string>("B", "E");
                var c_b = new Edge <string>("C", "B");
                var c_f = new Edge <string>("C", "F");
                var c_j = new Edge <string>("C", "J");
                var d_e = new Edge <string>("D", "E");
                var d_g = new Edge <string>("D", "G");
                var e_d = new Edge <string>("E", "D");
                var e_f = new Edge <string>("E", "F");
                var e_h = new Edge <string>("E", "H");
                var f_i = new Edge <string>("F", "I");
                var f_j = new Edge <string>("F", "J");
                var g_d = new Edge <string>("G", "D");
                var g_h = new Edge <string>("G", "H");
                var h_g = new Edge <string>("H", "G");
                var h_i = new Edge <string>("H", "I");
                var i_f = new Edge <string>("I", "F");
                var i_j = new Edge <string>("I", "J");
                var i_h = new Edge <string>("I", "H");
                var j_f = new Edge <string>("J", "F");

                // ReSharper restore InconsistentNaming

                // Add the edges
                g.AddEdge(a_b);
                g.AddEdge(a_d);
                g.AddEdge(b_a);
                g.AddEdge(b_c);
                g.AddEdge(b_e);
                g.AddEdge(c_b);
                g.AddEdge(c_f);
                g.AddEdge(c_j);
                g.AddEdge(d_e);
                g.AddEdge(d_g);
                g.AddEdge(e_d);
                g.AddEdge(e_f);
                g.AddEdge(e_h);
                g.AddEdge(f_i);
                g.AddEdge(f_j);
                g.AddEdge(g_d);
                g.AddEdge(g_h);
                g.AddEdge(h_g);
                g.AddEdge(h_i);
                g.AddEdge(i_f);
                g.AddEdge(i_h);
                g.AddEdge(i_j);
                g.AddEdge(j_f);

                // Define some weights to the edges
                costs = new Dictionary <Edge <string>, double>(g.EdgeCount)
                {
                    [a_b] = 4,
                    [a_d] = 1,
                    [b_a] = 74,
                    [b_c] = 2,
                    [b_e] = 12,
                    [c_b] = 12,
                    [c_f] = 74,
                    [c_j] = 12,
                    [d_e] = 32,
                    [d_g] = 22,
                    [e_d] = 66,
                    [e_f] = 76,
                    [e_h] = 33,
                    [f_i] = 11,
                    [f_j] = 21,
                    [g_d] = 12,
                    [g_h] = 10,
                    [h_g] = 2,
                    [h_i] = 72,
                    [i_f] = 31,
                    [i_h] = 18,
                    [i_j] = 7,
                    [j_f] = 8
                };

                return(g);
            }

            #endregion
        }
Exemplo n.º 54
0
        public void Scenario()
        {
            AdjacencyGraph <string, Edge <string> > graph = new AdjacencyGraph <string, Edge <string> >(true);

            // Add some vertices to the graph
            graph.AddVertex("A");
            graph.AddVertex("B");
            graph.AddVertex("C");
            graph.AddVertex("D");
            graph.AddVertex("E");
            graph.AddVertex("F");
            graph.AddVertex("G");
            graph.AddVertex("H");
            graph.AddVertex("I");
            graph.AddVertex("J");

            // Create the edges
            Edge <string> a_b = new Edge <string>("A", "B");
            Edge <string> a_d = new Edge <string>("A", "D");
            Edge <string> b_a = new Edge <string>("B", "A");
            Edge <string> b_c = new Edge <string>("B", "C");
            Edge <string> b_e = new Edge <string>("B", "E");
            Edge <string> c_b = new Edge <string>("C", "B");
            Edge <string> c_f = new Edge <string>("C", "F");
            Edge <string> c_j = new Edge <string>("C", "J");
            Edge <string> d_e = new Edge <string>("D", "E");
            Edge <string> d_g = new Edge <string>("D", "G");
            Edge <string> e_d = new Edge <string>("E", "D");
            Edge <string> e_f = new Edge <string>("E", "F");
            Edge <string> e_h = new Edge <string>("E", "H");
            Edge <string> f_i = new Edge <string>("F", "I");
            Edge <string> f_j = new Edge <string>("F", "J");
            Edge <string> g_d = new Edge <string>("G", "D");
            Edge <string> g_h = new Edge <string>("G", "H");
            Edge <string> h_g = new Edge <string>("H", "G");
            Edge <string> h_i = new Edge <string>("H", "I");
            Edge <string> i_f = new Edge <string>("I", "F");
            Edge <string> i_j = new Edge <string>("I", "J");
            Edge <string> i_h = new Edge <string>("I", "H");
            Edge <string> j_f = new Edge <string>("J", "F");

            // Add the edges
            graph.AddEdge(a_b);
            graph.AddEdge(a_d);
            graph.AddEdge(b_a);
            graph.AddEdge(b_c);
            graph.AddEdge(b_e);
            graph.AddEdge(c_b);
            graph.AddEdge(c_f);
            graph.AddEdge(c_j);
            graph.AddEdge(d_e);
            graph.AddEdge(d_g);
            graph.AddEdge(e_d);
            graph.AddEdge(e_f);
            graph.AddEdge(e_h);
            graph.AddEdge(f_i);
            graph.AddEdge(f_j);
            graph.AddEdge(g_d);
            graph.AddEdge(g_h);
            graph.AddEdge(h_g);
            graph.AddEdge(h_i);
            graph.AddEdge(i_f);
            graph.AddEdge(i_h);
            graph.AddEdge(i_j);
            graph.AddEdge(j_f);

            // Define some weights to the edges
            Dictionary <Edge <string>, double> edgeCost = new Dictionary <Edge <string>, double>(graph.EdgeCount);

            edgeCost.Add(a_b, 4);
            edgeCost.Add(a_d, 1);
            edgeCost.Add(b_a, 74);
            edgeCost.Add(b_c, 2);
            edgeCost.Add(b_e, 12);
            edgeCost.Add(c_b, 12);
            edgeCost.Add(c_f, 74);
            edgeCost.Add(c_j, 12);
            edgeCost.Add(d_e, 32);
            edgeCost.Add(d_g, 22);
            edgeCost.Add(e_d, 66);
            edgeCost.Add(e_f, 76);
            edgeCost.Add(e_h, 33);
            edgeCost.Add(f_i, 11);
            edgeCost.Add(f_j, 21);
            edgeCost.Add(g_d, 12);
            edgeCost.Add(g_h, 10);
            edgeCost.Add(h_g, 2);
            edgeCost.Add(h_i, 72);
            edgeCost.Add(i_f, 31);
            edgeCost.Add(i_h, 18);
            edgeCost.Add(i_j, 7);
            edgeCost.Add(j_f, 8);

            // We want to use Dijkstra on this graph
            var dijkstra = new DijkstraShortestPathAlgorithm <string, Edge <string> >(graph, e => edgeCost[e]);

            // Attach a Vertex Predecessor Recorder Observer to give us the paths
            var predecessorObserver = new VertexPredecessorRecorderObserver <string, Edge <string> >();

            using (predecessorObserver.Attach(dijkstra)) {
                // Run the algorithm with A set to be the source
                dijkstra.Compute("A");
            }

            foreach (KeyValuePair <string, Edge <string> > kvp in predecessorObserver.VertexPredecessors)
            {
                TestConsole.WriteLine("If you want to get to {0} you have to enter through the in edge {1}", kvp.Key, kvp.Value);
            }

            foreach (string v in graph.Vertices)
            {
                double distance =
                    AlgorithmExtensions.ComputePredecessorCost(
                        predecessorObserver.VertexPredecessors,
                        edgeCost, v);
                TestConsole.WriteLine("A -> {0}: {1}", v, distance);
            }
        }
Exemplo n.º 55
0
        public void BuildGraphFromMinimalGraphShapefile()
        {
            string path  = "minimalgraph.shp";
            int    count = 15;

            Assert.IsTrue(File.Exists(path));
            ShapefileReader     reader = new ShapefileReader(path);
            IGeometryCollection edges  = reader.ReadAll();

            Assert.IsNotNull(edges);
            Assert.IsInstanceOfType(typeof(GeometryCollection), edges);
            Assert.AreEqual(count, edges.NumGeometries);

            ILineString startls = null;
            // Build graph
            Dictionary <IEdge <IGeometry>, double>         consts = new Dictionary <IEdge <IGeometry>, double>(edges.NumGeometries);
            AdjacencyGraph <IGeometry, IEdge <IGeometry> > graph  = new AdjacencyGraph <IGeometry, IEdge <IGeometry> >(true);

            foreach (IMultiLineString mlstr in edges.Geometries)
            {
                Assert.AreEqual(1, mlstr.NumGeometries);
                ILineString str = (ILineString)mlstr.GetGeometryN(0);
                if (startls == null)
                {
                    startls = str;
                }

                // Add vertex 1
                IGeometry vertex1 = str.StartPoint;
                Assert.IsNotNull(vertex1);
                if (!graph.ContainsVertex(vertex1))
                {
                    Debug.WriteLine(String.Format("Adding vertex {0} to the list", vertex1));
                    graph.AddVertex(vertex1);
                }
                else
                {
                    Debug.WriteLine(String.Format("Vertex {0} already present", vertex1));
                }

                // Add vertex 2
                IGeometry vertex2 = str.EndPoint;
                Assert.IsNotNull(vertex2);
                if (!graph.ContainsVertex(vertex2))
                {
                    Debug.WriteLine(String.Format("Adding vertex {0} to the list", vertex2));
                    graph.AddVertex(vertex2);
                }
                else
                {
                    Debug.WriteLine(String.Format("Vertex {0} already present", vertex2));
                }

                // Compute weight
                double weight = weightComputer(str);
                Assert.Greater(weight, 0.0);

                // Add edge 1 => 2
                IEdge <IGeometry> edge1 = new Edge <IGeometry>(vertex1, vertex2);
                Assert.IsNotNull(edge1);
                graph.AddEdge(edge1);
                consts.Add(edge1, weight);

                // Add edge 2 => 1
                IEdge <IGeometry> edge2 = new Edge <IGeometry>(vertex2, vertex1);
                Assert.IsNotNull(edge2);
                graph.AddEdge(edge2);
                consts.Add(edge2, weight);
            }

            // Perform DijkstraShortestPathAlgorithm
            DijkstraShortestPathAlgorithm <IGeometry, IEdge <IGeometry> > dijkstra =
                new DijkstraShortestPathAlgorithm <IGeometry, IEdge <IGeometry> >(graph, consts);

            // attach a distance observer to give us the shortest path distances
            VertexDistanceRecorderObserver <IGeometry, IEdge <IGeometry> > distObserver =
                new VertexDistanceRecorderObserver <IGeometry, IEdge <IGeometry> >();

            distObserver.Attach(dijkstra);

            // Attach a Vertex Predecessor Recorder Observer to give us the paths
            VertexPredecessorRecorderObserver <IGeometry, IEdge <IGeometry> > predecessorObserver =
                new VertexPredecessorRecorderObserver <IGeometry, IEdge <IGeometry> >();

            predecessorObserver.Attach(dijkstra);

            // Run the algorithm
            Assert.IsNotNull(startls);
            IGeometry startPoint = startls.StartPoint;

            Debug.WriteLine(String.Format("Starting algorithm from root vertex {0}", startPoint));
            dijkstra.Compute(startPoint);

            foreach (KeyValuePair <IGeometry, int> kvp in distObserver.Distances)
            {
                Debug.WriteLine(String.Format("Distance from root to node {0} is {1}",
                                              kvp.Key, kvp.Value));
            }
            foreach (KeyValuePair <IGeometry, IEdge <IGeometry> > kvp in predecessorObserver.VertexPredecessors)
            {
                Debug.WriteLine(String.Format(
                                    "If you want to get to {0} you have to enter through the IN edge {1}", kvp.Key, kvp.Value));
            }
            Check(graph, consts, predecessorObserver);

            // Detach the observers
            distObserver.Detach(dijkstra);
            predecessorObserver.Detach(dijkstra);
        }
Exemplo n.º 56
0
        public void ToGraphvizWithInit()
        {
            var wrappedGraph = new AdjacencyGraph <int, Edge <int> >();

            wrappedGraph.AddVerticesAndEdgeRange(new[]
            {
                new Edge <int>(1, 2),
                new Edge <int>(1, 3),
                new Edge <int>(2, 4)
            });
            wrappedGraph.AddVertex(5);
            var clusteredGraph = new ClusteredAdjacencyGraph <int, Edge <int> >(wrappedGraph);
            ClusteredAdjacencyGraph <int, Edge <int> > subGraph1 = clusteredGraph.AddCluster();

            subGraph1.AddVerticesAndEdgeRange(new[]
            {
                new Edge <int>(6, 7),
                new Edge <int>(7, 8)
            });
            ClusteredAdjacencyGraph <int, Edge <int> > subGraph2 = clusteredGraph.AddCluster();

            subGraph2.AddVerticesAndEdge(new Edge <int>(9, 10));
            subGraph2.AddVertex(11);

            string expectedDot =
                "digraph G {" + Environment.NewLine
                + "node [shape=diamond];" + Environment.NewLine
                + "edge [tooltip=\"Test Edge\"];" + Environment.NewLine
                + "subgraph cluster1 {" + Environment.NewLine
                + "5 [label=\"Test Vertex 6\"];" + Environment.NewLine
                + "6 [label=\"Test Vertex 7\"];" + Environment.NewLine
                + "7 [label=\"Test Vertex 8\"];" + Environment.NewLine
                + "5 -> 6;" + Environment.NewLine
                + "6 -> 7;" + Environment.NewLine
                + "}" + Environment.NewLine
                + "subgraph cluster2 {" + Environment.NewLine
                + "8 [label=\"Test Vertex 9\"];" + Environment.NewLine
                + "9 [label=\"Test Vertex 10\"];" + Environment.NewLine
                + "10 [label=\"Test Vertex 11\"];" + Environment.NewLine
                + "8 -> 9;" + Environment.NewLine
                + "}" + Environment.NewLine
                + "0 [label=\"Test Vertex 1\"];" + Environment.NewLine
                + "1 [label=\"Test Vertex 2\"];" + Environment.NewLine
                + "2 [label=\"Test Vertex 3\"];" + Environment.NewLine
                + "3 [label=\"Test Vertex 4\"];" + Environment.NewLine
                + "4 [label=\"Test Vertex 5\"];" + Environment.NewLine
                + "0 -> 1;" + Environment.NewLine
                + "0 -> 2;" + Environment.NewLine
                + "1 -> 3;" + Environment.NewLine
                + "}";
            string dotGraph = clusteredGraph.ToGraphviz(algorithm =>
            {
                algorithm.CommonVertexFormat.Shape = GraphvizVertexShape.Diamond;
                algorithm.CommonEdgeFormat.ToolTip = "Test Edge";
                algorithm.FormatVertex            += (sender, args) =>
                {
                    args.VertexFormat.Label = $"Test Vertex {args.Vertex}";
                };
            });

            Assert.AreEqual(expectedDot, dotGraph);
        }
Exemplo n.º 57
0
 public void AnalyzeDependencies(AdjacencyGraph<string, IEdge<string>> graph)
 {
     graph.AddVertex(RefId);
     P.AnalyzeDependencies(graph, RefId, Info.DataType);
 }
Exemplo n.º 58
0
        public void BellmanFord_NegativeCycle()
        {
            // Without negative cycle
            var edge12 = new Edge <int>(1, 2);
            var edge23 = new Edge <int>(2, 3);
            var edge34 = new Edge <int>(3, 4);

            var negativeWeightGraph = new AdjacencyGraph <int, Edge <int> >();

            negativeWeightGraph.AddVerticesAndEdgeRange(new[]
            {
                edge12, edge23, edge34
            });

            var algorithm = new BellmanFordShortestPathAlgorithm <int, Edge <int> >(
                negativeWeightGraph,
                e =>
            {
                if (e == edge12)
                {
                    return(12.0);
                }
                if (e == edge23)
                {
                    return(-23.0);
                }
                if (e == edge34)
                {
                    return(-34.0);
                }
                return(1.0);
            });

            Assert.DoesNotThrow(() => algorithm.Compute(1));
            Assert.IsFalse(algorithm.FoundNegativeCycle);

            // With negative cycle
            var edge41 = new Edge <int>(4, 1);

            var negativeCycleGraph = new AdjacencyGraph <int, Edge <int> >();

            negativeCycleGraph.AddVerticesAndEdgeRange(new[]
            {
                edge12, edge23, edge34, edge41
            });

            algorithm = new BellmanFordShortestPathAlgorithm <int, Edge <int> >(
                negativeCycleGraph,
                e =>
            {
                if (e == edge12)
                {
                    return(12.0);
                }
                if (e == edge23)
                {
                    return(-23.0);
                }
                if (e == edge34)
                {
                    return(-34.0);
                }
                if (e == edge41)
                {
                    return(41.0);
                }
                return(1.0);
            });
            Assert.DoesNotThrow(() => algorithm.Compute(1));
            Assert.IsTrue(algorithm.FoundNegativeCycle);
        }
Exemplo n.º 59
0
 public void AnalyzeDependencies(AdjacencyGraph <string, IEdge <string> > graph)
 {
     P.AnalyzeDependencies(graph, Info);
 }
Exemplo n.º 60
0
        public void SerializeToGraphML_Throws()
        {
            // ReSharper disable AssignNullToNotNullAttribute
            // Filepath
            Assert.Throws <ArgumentNullException>(
                () => ((AdjacencyGraph <TestVertex, TestEdge>)null).SerializeToGraphML <TestVertex, TestEdge, AdjacencyGraph <TestVertex, TestEdge> >(WriteThrowsTestFilePath));

            var graph = new AdjacencyGraph <TestVertex, TestEdge>();

            Assert.Throws <ArgumentException>(
                () => graph.SerializeToGraphML <TestVertex, TestEdge, AdjacencyGraph <TestVertex, TestEdge> >((string)null));
            Assert.Throws <ArgumentException>(
                () => graph.SerializeToGraphML <TestVertex, TestEdge, AdjacencyGraph <TestVertex, TestEdge> >(""));

            Assert.Throws <ArgumentNullException>(
                () => ((AdjacencyGraph <TestVertex, TestEdge>)null).SerializeToGraphML <TestVertex, TestEdge, AdjacencyGraph <TestVertex, TestEdge> >(
                    WriteThrowsTestFilePath,
                    vertex => vertex.ID,
                    edge => edge.ID));

            Assert.Throws <ArgumentException>(
                () => graph.SerializeToGraphML <TestVertex, TestEdge, AdjacencyGraph <TestVertex, TestEdge> >(
                    (string)null,
                    vertex => vertex.ID,
                    edge => edge.ID));
            Assert.Throws <ArgumentException>(
                () => graph.SerializeToGraphML <TestVertex, TestEdge, AdjacencyGraph <TestVertex, TestEdge> >(
                    "",
                    vertex => vertex.ID,
                    edge => edge.ID));

            Assert.Throws <ArgumentNullException>(
                () => graph.SerializeToGraphML <TestVertex, TestEdge, AdjacencyGraph <TestVertex, TestEdge> >(
                    WriteThrowsTestFilePath,
                    null,
                    edge => edge.ID));

            Assert.Throws <ArgumentNullException>(
                () => ((AdjacencyGraph <TestVertex, TestEdge>)null).SerializeToGraphML <TestVertex, TestEdge, AdjacencyGraph <TestVertex, TestEdge> >(
                    WriteThrowsTestFilePath,
                    vertex => vertex.ID,
                    null));

            // XML writer
            Assert.Throws <ArgumentNullException>(
                () => graph.SerializeToGraphML <TestVertex, TestEdge, AdjacencyGraph <TestVertex, TestEdge> >((XmlWriter)null));
            Assert.Throws <ArgumentNullException>(
                () => graph.SerializeToGraphML <TestVertex, TestEdge, AdjacencyGraph <TestVertex, TestEdge> >(
                    (XmlWriter)null,
                    vertex => vertex.ID,
                    edge => edge.ID));

            using (XmlWriter writer = XmlWriter.Create(WriteThrowsTestFilePath))
            {
                Assert.Throws <ArgumentNullException>(
                    () => ((AdjacencyGraph <TestVertex, TestEdge>)null).SerializeToGraphML <TestVertex, TestEdge, AdjacencyGraph <TestVertex, TestEdge> >(writer));

                Assert.Throws <ArgumentNullException>(
                    () => ((AdjacencyGraph <TestVertex, TestEdge>)null).SerializeToGraphML <TestVertex, TestEdge, AdjacencyGraph <TestVertex, TestEdge> >(
                        writer,
                        vertex => vertex.ID,
                        edge => edge.ID));

                Assert.Throws <ArgumentNullException>(
                    () => graph.SerializeToGraphML <TestVertex, TestEdge, AdjacencyGraph <TestVertex, TestEdge> >(
                        writer,
                        null,
                        edge => edge.ID));

                Assert.Throws <ArgumentNullException>(
                    () => graph.SerializeToGraphML <TestVertex, TestEdge, AdjacencyGraph <TestVertex, TestEdge> >(
                        writer,
                        vertex => vertex.ID,
                        null));
            }
            // ReSharper restore AssignNullToNotNullAttribute
        }