Ejemplo n.º 1
0
 public void TestDirectedGraphEmptyHasEdgeTrue()
 {
     var vertices = 1.Upto(3).ToSet();
     var edges = new Set<IDirectedEdge<int>> { new DirectedEdge<int>(1, 2) };
     var graph = new DirectedGraph<int>(vertices, edges);
     graph.HasEdge(1, 2).ShouldBeTrue();
 }
        public void Run()
        {
            using (var reader = new StreamReader("SCC.txt"))
            using (var writer = new StreamWriter("output.txt"))
            {
                var graph = new DirectedGraph<int>();

                while (true)
                {
                    string row = reader.ReadLine();
                    if (row == null)
                    {
                        break;
                    }

                    var parts = row.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    var numbers = parts.Select(x => int.Parse(x, CultureInfo.InvariantCulture) - 1).ToArray();
                    var from = numbers[0];
                    var to = numbers[1];
                    if (from != to)
                    {
                        graph.AddEdge(from, to);
                    }
                }

                var calculator = new StronglyConnectedComponentsCalculator<int>(graph);

                var components = calculator.GetStronglyConnectedComponents().ToArray();
                var top5Components = components.OrderByDescending(x => x.Length).Take(5).ToArray();
                var result = string.Join(",", top5Components.Select(x => x.Length));
                writer.WriteLine(result);
            }
        }
Ejemplo n.º 3
0
        public void Run()
        {
            using (var reader = new StreamReader("kargerMinCut.txt"))
            using (var writer = new StreamWriter("output.txt"))
            {
                var graph = new DirectedGraph<int>();
                while (true)
                {
                    string row = reader.ReadLine();
                    if (row == null)
                    {
                        break;
                    }

                    var parts = row.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    var numbers = parts.Select(x => int.Parse(x, CultureInfo.InvariantCulture) - 1).ToArray();
                    foreach (var number in numbers.Skip(1))
                    {
                        graph.AddEdge(numbers[0], number);
                    }
                }

                int result = Enumerable.Repeat(0, 250).Select(_ => MinCut.GetMinCut(graph)).Min();

                writer.WriteLine(result);
            }
        }
        public void TestPriorityCalculation1NoWitnesses()
        {
            var graph = new DirectedGraph<CHEdgeData>();
            var vertex1 = graph.AddVertex(1, 0);
            var vertex2 = graph.AddVertex(2, 0);
            var vertex3 = graph.AddVertex(3, 0);

            graph.AddEdge(vertex1, vertex3, new CHEdgeData(1, true, true, true, 10));
            graph.AddEdge(vertex3, vertex1, new CHEdgeData(1, false, true, true, 10));
            graph.AddEdge(vertex2, vertex3, new CHEdgeData(1, true, true, true, 10));
            graph.AddEdge(vertex3, vertex2, new CHEdgeData(1, false, true, true, 10));

            var witnessCalculator = new DykstraWitnessCalculator(int.MaxValue);
            var priorityCalculator = new EdgeDifferenceContractedSearchSpace(graph, witnessCalculator);

            int newEdges, removedEdges, contracted, depth;
            priorityCalculator.Calculate(vertex1, out newEdges, out removedEdges, out depth, out contracted);
            Assert.AreEqual(0, newEdges);
            Assert.AreEqual(1, removedEdges);
            Assert.AreEqual(0, depth);
            Assert.AreEqual(0, contracted);
            priorityCalculator.Calculate(vertex2, out newEdges, out removedEdges, out depth, out contracted);
            Assert.AreEqual(0, newEdges);
            Assert.AreEqual(1, removedEdges);
            Assert.AreEqual(0, depth);
            Assert.AreEqual(0, contracted);
            priorityCalculator.Calculate(vertex3, out newEdges, out removedEdges, out depth, out contracted);
            Assert.AreEqual(2, newEdges);
            Assert.AreEqual(2, removedEdges);
            Assert.AreEqual(0, depth);
            Assert.AreEqual(0, contracted);
        }
Ejemplo n.º 5
0
 public void Graph_with_one_vertex_has_order_1()
 {
     var vertices = 1.WrapInList().ToSet();
     var edges = new Set<IDirectedEdge<int>>();
     var graph = new DirectedGraph<int>(vertices, edges);
     graph.Order().ShouldEqual(1);
 }
Ejemplo n.º 6
0
 public void OnDependencyWalkStart(long walkIndex, string sourceProperty, string nodeId)
 {
     graphSnapshot = dependencyEngine.GetGraphSnapshot();
     nodesInPath.Clear();
     nodesInPath[nodeId] = new NodeDetails(ReevaluationResult.Changed, 1);
     nodeIndex = 2;
 }
Ejemplo n.º 7
0
        public static bool IsSatisfiable(IReadOnlyCollection<Clause> clauses)
        {
            var graph = new DirectedGraph<int>();

            foreach (var clause in clauses)
            {
                var literal1 = clause.Literal1;
                var literal2 = clause.Literal2;
                var from1 = GetNodeIndex(literal1.Negate());
                var to1 = GetNodeIndex(literal2);

                graph.AddEdge(from1, to1);

                var from2 = GetNodeIndex(literal2.Negate());
                var to2 = GetNodeIndex(literal1);

                graph.AddEdge(from2, to2);
            }

            var calculator = new StronglyConnectedComponentsCalculator<int>(graph);
            var components = calculator.GetStronglyConnectedComponents().ToArray();
            foreach (var component in components)
            {
                var positiveLiteralNodes = component.Where(node => node >= 0).ToArray();
                var negativeLiteralNodes = new HashSet<int>(component.Where(node => node < 0));
                if (positiveLiteralNodes.Any(node => negativeLiteralNodes.Contains(GetNegativeLiteralNodeIndex(node))))
                {
                    return false;
                }
            }

            return true;
        }
Ejemplo n.º 8
0
 protected void AssertBlocks(string sExpected, DirectedGraph<HeuristicBlock> cfg)
 {
     var sb = new StringBuilder();
     foreach (var hblock in cfg.Nodes.OrderBy(hb => hb.Address))
     {
         sb.AppendFormat("{0}:  // pred:", hblock.Name);
         foreach (var pred in cfg.Predecessors(hblock).OrderBy(hb => hb.Address))
         {
             sb.AppendFormat(" {0}", pred.Name);
         }
         sb.AppendLine();
         var lastAddr = hblock.GetEndAddress();
         var dasm = prog.Architecture.CreateDisassembler(
             prog.Architecture.CreateImageReader(prog.Image, hblock.Address));
         foreach (var instr in dasm.TakeWhile(i => i.Address < lastAddr))
         {
             sb.AppendFormat("    {0}", instr);
             sb.AppendLine();
         }
     }
     var sActual = sb.Replace('\t', ' ').ToString();
     if (sActual != sExpected)
     {
         Debug.Print(sActual);
         Assert.AreEqual(sExpected, sActual);
     }
 }
Ejemplo n.º 9
0
        public static int GetMinCut(DirectedGraph<int> graph)
        {
            var nodes = new List<MergedNode>();
            var edges = new List<Edge>();
            foreach (var node in graph.Keys)
            {
                nodes.Add(new MergedNode(node));
                edges.AddRange(graph.GetOutNodes(node).Select(x => new Edge(node, x)));
            }

            var random = new Random();

            while (nodes.Count > 2)
            {
                var edgeIndex = random.Next(edges.Count);
                var edge = edges[edgeIndex];
                var node1 = nodes.First(node => node.Nodes.Contains(edge.From));
                var node2 = nodes.First(node => node.Nodes.Contains(edge.To));
                edges.RemoveAt(edgeIndex);
                if (node1 == node2)
                {
                    continue;
                }

                nodes.Remove(node1);
                nodes.Remove(node2);
                nodes.Add(node1.Merge(node2));
            }

            return GetCrossingEdgesCount(nodes[0], nodes[1], graph);
        }
Ejemplo n.º 10
0
 public void Graph_with_one_edge_has_size_1()
 {
     var vertices = 1.Upto(2).ToSet();
     var edges = new Set<IDirectedEdge<int>> { new DirectedEdge<int>(1, 2) };
     var graph = new DirectedGraph<int>(vertices, edges);
     graph.Size().ShouldEqual(1);
 }
Ejemplo n.º 11
0
        public void DirectedGraphAllowsDuplicateEdgesTest()
        {
            var graph = new DirectedGraph<int>(new[] { 1, 2 });

            graph.AddEdge(1, 2);
            graph.AddEdge(1, 2);

            graph.FindCycle().Should().BeEmpty("Expected no cycle vertices to be found");
        }
 /// <summary>
 /// Creates a <see cref="DirectedGraph"/> with the specified parameters.
 /// </summary>
 /// <param name="layout">The layout of the directed graph.</param>
 /// <param name="graphDirection">The direction of the graph.</param>
 /// <returns>The directed graph configured with the specified parameters.</returns>
 public DirectedGraph Create(LayoutEnum layout, GraphDirectionEnum graphDirection)
 {
     var graph = new DirectedGraph();
     graph.Layout = layout;
     graph.LayoutSpecified = true;
     graph.GraphDirection = graphDirection;
     graph.GraphDirectionSpecified = true;
     return graph;
 }
Ejemplo n.º 13
0
        public void TestVerifiedContraction1NoWitnesses()
        {
            var graph = new DirectedGraph<CHEdgeData>();
            var vertex1 = graph.AddVertex(1, 0);
            var vertex2 = graph.AddVertex(2, 0);
            var vertex3 = graph.AddVertex(3, 0);

            graph.AddEdge(vertex1, vertex3, new CHEdgeData(1, true, true, true, 10));
            graph.AddEdge(vertex3, vertex1, new CHEdgeData(1, false, true, true, 10));
            graph.AddEdge(vertex2, vertex3, new CHEdgeData(1, true, true, true, 10));
            graph.AddEdge(vertex3, vertex2, new CHEdgeData(1, false, true, true, 10));

            var witnessCalculator = new DykstraWitnessCalculator();
            var preProcessor = new CHPreprocessor(graph,
                new EdgeDifferenceContractedSearchSpace(graph, witnessCalculator), witnessCalculator);
            preProcessor.Contract(3);

            // there should be no edge from 1->3 and from 2->3.
            Assert.IsFalse(graph.ContainsEdges(1, 3));
            Assert.IsFalse(graph.ContainsEdges(2, 3));

            var router = new CHRouter();
            // expected: (1)-10s-(3)-10s-(2) (20s in total).
            var path = router.Calculate(graph, 1, 2);
            Assert.IsNotNull(path);
            Assert.AreEqual(20, path.Weight);
            var pathArray = path.ToArrayWithWeight();
            Assert.AreEqual(3, pathArray.Length);
            float latitude, longitude;
            Assert.AreEqual(0, pathArray[0].Item2);
            Assert.IsTrue(graph.GetVertex((uint)pathArray[0].Item1, out latitude, out longitude));
            Assert.AreEqual(1, latitude);
            Assert.AreEqual(10, pathArray[1].Item2);
            Assert.IsTrue(graph.GetVertex((uint)pathArray[1].Item1, out latitude, out longitude));
            Assert.AreEqual(3, latitude);
            Assert.AreEqual(20, pathArray[2].Item2);
            Assert.IsTrue(graph.GetVertex((uint)pathArray[2].Item1, out latitude, out longitude));
            Assert.AreEqual(2, latitude);

            // expected: (2)-10s-(3)-10s-(1) (20s in total).
            path = router.Calculate(graph, 2, 1);
            Assert.IsNotNull(path);
            Assert.AreEqual(20, path.Weight);
            pathArray = path.ToArrayWithWeight();
            Assert.AreEqual(3, pathArray.Length);
            Assert.AreEqual(0, pathArray[0].Item2);
            Assert.IsTrue(graph.GetVertex((uint)pathArray[0].Item1, out latitude, out longitude));
            Assert.AreEqual(2, latitude);
            Assert.AreEqual(10, pathArray[1].Item2);
            Assert.IsTrue(graph.GetVertex((uint)pathArray[1].Item1, out latitude, out longitude));
            Assert.AreEqual(3, latitude);
            Assert.AreEqual(20, pathArray[2].Item2);
            Assert.IsTrue(graph.GetVertex((uint)pathArray[2].Item1, out latitude, out longitude));
            Assert.AreEqual(1, latitude);
        }
 public void SetUp()
 {
     _graph = new DirectedGraph<char>
     {
         { 'u', new char[] { 'v', 'x' } },
         { 'v', new char[] { 'y' } },
         { 'y', new char[] { 'x' } },
         { 'x', new char[] { 'v' } },
         { 'w', new char[] { 'y', 'z' } },
         { 'z', new char[] { 'z' } }
     };
 }
Ejemplo n.º 15
0
 public DirectedGraph<Type> GetDependencyGraph()
 {
     DirectedGraph<Type> graph = new DirectedGraph<Type>();
     foreach (Type x in assembly.GetTypes())
     {
         foreach (Type y in GetDependentClasses(x))
         {
             graph.AddEdge(y, x);
         }
     }
     return graph;
 }
Ejemplo n.º 16
0
 public void InitGraph()
 {
     _graph = new DirectedGraph<char>();
     _graph.AddVertex('A');
     _graph.AddVertex('B');
     _graph.AddVertex('D');
     _graph.AddVertex('E');
     _graph.AddEdge('A', 'B');
     _graph.AddEdge('A', 'D');
     _graph.AddEdge('D', 'B');
     _graph.AddEdge('D', 'E');
     _graph.AddEdge('E', 'B');
 }
Ejemplo n.º 17
0
 public void Initialize()
 {
     // add several nodes
     graph = new DirectedGraph<string, int>();
     graph.AddEdge("A", "B", 5);
     graph.AddEdge("B", "C", 4);
     graph.AddEdge("C", "D", 8);
     graph.AddEdge("D", "C", 8);
     graph.AddEdge("D", "E", 6);
     graph.AddEdge("A", "D", 5);
     graph.AddEdge("C", "E", 2);
     graph.AddEdge("E", "B", 3);
     graph.AddEdge("A", "E", 7);
 }
Ejemplo n.º 18
0
        public Region Execute(Procedure proc)
        {
#if NILZ
        We focus on the novel aspects of our algorithm in this
paper and refer readers interested in any structural analysis
details elided to standard sources 
         
Like vanilla structural analysis, our algorithm visits
nodes in post-order in each iteration.   Intuitively,  this
means that all descendants of a node will be visited (and
hence had the chance to be reduced) before the node itself.
The algorithm’s behavior when visiting node _n_
depends on hether the region at _n_
is acyclic (has no loop) or not. For an acyclic region, the 
algorithm tries to match the subgraph
at _n_to an acyclic schemas (3.2). If there is no match,
and the region is a switch candidate, then it attempts to
refine the region at _n_ into a switch region (3.4).
            
If _n_ is cyclic, the algorithm 
compares the region at _n_ to the cyclic schemas (3.5)
If this fails, it refines _n_ into a loop (3.6).
If both matching and refinement do not make progress, the
current node _n_ is then skipped for the current iteration of
the algorithm.  If there is an iteration in which all
nodes are skipped, i.e., the algorithm makes no progress, then
the algorithm employs a last resort refinement (3.7) to
ensure that progress can be made in the next iteration.
#endif
            var result = BuildRegionGraph(proc);
            this.regionGraph = result.Item1;
            var entry = result.Item2;
            DumpGraph();
            newGraph = new DiGraph<Region>();
            do
            {
                this.Changed = false;
                this.doms = new DominatorGraph<Region>(this.regionGraph, result.Item2);
                this.unresolvedCycles = new List<Tuple<Region, ISet<Region>>>(); 
                var postOrder = new DfsIterator<Region>(regionGraph).PostOrder(entry).ToList();
                Debug.Print("Iterating....");
                DumpGraph();
                foreach (var n in postOrder) 
                {
                    entry = Dfs(n);
                }
            } while (Changed);
            return entry;
        }
Ejemplo n.º 19
0
 private static DirectedGraph<int> GetTestGraph()
 {
     var graph = new DirectedGraph<int>();
     graph.AddEdge(0, 1);
     graph.AddEdge(0, 3);
     graph.AddEdge(1, 0);
     graph.AddEdge(1, 2);
     graph.AddEdge(1, 3);
     graph.AddEdge(2, 1);
     graph.AddEdge(2, 3);
     graph.AddEdge(3, 0);
     graph.AddEdge(3, 1);
     graph.AddEdge(3, 2);
     return graph;
 }
Ejemplo n.º 20
0
        public void DirectedGraphFindsCyclesTest()
        {
            var graph = new DirectedGraph<int>(new[] { 1, 2, 3, 4, 5 });

            // Add cycle
            graph.AddEdge(1, 2);
            graph.AddEdge(2, 3);
            graph.AddEdge(3, 1);

            // Add extra edges
            graph.AddEdge(3, 4);
            graph.AddEdge(4, 5);

            graph.FindCycle().ShouldBeEquivalentTo(new[] { 1, 2, 3 }, "Expected cycle vertices to be found");
        }
Ejemplo n.º 21
0
        public void DirectedGraphFindsNoCyclesInAcyclicGraphTest()
        {
            var graph = new DirectedGraph<int>(new[] { 1, 2, 3, 4, 5 });

            // Add non-cyclic edges
            graph.AddEdge(1, 2);
            graph.AddEdge(1, 5);
            graph.AddEdge(2, 3);
            graph.AddEdge(2, 4);
            graph.AddEdge(3, 4);
            graph.AddEdge(3, 5);
            graph.AddEdge(1, 5);

            graph.FindCycle().Should().BeEmpty("Expected no cycle vertices to be found");
        }
        public void GetStronglyConnectedComponentsTest2()
        {
            var graph = new DirectedGraph<int>();
            graph.AddEdge(1, 3);
            graph.AddEdge(3, 5);
            graph.AddEdge(3, 9);
            graph.AddEdge(5, 7);
            graph.AddEdge(7, 1);

            var calculator = new StronglyConnectedComponentsCalculator<int>(graph);
            var components = calculator.GetStronglyConnectedComponents().ToArray();
            components.Should().HaveCount(2);
            components[0].Should().BeEquivalentTo(new[] { 9 });
            components[1].Should().BeEquivalentTo(new[] { 1, 3, 5, 7 });
        }
Ejemplo n.º 23
0
        public void DirectedGraphSortsAcyclicVerticesTest()
        {
            var graph = new DirectedGraph<int>(new[] { 4, 2, 1, 5, 3 });

            // Add non-cyclic edges
            graph.AddEdge(1, 2);
            graph.AddEdge(1, 5);
            graph.AddEdge(2, 3);
            graph.AddEdge(2, 4);
            graph.AddEdge(3, 4);
            graph.AddEdge(3, 5);
            graph.AddEdge(4, 5);

            graph.Sort().Should().BeInAscendingOrder("Expected vertices to be sorted");
        }
Ejemplo n.º 24
0
        public void DirectedGraphSortsThrowsForCyclicVerticesTest()
        {
            var graph = new DirectedGraph<int>(new[] { 4, 2, 1, 5, 3 });

            // Add cycle
            graph.AddEdge(1, 2);
            graph.AddEdge(2, 3);
            graph.AddEdge(3, 1);

            // Add extra edges
            graph.AddEdge(3, 4);
            graph.AddEdge(4, 5);

            graph.Invoking(g => g.Sort()).ShouldThrow<InvalidOperationException>();
        }
Ejemplo n.º 25
0
        public static DirectedGraph CreateDirectedGraph49()
        {
            var g = new DirectedGraph(5);

            g.AddEdge('A', 'B', 4);
            g.AddEdge('A', 'C', 2);
            g.AddEdge('B', 'C', 3);
            g.AddEdge('B', 'D', 2);
            g.AddEdge('B', 'E', 3);
            g.AddEdge('C', 'B', 1);
            g.AddEdge('C', 'D', 4);
            g.AddEdge('C', 'E', 5);
            g.AddEdge('E', 'D', 1);

            return g;
        }
Ejemplo n.º 26
0
        public static DirectedGraph CreateDirectedGraph49_Modfied()
        {
            var g = new DirectedGraph(5);

            g.AddEdge('A', 'B', 4);
            g.AddEdge('A', 'C', 2);
            g.AddEdge('B', 'C', 3);
            g.AddEdge('B', 'D', 2);
            g.AddEdge('B', 'E', 3);
            //AddEdge('C', 'B', 1);//remove cycle
            g.AddEdge('C', 'D', 4);
            g.AddEdge('C', 'E', 5);
            g.AddEdge('E', 'D', 1);

            return g;
        }
 private static DirectedGraph<int> GetTestGraph()
 {
     var graph = new DirectedGraph<int>();
     graph.AddEdge(0, 3);
     graph.AddEdge(1, 7);
     graph.AddEdge(2, 5);
     graph.AddEdge(3, 6);
     graph.AddEdge(4, 1);
     graph.AddEdge(5, 8);
     graph.AddEdge(6, 0);
     graph.AddEdge(7, 4);
     graph.AddEdge(7, 5);
     graph.AddEdge(8, 2);
     graph.AddEdge(8, 6);
     return graph;
 }
        public void FourComponents()
        {
            DirectedGraph<char> graph = new DirectedGraph<char>
            {
                { 'a', new char[] { 'b' } },
                { 'b', new char[] { 'e', 'f' } },
                { 'e', new char[] { 'a', 'f' } },
                { 'c', new char[] { 'd', 'g' } },
                { 'd', new char[] { 'c', 'h' } },
                { 'f', new char[] { 'g' } },
                { 'g', new char[] { 'f', 'h' } },
                { 'h', new char[] { 'h' } },
            };

            IEnumerable<char> vertexes = new char[]{ 'b', 'e', 'a', 'c', 'd', 'g', 'f', 'h' };

            StronglyConenctedComponentsAlgorithm<char> alg = new StronglyConenctedComponentsAlgorithm<char>(graph, vertexes);
            alg.Run();

            var scc = alg.StronglyConnectedComponents;

            Assert.AreEqual(graph.Keys.Count, scc.Keys.Count);

            // scc 1
            Assert.AreEqual(1, scc['b'].Count);
            Assert.AreEqual('e', scc['b'][0]);

            Assert.AreEqual(1, scc['e'].Count);
            Assert.AreEqual('a', scc['e'][0]);

            Assert.AreEqual(0, scc['a'].Count);

            // scc 2
            Assert.AreEqual(1, scc['g'].Count);
            Assert.AreEqual('f', scc['g'][0]);

            Assert.AreEqual(0, scc['f'].Count);

            // scc 3
            Assert.AreEqual(1, scc['c'].Count);
            Assert.AreEqual('d', scc['c'][0]);

            Assert.AreEqual(0, scc['d'].Count);

            // scc 3
            Assert.AreEqual(0, scc['h'].Count);
        }
Ejemplo n.º 29
0
        public static DirectedGraph CreateDirectedGraph38()
        {
            var g = new DirectedGraph(6);

            #region add path

            g.AddEdge(0, 2);
            g.AddEdge(1, 0);
            g.AddEdge(1, 3);
            g.AddEdge(2, 4);
            g.AddEdge(2, 5);
            g.AddEdge(3, 2);

            #endregion

            return g;
        }
Ejemplo n.º 30
0
        static IReadOnlyDictionary<string, IReadOnlyList<Export<IStyleRule, StyleRuleMetadata>>> OrderAndMapRules(
            IReadOnlyList<Export<IStyleRule, StyleRuleMetadata>> rules)
        {
            var languageRuleMap = new Dictionary<string, IReadOnlyList<Export<IStyleRule, StyleRuleMetadata>>>();

            ILookup<string, Export<IStyleRule, StyleRuleMetadata>> languageRuleLookup =
                rules.ToLookup(r => r.Metadata.LanguageName);
            foreach (IGrouping<string, Export<IStyleRule, StyleRuleMetadata>> languageRules in languageRuleLookup)
            {
                var graph = new DirectedGraph<Export<IStyleRule, StyleRuleMetadata>>(languageRules);

                Dictionary<string, Export<IStyleRule, StyleRuleMetadata>> nameRuleMap =
                    languageRules.ToDictionary(r => r.Metadata.Name);
                foreach (Export<IStyleRule, StyleRuleMetadata> languageRule in languageRules)
                {
                    foreach (string afterName in languageRule.Metadata.AfterNames)
                    {
                        Export<IStyleRule, StyleRuleMetadata> afterRule;
                        if (nameRuleMap.TryGetValue(afterName, out afterRule))
                        {
                            graph.AddEdge(afterRule, languageRule);
                        }
                    }

                    foreach (string beforeName in languageRule.Metadata.BeforeNames)
                    {
                        Export<IStyleRule, StyleRuleMetadata> beforeRule;
                        if (nameRuleMap.TryGetValue(beforeName, out beforeRule))
                        {
                            graph.AddEdge(languageRule, beforeRule);
                        }
                    }
                }

                IReadOnlyList<Export<IStyleRule, StyleRuleMetadata>> cycle = graph.FindCycle();
                if (cycle.Count > 0)
                {
                    var ruleNames = String.Join(", ", cycle.Select(r => r.Metadata.Name));
                    throw new InvalidOperationException($"Dependency cycle exists in rules {ruleNames}");
                }

                languageRuleMap.Add(languageRules.Key, graph.Sort());
            }

            return languageRuleMap;
        }
        public void TestVerifiedContraction3TinyOneWay()
        {
            var graph   = new DirectedGraph <CHEdgeData>();
            var vertex1 = graph.AddVertex(1, 0);
            var vertex2 = graph.AddVertex(2, 0);
            var vertex3 = graph.AddVertex(3, 0);
            var vertex4 = graph.AddVertex(4, 0);
            var vertex5 = graph.AddVertex(5, 0);

            graph.AddEdge(vertex1, vertex4, new CHEdgeData(1, true, true, true, 10));
            graph.AddEdge(vertex4, vertex1, new CHEdgeData(1, false, true, true, 10));
            graph.AddEdge(vertex1, vertex2, new CHEdgeData(1, true, true, false, 10));  // oneway forward
            graph.AddEdge(vertex2, vertex1, new CHEdgeData(1, false, false, true, 10)); // oneway backward.
            graph.AddEdge(vertex1, vertex3, new CHEdgeData(1, true, true, true, 10));
            graph.AddEdge(vertex3, vertex1, new CHEdgeData(1, false, true, true, 10));
            graph.AddEdge(vertex2, vertex3, new CHEdgeData(1, true, true, true, 10));
            graph.AddEdge(vertex3, vertex2, new CHEdgeData(1, false, true, true, 10));
            graph.AddEdge(vertex2, vertex5, new CHEdgeData(1, true, true, true, 10));
            graph.AddEdge(vertex5, vertex2, new CHEdgeData(1, false, true, true, 10));

            Assert.IsFalse(graph.ContainsEdges(vertex1, vertex1));
            Assert.IsTrue(graph.ContainsEdges(vertex2, vertex1));
            Assert.IsTrue(graph.ContainsEdges(vertex3, vertex1));
            Assert.IsTrue(graph.ContainsEdges(vertex4, vertex1));
            Assert.IsFalse(graph.ContainsEdges(vertex5, vertex1));
            Assert.IsTrue(graph.ContainsEdges(vertex1, vertex2));
            Assert.IsFalse(graph.ContainsEdges(vertex2, vertex2));
            Assert.IsTrue(graph.ContainsEdges(vertex3, vertex2));
            Assert.IsFalse(graph.ContainsEdges(vertex4, vertex2));
            Assert.IsTrue(graph.ContainsEdges(vertex5, vertex2));
            Assert.IsTrue(graph.ContainsEdges(vertex1, vertex3));
            Assert.IsTrue(graph.ContainsEdges(vertex2, vertex3));
            Assert.IsFalse(graph.ContainsEdges(vertex3, vertex3));
            Assert.IsFalse(graph.ContainsEdges(vertex4, vertex3));
            Assert.IsFalse(graph.ContainsEdges(vertex5, vertex3));
            Assert.IsTrue(graph.ContainsEdges(vertex1, vertex4));
            Assert.IsFalse(graph.ContainsEdges(vertex2, vertex4));
            Assert.IsFalse(graph.ContainsEdges(vertex3, vertex4));
            Assert.IsFalse(graph.ContainsEdges(vertex4, vertex4));
            Assert.IsFalse(graph.ContainsEdges(vertex5, vertex4));
            Assert.IsFalse(graph.ContainsEdges(vertex1, vertex5));
            Assert.IsTrue(graph.ContainsEdges(vertex2, vertex5));
            Assert.IsFalse(graph.ContainsEdges(vertex3, vertex5));
            Assert.IsFalse(graph.ContainsEdges(vertex4, vertex5));
            Assert.IsFalse(graph.ContainsEdges(vertex5, vertex5));

            var witnessCalculator = new DykstraWitnessCalculator();
            var preProcessor      = new CHPreProcessor(graph,
                                                       new EdgeDifferenceContractedSearchSpace(graph, witnessCalculator), witnessCalculator);

            preProcessor.Start();

            var router = new CHRouter();
            // expected: (4)-10s-(1)-10s-(2)-10s-(3) (30s in total).
            var path = router.Calculate(graph, 4, 5);

            Assert.IsNotNull(path);
            Assert.AreEqual(30, path.Weight);
            var pathArray = path.ToArrayWithWeight();

            Assert.AreEqual(4, pathArray.Length);
            float latitude, longitude;

            Assert.AreEqual(0, pathArray[0].Item2);
            Assert.IsTrue(graph.GetVertex((uint)pathArray[0].Item1, out latitude, out longitude));
            Assert.AreEqual(4, latitude);
            Assert.AreEqual(10, pathArray[1].Item2);
            Assert.IsTrue(graph.GetVertex((uint)pathArray[1].Item1, out latitude, out longitude));
            Assert.AreEqual(1, latitude);
            Assert.AreEqual(20, pathArray[2].Item2);
            Assert.IsTrue(graph.GetVertex((uint)pathArray[2].Item1, out latitude, out longitude));
            Assert.AreEqual(2, latitude);
            Assert.AreEqual(30, pathArray[3].Item2);
            Assert.IsTrue(graph.GetVertex((uint)pathArray[3].Item1, out latitude, out longitude));
            Assert.AreEqual(5, latitude);

            // expected: (5)-10s-(2)-10s-(3)-10s-(1)-10s-(4) (40s in total).
            path = router.Calculate(graph, 5, 4);
            Assert.IsNotNull(path);
            Assert.AreEqual(40, path.Weight);
            pathArray = path.ToArrayWithWeight();
            Assert.AreEqual(5, pathArray.Length);
            Assert.AreEqual(0, pathArray[0].Item2);
            Assert.IsTrue(graph.GetVertex((uint)pathArray[0].Item1, out latitude, out longitude));
            Assert.AreEqual(5, latitude);
            Assert.AreEqual(10, pathArray[1].Item2);
            Assert.IsTrue(graph.GetVertex((uint)pathArray[1].Item1, out latitude, out longitude));
            Assert.AreEqual(2, latitude);
            Assert.AreEqual(20, pathArray[2].Item2);
            Assert.IsTrue(graph.GetVertex((uint)pathArray[2].Item1, out latitude, out longitude));
            Assert.AreEqual(3, latitude);
            Assert.AreEqual(30, pathArray[3].Item2);
            Assert.IsTrue(graph.GetVertex((uint)pathArray[3].Item1, out latitude, out longitude));
            Assert.AreEqual(1, latitude);
            Assert.AreEqual(40, pathArray[4].Item2);
            Assert.IsTrue(graph.GetVertex((uint)pathArray[4].Item1, out latitude, out longitude));
            Assert.AreEqual(4, latitude);
        }
Ejemplo n.º 32
0
 public DirectedGraphContainer(DirectedGraph graph)
 {
     DirectedGraphInfo = graph;
 }
Ejemplo n.º 33
0
 public SccFinder(DirectedGraph <T> graph, Action <IList <T> > processScc) :
     this(graph, x => { }, processScc)
 {
 }
        /// <summary>
        /// Generates simple-styled graph
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="colors">The colors: Color.LightGray, Color.WhiteSmoke, Color.OrangeRed, Color.CadetBlue, Color.Yellow, Color.SteelBlue, Color.Orchid</param>
        /// <param name="limit">The limit.</param>
        /// <returns></returns>
        public DirectedGraph GetModelGraph(pipelineModel <pipelineTaskSubjectContentToken> model, Color[] colors = null, Int32 limit = 10)
        {
            if (colors == null)
            {
                colors = new Color[] { Color.LightGray, Color.WhiteSmoke, Color.OrangeRed, Color.GreenYellow, Color.Yellow, Color.SteelBlue, Color.Orchid, Color.Yellow, Color.SteelBlue, Color.Orchid };
            }
            DirectedGraph output = new DirectedGraph();

            output.Title = model.name;

            output.Layout = imbSCI.Graph.DGML.enums.GraphLayoutEnum.Sugiyama;
            output.NeighborhoodDistance = 20;

            var st_basic       = output.Categories.AddOrGetCategory(0, nameof(pipelineNodeTypeEnum.none), "");
            var st_taskBuilder = output.Categories.AddOrGetCategory(pipelineNodeTypeEnum.taskBuilder.ToInt32(), nameof(pipelineNodeTypeEnum.taskBuilder), nameof(pipelineNodeTypeEnum.none));
            var st_distributor = output.Categories.AddOrGetCategory(pipelineNodeTypeEnum.distributor.ToInt32(), nameof(pipelineNodeTypeEnum.distributor), nameof(pipelineNodeTypeEnum.none));
            var st_transformer = output.Categories.AddOrGetCategory(pipelineNodeTypeEnum.transformer.ToInt32(), nameof(pipelineNodeTypeEnum.transformer), nameof(pipelineNodeTypeEnum.none));
            var st_bin         = output.Categories.AddOrGetCategory(pipelineNodeTypeEnum.bin.ToInt32(), nameof(pipelineNodeTypeEnum.bin), nameof(pipelineNodeTypeEnum.none));
            var st_model       = output.Categories.AddOrGetCategory(pipelineNodeTypeEnum.model.ToInt32(), nameof(pipelineNodeTypeEnum.model), nameof(pipelineNodeTypeEnum.none));

            st_basic.Stroke          = colors[0].ColorToHex();
            st_basic.StrokeThinkness = 2;
            st_basic.Background      = colors[1].ColorToHex();

            st_bin.StrokeDashArray = "5,2,5,2";

            st_taskBuilder.Background = colors[2].ColorToHex();
            st_transformer.Background = colors[3].ColorToHex();

            st_distributor.Background = colors[4].ColorToHex();

            st_bin.Background = colors[5].ColorToHex();

            st_model.Background = colors[6].ColorToHex();

            List <IPipelineNode> totalSet = new List <IPipelineNode>();
            List <IPipelineNode> nextSet  = new List <IPipelineNode>();

            nextSet.Add(model);
            Int32 i = 0;

            Node modelMainNode = null;
            Node trashBinNode  = null;
            Node exitBinNode   = null;

            while (nextSet.Any())
            {
                i++;
                List <IPipelineNode> newNextSet = new List <IPipelineNode>();
                // <---------------------------------------------------[ * ]
                foreach (IPipelineNode parent in nextSet)
                {
                    if (totalSet.Contains(parent))
                    {
                        continue;
                    }

                    if (parent == null)
                    {
                        continue;
                    }
                    parent.SetLabel();

                    Node parentNode = output.Nodes.AddNode(parent.path, parent.Label);

                    if (parentNode == null)
                    {
                        continue;
                    }

                    // <-------------------------------------------------------------------------------  //
                    if (parent.parent != null)
                    {
                        ordinalSet.Add(parent.parent as IPipelineNode, parent);                         //
                    }
                    // <-----------------------------------------------------------------------------  //

                    if (!nodeRegistry.ContainsKey(parent))
                    {
                        nodeRegistry.Add(parent, parentNode);
                    }

                    SetCategory(parentNode, parent);

                    if (parent is IPipelineModel pipeModel)
                    {
                        trashBinNode          = output.Nodes.AddNode(pipeModel.trashBin.path, pipeModel.trashBin.Label);
                        exitBinNode           = output.Nodes.AddNode(pipeModel.exitBin.path, pipeModel.exitBin.Label);
                        trashBinNode.Category = pipelineNodeTypeEnum.bin.ToInt32().ToString();
                        exitBinNode.Category  = pipelineNodeTypeEnum.bin.ToInt32().ToString();

                        if (!nodeRegistry.ContainsKey(pipeModel.trashBin))
                        {
                            nodeRegistry.Add(pipeModel.trashBin, trashBinNode);
                        }

                        if (!nodeRegistry.ContainsKey(pipeModel.exitBin))
                        {
                            nodeRegistry.Add(pipeModel.exitBin, exitBinNode);
                        }

                        //var trashNode = output.Nodes.AddNode(.path, pipeModel.trashBin.Label);

                        modelMainNode = parentNode;

                        //  AddAndLink(output, parentNode, pipeModel.exitBin, newNextSet, Color.Green).Label = "Output";
                    }

                    if (parent is pipelineContentTokenLevelDistribution distNode)
                    {
                        if (distNode != null)
                        {
                            AddAndLink(output, parentNode, distNode?.repoPipeline, newNextSet, Color.Violet, "Repository");
                            AddAndLink(output, parentNode, distNode?.sitePipeline, newNextSet, Color.Violet, "Site");
                            AddAndLink(output, parentNode, distNode?.pagePipeline, newNextSet, Color.Violet, "Page");
                            AddAndLink(output, parentNode, distNode?.blockPipeline, newNextSet, Color.Violet, "Block");
                            AddAndLink(output, parentNode, distNode?.streamPipeline, newNextSet, Color.Violet, "Stream");
                            AddAndLink(output, parentNode, distNode?.chunkPipeline, newNextSet, Color.Violet, "Chunk");
                            AddAndLink(output, parentNode, distNode?.tokenPipeline, newNextSet, Color.Violet, "Token");
                        }
                    }
                    else if (parent.nodeType == pipelineNodeTypeEnum.distributor)
                    {
                        parentNode.Label = GetLabel(parent);
                    }
                    else
                    {
                        var lNext = AddAndLink(output, parentNode, parent.next, newNextSet, Color.SteelBlue, "Next");
                        if (parent.next == model.exitBin)
                        {
                            if (lNext != null)
                            {
                                lNext.StrokeDashArray = "2,3,2,3";
                                lNext.Label           = "Done";
                            }
                        }

                        var lForward = AddAndLink(output, parentNode, parent.forward, newNextSet, Color.OrangeRed, "Forward");
                    }

                    if (parent.nodeType == pipelineNodeTypeEnum.distributor)
                    {
                        var tl = output.Links.AddLink(parentNode, trashBinNode, "Removed");
                        tl.Stroke          = Color.Gray.ColorToHex();
                        tl.StrokeDashArray = "2,2,5,2,5";
                        tl.StrokeThinkness = 8;
                    }

                    if (parent.GetType().Name.Contains("TaskBuilder"))
                    {
                        if (modelMainNode != null)
                        {
                            var ntl = output.Links.AddLink(parentNode, modelMainNode, "New Tasks");
                            ntl.Stroke          = Color.MediumVioletRed.ColorToHex();
                            ntl.StrokeDashArray = "2,2,5,2,5";
                            ntl.StrokeThinkness = 8;
                        }
                    }

                    if (parent.parent != null)
                    {
                        IPipelineNode parentFolder = parent.parent as IPipelineNode;

                        var l = new Link(parentFolder.path, parentNode.Id, true);

                        if (parentFolder.next == parent)
                        {
                            l.Stroke          = Color.SteelBlue.ColorToHex();
                            l.Label           = "No";
                            l.StrokeThinkness = 4;
                            output.Links.Add(l);
                        }
                        else if (parentFolder.forward == parent)
                        {
                            l.Stroke          = Color.OrangeRed.ColorToHex();
                            l.Label           = "Execute";
                            l.StrokeThinkness = 6;
                            output.Links.Add(l);
                        }
                        else
                        {
                            l.Stroke          = Color.DarkGray.ColorToHex();
                            l.Label           = "Owner";
                            l.StrokeDashArray = "2,5,2,5";
                            l.StrokeThinkness = 2;
                        }
                        // output.Links.Add(l);
                    }

                    foreach (var pair in parent)
                    {
                        if (!newNextSet.Contains(pair))
                        {
                            newNextSet.Add(pair as IPipelineNode);
                            totalSet.Add(pair as IPipelineNode);
                        }
                    }
                }

                if (i > limit)
                {
                    break;
                }
                nextSet = newNextSet;
            }
            // <---------------------------------------------------[ * ]

            // <---------------------------------------------------[ * ]
            foreach (var pair in ordinalSet)
            {
                IPipelineNode firstPipelineNode = null;
                Node          firstNode         = null;

                IPipelineNode currentPipelineNode = null;
                Node          currentNode         = null;

                foreach (IPipelineNode p in pair.Value)
                {
                    if (firstPipelineNode == null)
                    {
                        firstPipelineNode = p;
                        firstNode         = nodeRegistry[firstPipelineNode];
                    }
                    else
                    {
                        //var ld = output.Links.AddLink(firstNode, nodeRegistry[p], "Next");
                        //ld.Stroke = Color.SteelBlue.ColorToHex();
                        //ld.StrokeDashArray = "2,5,2,5";
                        //ld.StrokeThinkness = 4;
                        firstNode = nodeRegistry[p];
                    }
                    currentNode         = nodeRegistry[p];
                    currentPipelineNode = p;
                }

                if (pair.Key.level > 1)
                {
                    var l = output.Links.AddLink(currentNode, nodeRegistry[model.exitBin], "Done");
                    l.Stroke = Color.SteelBlue.ColorToHex();
                    //l.StrokeDashArray = "";
                    l.StrokeThinkness = 4;
                }
            }
            // <---------------------------------------------------[ * ]

            // <---------------------------------------------------[ * ]
            var allEnums = Enum.GetValues(typeof(pipelineNodeTypeEnum));

            var LEGEND = output.Nodes.AddNode("LEGEND");

            foreach (pipelineNodeTypeEnum en in allEnums)
            {
                var n = output.Nodes.AddNode("LEG" + en.ToString(), en.ToString().imbTitleCamelOperation(true));
                n.Category = en.ToInt32().ToString();
                var l = output.Links.AddLink(LEGEND, n, "");
                l.StrokeDashArray = "5,5,5,5";
            }
            // <---------------------------------------------------[ * ]

            //var st_basic = output.Categories.AddOrGetCategory(0, nameof(pipelineNodeTypeEnum.none), "");
            //var st_taskBuilder = output.Categories.AddOrGetCategory(pipelineNodeTypeEnum.taskBuilder.ToInt32(), nameof(pipelineNodeTypeEnum.taskBuilder), nameof(pipelineNodeTypeEnum.none));
            //var st_distributor = output.Categories.AddOrGetCategory(pipelineNodeTypeEnum.distributor.ToInt32(), nameof(pipelineNodeTypeEnum.distributor), nameof(pipelineNodeTypeEnum.none));
            //var st_transformer = output.Categories.AddOrGetCategory(pipelineNodeTypeEnum.transformer.ToInt32(), nameof(pipelineNodeTypeEnum.transformer), nameof(pipelineNodeTypeEnum.none));
            //var st_bin = output.Categories.AddOrGetCategory(pipelineNodeTypeEnum.bin.ToInt32(), nameof(pipelineNodeTypeEnum.bin), nameof(pipelineNodeTypeEnum.none));
            //var st_model = output.Categories.AddOrGetCategory(pipelineNodeTypeEnum.model.ToInt32(), nameof(pipelineNodeTypeEnum.model), nameof(pipelineNodeTypeEnum.none));

            return(output);
        }
Ejemplo n.º 35
0
        private Boolean TestCaseTags(DirectedGraph dg, TestCase tc)
        {
            Boolean ret = false;

            foreach (KeyValuePair <String, String> pair in dg.Values)
            {
                switch (pair.Key)
                {
                case "TDSTATE":
                    tc.TDstate = HttpUtility.UrlDecode(pair.Value);
                    break;

                case "TDASSIGNED":
                    tc.TDassigned = HttpUtility.UrlDecode(pair.Value);
                    break;

                case "TDREASON":
                    tc.TDreason = HttpUtility.UrlDecode(pair.Value);
                    break;

                case "TDITERATIONPATH":
                    tc.TDiterationPath = HttpUtility.UrlDecode(pair.Value);
                    break;

                case "TDAREAPATH":
                    tc.TDareaPath = HttpUtility.UrlDecode(pair.Value);
                    break;

                case "TDAPPLICATION":
                    tc.TDapplication = HttpUtility.UrlDecode(pair.Value);
                    break;

                case "TDCOMPLEXITY":
                    tc.TDcomplexity = HttpUtility.UrlDecode(pair.Value);
                    break;

                case "TDRISKS":
                    tc.TDrisks = HttpUtility.UrlDecode(pair.Value);
                    break;

                case "TDTCLIFECYCLE":
                    tc.TDtcLifecycle = HttpUtility.UrlDecode(pair.Value);
                    break;

                case "TDLIFECYCLETYPE":
                    tc.TDlifecycleType = HttpUtility.UrlDecode(pair.Value);
                    break;

                case "TDTCTEAMUSAGE":
                    tc.TDtcTeamUsage = HttpUtility.UrlDecode(pair.Value);
                    break;

                case "TDPOSTCONDITIONS":
                    tc.TDpostConditions = HttpUtility.UrlDecode(pair.Value);
                    ret = true;
                    break;

                case "TDPRECONDITIONS":
                    tc.TDpreConditions = HttpUtility.UrlDecode(pair.Value);
                    ret = true;
                    break;

                default:
                    break;
                }
            }
            return(ret);
        }
Ejemplo n.º 36
0
        private static void SaveGroup(Schema schema, IGrouping <TypeNew, Entity> group, DirectedGraph <Entity> backEdges)
        {
            Table table = schema.Table(group.Key.Type);

            if (group.Key.IsNew)
            {
                table.InsertMany(group.ToList(), backEdges);
            }
            else
            {
                table.UpdateMany(group.ToList(), backEdges);
            }
        }
Ejemplo n.º 37
0
 internal PreSavingContext(DirectedGraph <Modifiable> graph)
 {
     this.Graph = graph;
 }
Ejemplo n.º 38
0
 public static DirectedGraph <Modifiable> FromRootsEntity <T>(IEnumerable <T> roots)
     where T : Modifiable
 {
     return(DirectedGraph <Modifiable> .Generate(roots.Cast <Modifiable>(), ModifyInspector.EntityExplore, ReferenceEqualityComparer <Modifiable> .Default));
 }
Ejemplo n.º 39
0
        public static List <IntegrityCheckWithEntity> WithEntities(this Dictionary <Guid, IntegrityCheck> integrityChecks, DirectedGraph <Modifiable> graph)
        {
            var modifiableEntities = graph.OfType <ModifiableEntity>().ToDictionary(a => a.temporalId);

            return(integrityChecks.Values.Select(a => new IntegrityCheckWithEntity(a, modifiableEntities.GetOrThrow(a.TemporalId))).ToList());
        }
Ejemplo n.º 40
0
        /// <summary>
        /// PageRank computes a ranking of the nodes in the graph G based on
        /// the structure of the incoming links.It was originally designed as
        /// an algorithm to rank web pages.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <description></description>
        /// <param name="graph"></param>
        /// <description></description>
        /// <param name="alpha"></param>
        /// <description></description>
        /// <param name="maxItteration"></param>
        /// <description></description>
        /// <param name="tol"></param>
        /// <description></description>
        /// <param name="nstart"></param>
        /// <description></description>
        /// <param name="personalization"></param>
        /// <description></description>
        /// <param name="dangling"></param>
        /// <description></description>
        /// <returns>rankVector</returns>
        public Dictionary <T, double> Rank <T>(DirectedGraph <T> graph, double alpha = 0.85,
                                               double maxItteration            = 100, double tol = 1.0e-6,
                                               Dictionary <T, double> nstart   = null, Dictionary <T, double> personalization = null,
                                               Dictionary <T, double> dangling = null)
        {
            Dictionary <T, double> _rankVector = null;
            DirectedGraph <T>      dGraph;

            // Boundary condition
            // Check if graph is empty then return with empty page rank dictionary
            if (graph.IsEmpty)
            {
                return(null);
            }

            if (!graph.IsDirected)
            {
                // Convert to directed graph
                //dgraph = Graph.BuildDirectedGraph(graph);
            }
            else
            {
                dGraph = graph;
            }

            //Create a copy in (right) stochastic form
            //stochasti matrix has a square matrix that have summation of each row is 1.
            DirectedGraph <T> sGraph = GraphUtils.ToStochastic(graph);

            int N = sGraph.Count();

            Dictionary <GraphNode <T>, double> _x = new Dictionary <GraphNode <T>, double>();
            Dictionary <GraphNode <T>, double> _p = new Dictionary <GraphNode <T>, double>();
            Dictionary <GraphNode <T>, double> _dangling_weights = new Dictionary <GraphNode <T>, double>();

            // Choose fixed starting vector if not given
            if (nstart == null)
            {
                _x = sGraph.Nodes.ToDictionary(item => item as GraphNode <T>, val => 1.0 / N);
            }
            else
            {
                // Normalized nstart vector
                double _nSum = (double)nstart.Sum(node => node.Value);
                _p = nstart.ToDictionary(item => item.Key as GraphNode <T>, item => item.Value / _nSum);
            }

            if (personalization == null)
            {
                _p = sGraph.Nodes.ToDictionary(item => item as GraphNode <T>, val => 1.0 / N);
            }
            else
            {
                // Normalized personalization vector
                double _pSum = (double)personalization.Sum(node => node.Value);
                _p = personalization.ToDictionary(item => item.Key as GraphNode <T>, item => item.Value / _pSum);
            }

            if (dangling == null)
            {
                _dangling_weights = sGraph.Nodes.ToDictionary(item => item as GraphNode <T>, val => 1.0 / N);
            }
            else
            {
                // Normalized personalization vector
                double _dSum = (double)dangling.Sum(node => node.Value);
                _dangling_weights = dangling.ToDictionary(item => item.Key as GraphNode <T>, item => item.Value / _dSum);
            }

            // Get the dangling nodes of graph
            List <GraphNode <T> > _danglingNodes = sGraph.DanglingNodes;

            Dictionary <GraphNode <T>, double> _xLast = _x;

            do
            {
                //copy the the older rank value
                _xLast = _x.ToDictionary(item => item.Key, item => item.Value);
                _x     = _xLast.ToDictionary(item => item.Key, value => 0.0);

                //calculate the dangling sum
                var danglesum = alpha * _xLast.Where(x => _danglingNodes.Any(item => x.Key == item)).Sum(v => v.Value);

                foreach (GraphNode <T> page in _x.Keys.ToList())
                {
                    var nbrs = sGraph[page];
                    foreach (var nbr in nbrs)
                    {
                        var xn = _xLast[page];
                        var we = sGraph[page, nbr.GraphNode as GraphNode <T> ];
                        _x[nbr.GraphNode as GraphNode <T> ] += alpha * xn * we;
                    }

                    var _dnglWeight = _dangling_weights.ContainsKey(page) ? _dangling_weights[page] : 0;
                    var _perWeight  = _dangling_weights.ContainsKey(page) ? _dangling_weights[page] : 0;
                    _x[page] += danglesum * _dnglWeight + (1.0 - alpha) * _perWeight;
                }

                //check convergence, l1 norm
                double err = 0.0;
                foreach (var node in _x.Keys.ToList())
                {
                    err += Math.Abs(_x[node] - _xLast[node]);
                }

                if (err < N * tol)
                {
                    _rankVector = _x.ToDictionary(item => item.Key.Value, item => item.Value);
                    break;
                }
            } while (maxItteration-- > 0);

            return(_rankVector);
        }
Ejemplo n.º 41
0
 public PipExecutionData(CachedGraph cachedGraph, DirectedGraph dataflowGraphOverride = null)
 {
     CachedGraph   = cachedGraph;
     DataflowGraph = dataflowGraphOverride ?? CachedGraph.DataflowGraph;
 }
Ejemplo n.º 42
0
        public void CommandifiedGraphAddRemoveGraphAndEdgesWithUndoTest()
        {
            Guid sessionId = Guid.NewGuid();

            CQManager.ActivateCommandQueueStack(sessionId);

            DirectedGraph <int, DirectedEdge <int> > graph = new DirectedGraph <int, DirectedEdge <int> >(true);

            graph.Add(42);
            graph.Add(13);
            graph.Add(10);
            graph.Add(new DirectedEdge <int>(42, 13));                  // 42 -> 13
            graph.Add(new DirectedEdge <int>(42, 10));                  // 42 -> 10
            Assert.IsTrue(graph.Contains(42));
            Assert.IsTrue(graph.Contains(13));
            Assert.IsTrue(graph.Contains(10));
            Assert.AreEqual(2, graph.EdgeCount);
            Assert.IsTrue(graph.ContainsEdge(42, 13));
            Assert.IsTrue(graph.ContainsEdge(42, 10));

            // create graph to add to this graph. Doesn't have to be a commandified graph, as we're not rolling back the actions on that graph.
            DirectedGraph <int, DirectedEdge <int> > graphToAdd = new DirectedGraph <int, DirectedEdge <int> >();

            graphToAdd.Add(1);
            graphToAdd.Add(2);
            graphToAdd.Add(3);
            graphToAdd.Add(new DirectedEdge <int>(1, 2));               // 1 -> 2
            graphToAdd.Add(new DirectedEdge <int>(1, 3));               // 1 -> 3
            graphToAdd.Add(new DirectedEdge <int>(2, 3));               // 2 -> 3
            Assert.AreEqual(3, graphToAdd.VertexCount);
            Assert.AreEqual(3, graphToAdd.EdgeCount);

            // add this graph to the main graph. This is an undoable action.
            graph.Add(graphToAdd);
            Assert.AreEqual(6, graph.VertexCount);
            Assert.AreEqual(5, graph.EdgeCount);
            Assert.IsTrue(graph.Contains(1));
            Assert.IsTrue(graph.Contains(2));
            Assert.IsTrue(graph.Contains(3));
            Assert.IsTrue(graph.ContainsEdge(1, 2));
            Assert.IsTrue(graph.ContainsEdge(1, 3));
            Assert.IsTrue(graph.ContainsEdge(2, 3));

            // undo add
            CQManager.UndoLastCommand();
            Assert.AreEqual(3, graph.VertexCount);
            Assert.AreEqual(2, graph.EdgeCount);
            Assert.IsFalse(graph.Contains(1));
            Assert.IsFalse(graph.Contains(2));
            Assert.IsFalse(graph.Contains(3));
            Assert.IsFalse(graph.ContainsEdge(1, 2));
            Assert.IsFalse(graph.ContainsEdge(1, 3));
            Assert.IsFalse(graph.ContainsEdge(2, 3));

            // redo
            CQManager.RedoLastCommand();
            Assert.AreEqual(6, graph.VertexCount);
            Assert.AreEqual(5, graph.EdgeCount);
            Assert.IsTrue(graph.Contains(1));
            Assert.IsTrue(graph.Contains(2));
            Assert.IsTrue(graph.Contains(3));
            Assert.IsTrue(graph.ContainsEdge(1, 2));
            Assert.IsTrue(graph.ContainsEdge(1, 3));
            Assert.IsTrue(graph.ContainsEdge(2, 3));

            // remove the graph we added
            graph.Remove(graphToAdd);
            Assert.AreEqual(3, graph.VertexCount);
            Assert.AreEqual(2, graph.EdgeCount);
            Assert.IsFalse(graph.Contains(1));
            Assert.IsFalse(graph.Contains(2));
            Assert.IsFalse(graph.Contains(3));
            Assert.IsFalse(graph.ContainsEdge(1, 2));
            Assert.IsFalse(graph.ContainsEdge(1, 3));
            Assert.IsFalse(graph.ContainsEdge(2, 3));

            CQManager.UndoLastCommand();
            Assert.AreEqual(6, graph.VertexCount);
            Assert.AreEqual(5, graph.EdgeCount);
            Assert.IsTrue(graph.Contains(1));
            Assert.IsTrue(graph.Contains(2));
            Assert.IsTrue(graph.Contains(3));
            Assert.IsTrue(graph.ContainsEdge(1, 2));
            Assert.IsTrue(graph.ContainsEdge(1, 3));
            Assert.IsTrue(graph.ContainsEdge(2, 3));

            DirectedEdge <int> newEdge = new DirectedEdge <int>(42, 1);                         // 42 -> 1

            graph.Add(newEdge);
            Assert.AreEqual(6, graph.EdgeCount);
            Assert.IsTrue(graph.ContainsEdge(42, 1));
            Assert.IsFalse(graph.ContainsEdge(1, 42));

            CQManager.UndoLastCommand();
            Assert.AreEqual(5, graph.EdgeCount);
            Assert.IsFalse(graph.ContainsEdge(42, 1));

            CQManager.RedoLastCommand();
            Assert.AreEqual(6, graph.EdgeCount);
            Assert.IsTrue(graph.ContainsEdge(42, 1));

            graph.Remove(newEdge);
            Assert.AreEqual(5, graph.EdgeCount);
            Assert.IsFalse(graph.ContainsEdge(42, 1));

            CQManager.UndoLastCommand();
            Assert.AreEqual(6, graph.EdgeCount);
            Assert.IsTrue(graph.ContainsEdge(42, 1));

            graph.Disconnect(42, 1, false);
            Assert.AreEqual(5, graph.EdgeCount);
            Assert.IsFalse(graph.ContainsEdge(42, 1));

            CQManager.UndoLastCommand();
            Assert.AreEqual(6, graph.EdgeCount);
            Assert.IsTrue(graph.ContainsEdge(42, 1));

            CQManager.ActivateCommandQueueStack(Guid.Empty);
        }
Ejemplo n.º 43
0
 public static Dictionary <TNode, TNode?> Create(DirectedGraph <TNode> graph, TNode root)
 {
     return(new Builder(graph, root).Dominators());
 }
Ejemplo n.º 44
0
 public RtlBackwalkHost(Program program, DirectedGraph <RtlBlock> graph)
 {
     this.program = program;
     this.graph   = graph;
 }
 /// <summary>
 /// Displays the shortest exit path on the graph.
 /// </summary>
 /// <param name="u"></param>
 /// <param name="v"></param>
 /// <param name="maze"></param>
 /// <param name="paths"></param>
 /// <param name="graph"></param>
 private static void DisplayPath(Cell u, Cell v, Maze maze, Dictionary <Cell, Cell> paths, DirectedGraph <Cell, Direction> graph)
 {
     while (v != u)
     {
         Cell      temp = paths[v];
         Direction x;
         graph.TryGetEdge(temp, v, out x);
         maze.DrawPath(temp, x);
         v = temp;
     }
 }
Ejemplo n.º 46
0
 private DfsIterator <T> CreateGraphIterator <T>(DirectedGraph <T> graph) where T : class
 {
     return(new DfsIterator <T>(graph));
 }
Ejemplo n.º 47
0
 public GraphTests()
 {
     sut = new DirectedGraph <int>();
 }
        public static DirectedGraphAcyclic CreateDirectedGraphAcyclic(
            DirectedGraph digraph,
            GraphDepthInfo depthInfo,
            out int[] newIdByOldId,
            out int[] connectionIndexMap,
            ref int[]?timsortWorkArr,
            ref int[]?timsortWorkVArr)
        {
            int inputCount  = digraph.InputCount;
            int outputCount = digraph.OutputCount;

            // Assert that all input nodes are at depth zero.
            // Any input node with a non-zero depth must have an input connection, and this is not supported.
            Debug.Assert(SpanUtils.Equals(depthInfo._nodeDepthArr.AsSpan(0, inputCount), 0));

            // Compile a mapping from current node IDs to new IDs (based on node depth in the graph).
            newIdByOldId = CompileNodeIdMap(depthInfo, digraph.TotalNodeCount, inputCount, ref timsortWorkArr, ref timsortWorkVArr);

            // Map the connection node IDs.
            ConnectionIdArrays connIdArrays = digraph.ConnectionIdArrays;

            MapIds(connIdArrays, newIdByOldId);

            // Init connection index map.
            int connCount = connIdArrays.Length;

            connectionIndexMap = new int[connCount];
            for (int i = 0; i < connCount; i++)
            {
                connectionIndexMap[i] = i;
            }

            // Sort the connections based on sourceID, targetId; this will arrange the connections based on the depth
            // of the source nodes.
            // Note. This sort routine will also sort a secondary array, i.e. keep the items in both arrays aligned;
            // here we use this to create connectionIndexMap.
            ConnectionSorter <int> .Sort(connIdArrays, connectionIndexMap);

            // Make a copy of the sub-range of newIdMap that represents the output nodes.
            // This is required later to be able to locate the output nodes now that they have been sorted by depth.
            int[] outputNodeIdxArr = new int[outputCount];
            Array.Copy(newIdByOldId, inputCount, outputNodeIdxArr, 0, outputCount);

            // Create an array of LayerInfo(s).
            // Each LayerInfo contains the index + 1 of both the last node and last connection in that layer.
            //
            // The array is in order of depth, from layer zero (inputs nodes) to the last layer (usually output nodes,
            // but not necessarily if there is a dead end pathway with a high number of hops).
            //
            // Note. There is guaranteed to be at least one connection with a source at a given depth level, this is
            // because for there to be a layer N there must necessarily be a connection from a node in layer N-1
            // to a node in layer N.
            int graphDepth = depthInfo._graphDepth;

            LayerInfo[] layerInfoArr = new LayerInfo[graphDepth];

            // Note. Scanning over nodes can start at inputCount instead of zero, because all nodes prior to that index
            // are input nodes and are therefore at depth zero. (input nodes are never the target of a connection,
            // therefore are always guaranteed to be at the start of a connectivity graph, and thus at depth zero).
            int nodeCount = digraph.TotalNodeCount;
            int nodeIdx   = inputCount;
            int connIdx   = 0;

            int[] nodeDepthArr = depthInfo._nodeDepthArr;
            int[] srcIdArr     = connIdArrays._sourceIdArr;

            for (int currDepth = 0; currDepth < graphDepth; currDepth++)
            {
                // Scan for last node at the current depth.
                for (; nodeIdx < nodeCount && nodeDepthArr[nodeIdx] == currDepth; nodeIdx++)
                {
                    ;
                }

                // Scan for last connection at the current depth.
                for (; connIdx < srcIdArr.Length && nodeDepthArr[srcIdArr[connIdx]] == currDepth; connIdx++)
                {
                    ;
                }

                // Store node and connection end indexes for the layer.
                layerInfoArr[currDepth] = new LayerInfo(nodeIdx, connIdx);
            }

            // Construct and return.
            return(new DirectedGraphAcyclic(
                       inputCount, outputCount, nodeCount,
                       connIdArrays,
                       layerInfoArr,
                       outputNodeIdxArr));
        }
Ejemplo n.º 49
0
        public static void Save(Entity[] entities)
        {
            if (entities == null || entities.Any(e => e == null))
            {
                throw new ArgumentNullException("entity");
            }

            using (var log = HeavyProfiler.LogNoStackTrace("PreSaving"))
            {
                Schema schema = Schema.Current;
                DirectedGraph <Modifiable> modifiables = PreSaving(() => GraphExplorer.FromRoots(entities));

                HashSet <Entity> wasNew          = modifiables.OfType <Entity>().Where(a => a.IsNew).ToHashSet(ReferenceEqualityComparer <Entity> .Default);
                HashSet <Entity> wasSelfModified = modifiables.OfType <Entity>().Where(a => a.Modified == ModifiedState.SelfModified).ToHashSet(ReferenceEqualityComparer <Entity> .Default);

                log.Switch("Integrity");

                var error = GraphExplorer.FullIntegrityCheck(modifiables);
                if (error != null)
                {
#if DEBUG
                    throw new IntegrityCheckException(error.WithEntities(modifiables));
#else
                    throw new IntegrityCheckException(error);
#endif
                }

                log.Switch("Graph");

                GraphExplorer.PropagateModifications(modifiables.Inverse());

                //colapsa modifiables (collections and embeddeds) keeping indentifiables only
                DirectedGraph <Entity> identifiables = GraphExplorer.ColapseIdentifiables(modifiables);

                foreach (var node in identifiables)
                {
                    schema.OnSaving(node);
                }

                //Remove all the edges that doesn't mean a dependency
                identifiables.RemoveEdges(identifiables.Edges.Where(e => !e.To.IsNew).ToList());

                //Remove all the nodes that are not modified
                List <Entity> notModified = identifiables.Where(node => !node.IsGraphModified).ToList();

                notModified.ForEach(node => identifiables.RemoveFullNode(node, None));

                log.Switch("SaveGroups");

                SaveGraph(schema, identifiables);

                foreach (var node in identifiables)
                {
                    schema.OnSaved(node, new SavedEventArgs
                    {
                        IsRoot          = entities.Contains(node),
                        WasNew          = wasNew.Contains(node),
                        WasSelfModified = wasSelfModified.Contains(node),
                    });
                }

                EntityCache.Add(identifiables);
                EntityCache.Add(notModified);

                GraphExplorer.CleanModifications(modifiables);
            }
        }
Ejemplo n.º 50
0
        /// <summary>Calculate / create a directed graph from model</summary>
        public void CalculateDirectedGraph()
        {
            DirectedGraph oldGraph = directedGraphInfo;

            if (directedGraphInfo == null)
            {
                directedGraphInfo = new DirectedGraph();
            }

            directedGraphInfo.Begin();

            bool needAtmosphereNode = false;

            foreach (NutrientPool pool in this.FindAllChildren <NutrientPool>())
            {
                Point location = default(Point);
                Node  oldNode;
                if (oldGraph != null && pool.Name != null && (oldNode = oldGraph.Nodes.Find(f => f.Name == pool.Name)) != null)
                {
                    location = oldNode.Location;
                }
                directedGraphInfo.AddNode(pool.Name, ColourUtilities.ChooseColour(3), Color.Black, location);

                foreach (CarbonFlow cFlow in pool.FindAllChildren <CarbonFlow>())
                {
                    foreach (string destinationName in cFlow.destinationNames)
                    {
                        string destName = destinationName;
                        if (destName == null)
                        {
                            destName           = "Atmosphere";
                            needAtmosphereNode = true;
                        }

                        location = default(Point);
                        Arc oldArc;
                        if (oldGraph != null && pool.Name != null && (oldArc = oldGraph.Arcs.Find(f => f.SourceName == pool.Name && f.DestinationName == destName)) != null)
                        {
                            location = oldArc.Location;
                        }

                        directedGraphInfo.AddArc(null, pool.Name, destName, Color.Black, location);
                    }
                }
            }

            foreach (Solute solute in this.FindAllChildren <Solute>())
            {
                directedGraphInfo.AddNode(solute.Name, ColourUtilities.ChooseColour(2), Color.Black);
                foreach (NFlow nitrogenFlow in solute.FindAllChildren <NFlow>())
                {
                    string destName = nitrogenFlow.destinationName;
                    if (destName == null)
                    {
                        destName           = "Atmosphere";
                        needAtmosphereNode = true;
                    }
                    directedGraphInfo.AddArc(null, nitrogenFlow.sourceName, destName, Color.Black);
                }
            }

            if (needAtmosphereNode)
            {
                directedGraphInfo.AddTransparentNode("Atmosphere");
            }


            directedGraphInfo.End();
        }
Ejemplo n.º 51
0
 public static Dictionary <Guid, IntegrityCheck>?EntityIntegrityCheck(DirectedGraph <Modifiable> graph)
 {
     return(graph.OfType <ModifiableEntity>()
            .ToDictionaryOrNull(a => a.temporalId, a => a.IntegrityCheck()));
 }
Ejemplo n.º 52
0
    public void Load()
    {
        DirectedGraph graph = (DirectedGraph)GraphUtility.LoadDebugGraph();

        constructor.CreateGraph(graph);
    }
Ejemplo n.º 53
0
 public static DirectedGraph <Modifiable> FromRootVirtual(Modifiable root)
 {
     return(DirectedGraph <Modifiable> .Generate(root, ModifyInspector.FullExploreVirtual, ReferenceEqualityComparer <Modifiable> .Default));
 }
Ejemplo n.º 54
0
 public GraphIterator(GraphTraversals the_traversal_method, Vertex <T> the_parent_root, DirectedGraph <T> the_parent)
 {
     /*my_traversal_method = the_traversal_method;
      * my_parent = the_parent;
      *
      * //prepare stack for traversal
      * my_elements = new Stack<BinaryNode<T>>(my_parent.size());
      *
      * //add the first element if it is there
      * if (my_parent.my_root != null)
      * {
      *  my_elements.push(my_parent.my_root);
      * }*/
 }
 public DijkstraAlgorithm(DirectedGraph graph) : base(graph)
 {
 }
Ejemplo n.º 56
0
 public static void SetValidationErrors(DirectedGraph <Modifiable> directedGraph, IntegrityCheckException e)
 {
     SetValidationErrors(directedGraph, e.Errors);
 }
Ejemplo n.º 57
0
 public void Create()
 {
     constructor.CreateGraph(DirectedGraph.CreateGraphWithStartNode());
 }
Ejemplo n.º 58
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PackageUpgradeVisualizer"/> class.
 /// </summary>
 /// <param name="directedGraph">The directed graph used to visualize package upgrades.</param>
 /// <exception cref="ArgumentNullException"><paramref name="directedGraph"/> is <c>null</c>.</exception>
 public PackageUpgradeVisualizer(DirectedGraph directedGraph)
     : this(directedGraph, new PackageUpgradePalette())
 {
 }
Ejemplo n.º 59
0
        /// <summary>
        /// Gets the directed graph from <see cref="folderNode"/>
        /// </summary>
        /// <param name="folder">The folder.</param>
        /// <param name="doFolderDescription">if set to <c>true</c> [do folder description].</param>
        /// <param name="doFileEntries">if set to <c>true</c> [do file entries].</param>
        /// <param name="doFileDescriptions">if set to <c>true</c> [do file descriptions].</param>
        /// <param name="limit">The limit.</param>
        /// <returns></returns>
        public static DirectedGraph GetDirectedGraph(this folderNode folder, Boolean doFolderDescription, Boolean doFileEntries, Boolean doFileDescriptions, Int32 limit = 100)
        {
            DirectedGraph output = new DirectedGraph();

            output.Title = folder.name;

            output.Categories.AddOrGetCategory(CAT_FOLDERNODE, "Folder", "").Background = Color.Orange.ColorToHex();                    //.toHexColor();
            output.Categories.AddOrGetCategory(CAT_FOLDERNODEDESC, "Folder Description", "").Background = Color.LightGray.ColorToHex(); //.toHexColor();
            output.Categories.AddOrGetCategory(CAT_FILE, "File", "").Background = Color.LightSteelBlue.ColorToHex();                    //.toHexColor();
            output.Categories.AddOrGetCategory(CAT_FILEDESC, "File Description", "").Background = Color.LightGray.ColorToHex();         //.toHexColor();

            List <folderNode> nextSet = new List <folderNode>();

            nextSet.Add(folder);
            Int32 i = 0;

            while (nextSet.Any())
            {
                i++;
                List <folderNode> newNextSet = new List <folderNode>();

                foreach (folderNode parent in nextSet)
                {
                    var parentNode = output.Nodes.AddNode(parent.path, parent.name);
                    parentNode.Category = CAT_FOLDERNODE;

                    if (parent.parent != null)
                    {
                        folderNode parentFolder = parent.parent as folderNode;
                        Link       l            = new Link(parentFolder.path, parentNode.Id, true);
                        l.Stroke = Color.OrangeRed.ColorToHex(); //.toHexColor();
                        output.Links.Add(l);
                    }

                    foreach (var pair in parent)
                    {
                        newNextSet.AddUnique(pair.Value);
                    }

                    if (doFolderDescription)
                    {
                        if (!parent.description.isNullOrEmpty())
                        {
                            Node descNode = output.Nodes.AddNode(parent.path + "_DESC", parent.description);
                            descNode.Category = CAT_FOLDERNODEDESC;
                            output.Links.AddLink(parentNode, descNode, "About").StrokeDashArray = "2,5,2,5";
                        }
                    }

                    if (doFileEntries)
                    {
                        foreach (var f in parent.AdditionalFileEntries)
                        {
                            Node fileNode = output.Nodes.AddNode(parent.path + f.Key, f.Value.description);
                            fileNode.Category = CAT_FILE;
                            var fileLink = output.Links.AddLink(parentNode, fileNode, f.Value.filename);
                            fileLink.StrokeDashArray = "2,2,5,2";
                            fileLink.Stroke          = Color.LightGray.ColorToHex(); //.toHexColor();

                            //if (doFileDescriptions)
                            //{
                            //    Node fileInfoNode = output.Nodes.AddNode(parent.path + f.Key + "_DESC", );
                            //    fileInfoNode.Category = CAT_FILEDESC;
                            //    var fileInfoLink = output.Links.AddLink(fileNode, fileInfoNode, "");
                            //    fileLink.StrokeDashArray = "2,2,5,2";
                            //    fileLink.Stroke = Color.LightGray.toHexColor();
                            //}
                        }
                    }
                }

                if (i > limit)
                {
                    break;
                }
                nextSet = newNextSet;
            }

            return(output);
        }
Ejemplo n.º 60
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PackageUpgradeVisualizer"/> class.
 /// </summary>
 /// <param name="directedGraph">The directed graph used to visualize package upgrades.</param>
 /// <param name="palette">The color palette to color nodes and links.</param>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="directedGraph"/> is <c>null</c>.
 /// - or -
 /// <paramref name="palette"/> is <c>null</c>.
 /// </exception>
 public PackageUpgradeVisualizer(DirectedGraph directedGraph, PackageUpgradePalette palette)
 {
     _directedGraph = directedGraph ?? throw new ArgumentNullException(nameof(directedGraph));
     _palette       = palette ?? throw new ArgumentNullException(nameof(palette));
 }