예제 #1
0
        public void InEdges_Throws()
        {
            var graph1         = new BidirectionalGraph <EquatableTestVertex, Edge <EquatableTestVertex> >();
            var filteredGraph1 = new FilteredBidirectionalGraph
                                 <
                EquatableTestVertex,
                Edge <EquatableTestVertex>,
                BidirectionalGraph <EquatableTestVertex, Edge <EquatableTestVertex> >
                                 >(
                graph1,
                _ => true,
                _ => true);

            InEdges_NullThrows_Test(filteredGraph1);
            InEdges_Throws_Test(filteredGraph1);

            var graph2         = new BidirectionalGraph <int, Edge <int> >();
            var filteredGraph2 = new FilteredBidirectionalGraph <int, Edge <int>, BidirectionalGraph <int, Edge <int> > >(
                graph2,
                vertex => vertex < 4,
                _ => true);

            graph2.AddVertexRange(new[] { 1, 2, 3, 4, 5 });
            // ReSharper disable ReturnValueOfPureMethodIsNotUsed
            Assert.Throws <VertexNotFoundException>(() => filteredGraph2.InEdges(4));
            Assert.Throws <VertexNotFoundException>(() => filteredGraph2.InEdges(5));
            // ReSharper restore ReturnValueOfPureMethodIsNotUsed
        }
예제 #2
0
        private void GenerateSpanningTree()
        {
            _spanningTree = new BidirectionalGraph <TVertex, Edge <TVertex> >(false);
            _spanningTree.AddVertexRange(VisitedGraph.Vertices);
            IQueue <TVertex> vb = new QuikGraph.Collections.Queue <TVertex>();

            vb.Enqueue(VisitedGraph.Vertices.OrderBy(v => VisitedGraph.InDegree(v)).First());

            switch (Parameters.SpanningTreeGeneration)
            {
            case SpanningTreeGeneration.BFS:
                var bfs = new BreadthFirstSearchAlgorithm <TVertex, TEdge>(VisitedGraph, vb, new Dictionary <TVertex, GraphColor>());
                bfs.TreeEdge += e =>
                {
                    ThrowIfCancellationRequested();
                    _spanningTree.AddEdge(new Edge <TVertex>(e.Source, e.Target));
                };
                bfs.Compute();
                break;

            case SpanningTreeGeneration.DFS:
                var dfs = new DepthFirstSearchAlgorithm <TVertex, TEdge>(VisitedGraph);
                dfs.TreeEdge += e =>
                {
                    ThrowIfCancellationRequested();
                    _spanningTree.AddEdge(new Edge <TVertex>(e.Source, e.Target));
                };
                dfs.Compute();
                break;
            }
        }
예제 #3
0
        public static BidirectionalGraph <TVertex, TEdge> CreateGraph <TVertex, TEdge, TEdgeData>(
            [NotNull, ItemNotNull] IEnumerable <TVertex> vertices,
            [NotNull, ItemNotNull] IEnumerable <TEdgeData> edgesData,
            [NotNull, InstantHandle] Func <TEdgeData, TEdge> edgeFactory,
            bool allowParallelEdges)
            where TEdge : IEdge <TVertex>
        {
            if (edgesData is null)
            {
                throw new ArgumentNullException(nameof(edgesData));
            }
            if (edgeFactory is null)
            {
                throw new ArgumentNullException(nameof(edgeFactory));
            }

            var graph = new BidirectionalGraph <TVertex, TEdge>(allowParallelEdges);

            graph.AddVertexRange(vertices);

            // Create the edges
            foreach (TEdgeData data in edgesData)
            {
                TEdge edge = edgeFactory(data);
                graph.AddEdge(edge);
            }

            return(graph);
        }
예제 #4
0
        private void runRelaxTest(BidirectionalGraph <MyVertex, MyEdge> g, List <MyVertex> verts, List <MyEdge> edges)
        {
            g.AddVertexRange(verts);
            g.AddEdgeRange(edges);

            var relaxer = new BasicForceRelaxer <MyVertex, MyEdge>(g);

            relaxer.Reset();
            engine.AddSimulator(new BasicSimulator(delegate
            {
                for (int i = 0; i < 10; i++)
                {
                    relaxer.Relax(TW.Graphics.Elapsed);
                }

                foreach (var n in g.Vertices)
                {
                    TW.Graphics.LineManager3D.AddCenteredBox(n.Position, 1, n.Color);
                }
                foreach (var e in g.Edges)
                {
                    TW.Graphics.LineManager3D.AddLine(e.Source.Position, e.Source.Color, e.Target.Position, e.Target.Color);
                }
            }));
        }
예제 #5
0
        public void CloneTest()
        {
            var g = new BidirectionalGraph<int, Edge<int>>();
            g.AddVertexRange(new int[3] {1, 2, 3});
            g.AddEdge(new Edge<int>(1, 2));
            g.AddEdge(new Edge<int>(2, 3));
            g.AddEdge(new Edge<int>(3, 1));

            Assert.AreEqual(3, g.VertexCount);
            Assert.AreEqual(3, g.EdgeCount);

            var h = g.Clone();

            Assert.AreEqual(3, h.VertexCount);
            Assert.AreEqual(3, h.EdgeCount);

            h.AddVertexRange(new int[4] { 10, 11, 12, 13 });
            h.AddEdge(new Edge<int>(10, 11));

            Assert.AreEqual(7, h.VertexCount);
            Assert.AreEqual(4, h.EdgeCount);

            var i = 0;
            foreach (var e in h.Edges)
                i++;

            Assert.AreEqual(4, i);

            Assert.AreEqual(3, g.VertexCount);
            Assert.AreEqual(3, g.EdgeCount);
        }
예제 #6
0
        // constructor from recently prepared BasicBlocksList
        public Graph(BasicBlocksList listBlocks)
        {
            CFG.AddVertexRange(listBlocks.Blocks);

            foreach (BasicBlock block in listBlocks.Blocks)
            {
                blockMap.Add(block.BlockId, block);
            }

            foreach (var block in listBlocks.Blocks)
            {
                foreach (var numIn in block.InputBlocks)
                {
                    CFG.AddEdge(new Edge <BasicBlock>(this.getBlockById(numIn), block));
                }
            }

            spanTree.AddVertexRange(listBlocks.Blocks);
            var visited = new Dictionary <BasicBlock, bool>();

            foreach (var v in spanTree.Vertices)
            {
                visited[v] = false;
            }
            int c = spanTree.Vertices.Count();

            dfs(blockMap[blockMap.Keys.First()], visited, ref c);
        }
예제 #7
0
        public static BidirectionalGraph <TVertex, Edge <TVertex> > CreateGraph <TVertex, TOtherEdge>(
            IEnumerable <TVertex> vertices,
            IEnumerable <TOtherEdge> edges,
            string sourcePropertyName,
            string targetPropertyName)
            where TVertex : class
        {
            var graph = new BidirectionalGraph <TVertex, Edge <TVertex> >();

            graph.AddVertexRange(vertices);

            //get the property infos
            System.Reflection.PropertyInfo spi = typeof(TOtherEdge).GetProperty(sourcePropertyName);
            System.Reflection.PropertyInfo tpi = typeof(TOtherEdge).GetProperty(targetPropertyName);

            //creating the new edges
            foreach (TOtherEdge oe in edges)
            {
                var edge = new Edge <TVertex>(
                    spi.GetValue(oe, null) as TVertex,
                    tpi.GetValue(oe, null) as TVertex);
                graph.AddEdge(edge);
            }

            return(graph);
        }
        protected virtual void GenerateSpanningTree(CancellationToken cancellationToken)
        {
            SpanningTree = new BidirectionalGraph <TVertex, Edge <TVertex> >(false);
            SpanningTree.AddVertexRange(VisitedGraph.Vertices.OrderBy(v => VisitedGraph.InDegree(v)));

            EdgeAction <TVertex, TEdge> action = e =>
            {
                cancellationToken.ThrowIfCancellationRequested();
                SpanningTree.AddEdge(new Edge <TVertex>(e.Source, e.Target));
            };

            switch (Parameters.SpanningTreeGeneration)
            {
            case SpanningTreeGeneration.BFS:
                var bfsAlgo = new BreadthFirstSearchAlgorithm <TVertex, TEdge>(VisitedGraph);
                bfsAlgo.TreeEdge += action;
                bfsAlgo.Compute();
                break;

            case SpanningTreeGeneration.DFS:
                var dfsAlgo = new DepthFirstSearchAlgorithm <TVertex, TEdge>(VisitedGraph);
                dfsAlgo.TreeEdge           += action;
                dfsAlgo.ForwardOrCrossEdge += action;
                dfsAlgo.Compute();
                break;
            }
        }
예제 #9
0
        /// <summary>
        /// Sort a list of ColumnOrigins based on the references between the tables.
        /// </summary>
        /// <param name="columnOrigins">ColumnOrigins to sort</param>
        /// <returns>Sorted ColumnOrigins</returns>
        private List <ColumnOrigin> SortTablesFromReferences(List <ColumnOrigin> columnOrigins)
        {
            var referenceGraph = new BidirectionalGraph <Table, Edge <Table> >();

            var tables = columnOrigins.Select(c => c.Table).ToList();

            // List of tables that is used in the columnorigins
            HashSet <Table> relevantTables = new HashSet <Table>(tables);

            // Add vertices to graph
            referenceGraph.AddVertexRange(tables);

            // Add edges to graph
            // Edges are added between T1 and T2, iff. T1 has a linking reference to T2
            foreach (var table in tables)
            {
                foreach (var outRelation in table.Relations.Where(r => r.LinkTable == table && r.LinkTable != r.AnchorTable))
                {
                    if (!relevantTables.Contains(outRelation.AnchorTable))
                    {
                        continue;
                    }

                    referenceGraph.AddEdge(new Edge <Table>(outRelation.LinkTable, outRelation.AnchorTable));
                }
            }

            // Topological sort
            var topologicalSort = referenceGraph.TopologicalSort();
            // Associate tables with their ordering
            var tableOrderings = topologicalSort.Select((table, index) => new KeyValuePair <Table, int>(table, index)).ToDictionary(pair => pair.Key, pair => pair.Value);

            // Order column origins by the ordering in tableOrderings
            return(columnOrigins.OrderBy(origin => tableOrderings[origin.Table]).ToList());
        }
예제 #10
0
        public void TransitiveClosure_IsolatedVertices()
        {
            const string vertex1 = "/test";
            const string vertex2 = "/test/123";
            const string vertex3 = "/test/456";
            const string vertex4 = "/test/notlinked";
            var          edge12  = new EquatableEdge <string>(vertex1, vertex2);
            var          edge23  = new EquatableEdge <string>(vertex2, vertex3);

            var graph = new BidirectionalGraph <string, EquatableEdge <string> >();

            graph.AddVertexRange(new[] { vertex1, vertex2, vertex3, vertex4 });
            graph.AddEdgeRange(new[] { edge12, edge23 });

            BidirectionalGraph <string, EquatableEdge <string> > result = graph.ComputeTransitiveClosure((u, v) => new EquatableEdge <string>(u, v));

            AssertHasVertices(result, new[] { vertex1, vertex2, vertex3, vertex4 });
            AssertHasEdges(
                result,
                new[]
            {
                edge12,
                new EquatableEdge <string>(vertex1, vertex3),
                edge23
            });
        }
예제 #11
0
        private void OnClickMenuOpen(object sender, RoutedEventArgs e)
        {
            var newGraph = new BidirectionalGraph <object, IEdge <object> >();
            var filePath = SimpleFileDialog.Show();

            if (filePath == null)
            {
                return;
            }

            try
            {
                _fileTool = new FileTool(filePath);
                _fileTool.OpenFile();
                newGraph.AddVertexRange(_fileTool.GenerateVertexes());
                newGraph.AddEdgeRange(_fileTool.GenerateEdges());
                MainGraphLayout.Graph = newGraph;
            }
            catch (KeyNotFoundException)
            {
                ShowError("Key for edge not found!");
            }
            catch (Exception)
            {
                ShowError("Unknown exception!");
            }
        }
        public void Clone()
        {
            var graph = new BidirectionalGraph <int, Edge <int> >();

            graph.AddVertexRange(new[] { 1, 2, 3 });
            graph.AddEdge(new Edge <int>(1, 2));
            graph.AddEdge(new Edge <int>(2, 3));
            graph.AddEdge(new Edge <int>(3, 1));

            Assert.AreEqual(3, graph.VertexCount);
            Assert.AreEqual(3, graph.EdgeCount);

            var clonedGraph = graph.Clone();

            Assert.AreEqual(3, clonedGraph.VertexCount);
            Assert.AreEqual(3, clonedGraph.EdgeCount);

            clonedGraph.AddVertexRange(new[] { 10, 11, 12, 13 });
            clonedGraph.AddEdge(new Edge <int>(10, 11));

            Assert.AreEqual(7, clonedGraph.VertexCount);
            Assert.AreEqual(4, clonedGraph.EdgeCount);

            int edgeCount = clonedGraph.Edges.Count();

            Assert.AreEqual(4, edgeCount);

            Assert.AreEqual(3, graph.VertexCount);
            Assert.AreEqual(3, graph.EdgeCount);
        }
예제 #13
0
        private static TGraph GenerateGroupGraph(ICollection <TVertex> vertices, ICollection <TEdge> edges)
        {
            var graph = new BidirectionalGraph <TVertex, TEdge>(true, vertices.Count, edges.Count);

            graph.AddVertexRange(vertices);
            graph.AddEdgeRange(edges);
            return((TGraph)(object)graph);
        }
예제 #14
0
        public TSP(TGraph visitedGraph, Func <TEdge, double> weights)
            : base(null, visitedGraph, weights, DistanceRelaxers.ShortestDistance)
        {
            BidirectionalGraph <TVertex, TEdge> path = new BidirectionalGraph <TVertex, TEdge>();

            path.AddVertexRange(visitedGraph.Vertices);
            taskManager.AddTask(new Task <TVertex, TEdge>(visitedGraph, buildWeightsDict(visitedGraph, weights), path, 0));
        }
예제 #15
0
        private static BidirectionalGraph <object, IEdge <object> > TypeGraph(PreparedMetricsReport metrics)
        {
            var graph = new BidirectionalGraph <object, IEdge <object> >(false);

            graph.AddVertexRange(metrics.Report.TypeGraph.Vertices.Select(v => v.FullName));
            graph.AddEdgeRange(metrics.Report.TypeGraph.Edges.Select(e => new Edge <object>(e.Item1.FullName, e.Item2.FullName)));
            return(graph);
        }
        public void ComputeWithRootAndTarget()
        {
            var graph = new BidirectionalGraph <int, Edge <int> >();

            graph.AddVertexRange(new[] { 0, 1 });
            var algorithm = new BestFirstFrontierSearchAlgorithm <int, Edge <int> >(graph, _ => 1.0, DistanceRelaxers.EdgeShortestDistance);

            ComputeWithRootAndTarget_Test(algorithm);
        }
예제 #17
0
        // Constructor from list of blocks
        public CFGraph(List <IBaseBlock> blocks)
        {
            Blocks    = blocks;
            EdgeTypes = new EdgeTypes();

            // First step - construct
            List <CFGNode> cfg_nodes = new List <CFGNode>(blocks.Count);

            for (int i = 0; i < blocks.Count; i++)
            {
                cfg_nodes.Add(new CFGNode(blocks[i]));
            }

            // Second step - make connections
            for (int i = 0; i < cfg_nodes.Count; i++)
            {
                var lastOp = cfg_nodes[i].Value.Enumerate().Last();
                if (i != cfg_nodes.Count - 1 &&
                    lastOp.Operation != LinearRepr.Values.Operation.Goto)
                {
                    cfg_nodes[i].SetDirectChild(cfg_nodes[i + 1]);
                }

                if (lastOp.Operation == LinearRepr.Values.Operation.Goto ||
                    lastOp.Operation == LinearRepr.Values.Operation.CondGoto)
                {
                    var     gotoBlock = blocks.FirstOrDefault(b => b.Enumerate().First().Label.Equals(lastOp.Destination));
                    CFGNode goto_node = cfg_nodes.Find(el => el.Value == gotoBlock);
                    cfg_nodes[i].SetGotoChild(goto_node);
                }
            }

            // Make IList and add as vertexes
            var base_cfg_nodes = cfg_nodes as IList <CFGNode> ?? cfg_nodes.ToList();

            graph.AddVertexRange(base_cfg_nodes);


            // Add edges now
            foreach (var node in base_cfg_nodes)
            {
                if (node.directChild != null)
                {
                    graph.AddEdge(new Edge <CFGNode>(node, node.directChild));
                }

                if (node.gotoNode != null)
                {
                    graph.AddEdge(new Edge <CFGNode>(node, node.gotoNode));
                }
            }

            ClassificateEdges();
            buildDominatorTree();

            naturalCycleGraph = new NaturalCycleGraph(this);
        }
        private void FillGraph()
        {
            var graph = new BidirectionalGraph <object, IEdge <object> >(false);

            graph.AddVertexRange(cycle.Namespaces);
            graph.AddEdgeRange(
                from namespaceInCycle in cycle.Namespaces
                from outOfNamespaceReference in cycle.TypesReferencingOutOf(namespaceInCycle)
                select new Edge <object>(namespaceInCycle, outOfNamespaceReference.TargetNamespace.Name));
            Graph = graph;
        }
예제 #19
0
        private void UpdateGraph(TypeCycle cycle)
        {
            var graph = new BidirectionalGraph <object, IEdge <object> >(false);

            graph.AddVertexRange(cycle.TypesInCycle.Select(t => t.DisplayName));
            graph.AddEdgeRange(
                from type in cycle.TypesInCycle
                from referencedType in type.ReferencedTypes
                select new Edge <object>(referencedType.Source, referencedType.Target));
            Graph = graph;
            Changed(() => Graph);
        }
        public void UnBalance_Throws()
        {
            var graph = new BidirectionalGraph <int, Edge <int> >();

            graph.AddVertexRange(new[] { 1, 2 });
            VertexFactory <int>            vertexFactory = () => 1;
            EdgeFactory <int, Edge <int> > edgeFactory   = (source, target) => new Edge <int>(source, target);

            var algorithm = new GraphBalancerAlgorithm <int, Edge <int> >(graph, 1, 2, vertexFactory, edgeFactory);

            Assert.Throws <InvalidOperationException>(() => algorithm.UnBalance());
        }
예제 #21
0
        public static BidirectionalGraph <TVertex, Edge <TVertex> > CreateGraph <TVertex, TEdgeData>(
            [NotNull, ItemNotNull] IEnumerable <TVertex> vertices,
            [NotNull, ItemNotNull] IEnumerable <TEdgeData> edgesData,
            [NotNull] string sourcePropertyName,
            [NotNull] string targetPropertyName)
        {
            if (edgesData is null)
            {
                throw new ArgumentNullException(nameof(edgesData));
            }

            var graph = new BidirectionalGraph <TVertex, Edge <TVertex> >();

            graph.AddVertexRange(vertices);

            // Get the property infos
            PropertyInfo sourceProperty = typeof(TEdgeData).GetProperty(sourcePropertyName)
                                          ?? throw new ArgumentException(
                                                    $"No source property named {sourcePropertyName} on type {typeof(TEdgeData).Name}.",
                                                    nameof(sourcePropertyName));

            if (!typeof(TVertex).IsAssignableFrom(sourceProperty.PropertyType))
            {
                throw new ArgumentException(
                          $"Type of property {sourcePropertyName} is not assignable to type {typeof(TVertex).Name}.",
                          nameof(sourcePropertyName));
            }

            PropertyInfo targetProperty = typeof(TEdgeData).GetProperty(targetPropertyName)
                                          ?? throw new ArgumentException(
                                                    $"No source property named {targetPropertyName} on type {typeof(TEdgeData).Name}.",
                                                    nameof(targetPropertyName));

            if (!typeof(TVertex).IsAssignableFrom(targetProperty.PropertyType))
            {
                throw new ArgumentException(
                          $"Type of property {targetPropertyName} is not assignable to type {typeof(TVertex).Name}.",
                          nameof(targetPropertyName));
            }

            // Create the new edges
            foreach (TEdgeData data in edgesData)
            {
                var edge = new Edge <TVertex>(
                    (TVertex)sourceProperty.GetValue(data, null),
                    (TVertex)targetProperty.GetValue(data, null));
                graph.AddEdge(edge);
            }

            return(graph);
        }
        public BidirectionalGraph <Resource.Resource, AssociationViewEdge> CreateResourceLoadGraph()
        {
            var resourceModel = _resourceModelProvider.GetResourceModel();

            var resourceGraph = new BidirectionalGraph <Resource.Resource, AssociationViewEdge>();

            var resources = resourceModel.GetAllResources()
                            .Where(r => !r.IsAbstract() && !r.FullName.IsEdFiSchoolYearType())
                            .ToArray();

            resourceGraph.AddVertexRange(resources);

            var edges = resources
                        // Abstract resources are already covered by their concrete resources in the model
                        .Where(res => !res.IsAbstract())
                        // Add edges for all references (incoming associations) and descriptor usages
                        .SelectMany(
                res =>

                // Add all incoming reference in the entire resource
                res.AllContainedReferences.SelectMany(AssociationViewEdge.CreateEdges)

                // Add direct descriptor associations
                .Concat(
                    res.AllContainedItemTypesOrSelf.SelectMany(
                        rc => rc.Properties.Where(p => p.IsDirectLookup)
                        .Select(
                            p => new AssociationViewEdge(
                                p.DescriptorResource,
                                p.Parent.ResourceRoot,
                                p.EntityProperty.IncomingAssociations.Single())))))

                        // Eliminate redundant edges
                        .Distinct(AssociationViewEdge.Comparer);

            resourceGraph.AddEdgeRange(edges.Where(e => !e.Source.FullName.IsEdFiSchoolYearType()));

            // Apply predefined graph transformations
            if (_graphTransformers.Any())
            {
                foreach (var graphTransformer in _graphTransformers)
                {
                    graphTransformer.Transform(resourceGraph);
                }
            }

            resourceGraph.BreakCycles(edge => edge.AssociationView.IsSoftDependency);

            return(resourceGraph);
        }
예제 #23
0
        public ActionGraph(IEngineConfiguration config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }
            var graph = new BidirectionalGraph <IAction, Edge <IAction> >(false);

            graph.AddVertexRange(config.Actions);
            var edges = config.Links.Select(x => new Edge <IAction>(x.From, x.To));

            graph.AddEdgeRange(edges);
            _graph = graph;
        }
예제 #24
0
        public static IImmutableBidirectionalGraph <TVertex, TVertexId, TEdge, TEdgeId> Create(
            IImmutableSet <TVertex> vertices,
            IImmutableSet <TEdge> edges,
            bool allowParallelEdges = false)
        {
            var vertexDictionary = vertices.ToImmutableDictionary(i => i.Id);
            var edgeDictionary   = edges.ToImmutableDictionary(i => i.Id);

            var graph = new BidirectionalGraph <TVertexId, VertexIdEdge <TVertexId, TEdgeId> >(allowParallelEdges);

            graph.AddVertexRange(vertexDictionary.Keys);
            graph.AddEdgeRange(edges.Select(ToVertexIdEdge));

            return(CreateInstance(vertexDictionary, edgeDictionary, graph));
        }
        public void SortAnotherOne()
        {
            var graph = new BidirectionalGraph <int, Edge <int> >();

            graph.AddVertexRange(new[] { 0, 1, 2, 3, 4 });
            graph.AddEdge(new Edge <int>(0, 1));
            graph.AddEdge(new Edge <int>(1, 2));
            graph.AddEdge(new Edge <int>(1, 3));
            graph.AddEdge(new Edge <int>(2, 3));
            graph.AddEdge(new Edge <int>(3, 4));

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

            algorithm.Compute();
        }
예제 #26
0
        /// <inheritdoc />
        protected override void Initialize()
        {
            base.Initialize();

            var path = new BidirectionalGraph <TVertex, TEdge>();

            path.AddVertexRange(VisitedGraph.Vertices);

            _taskManager.AddTask(
                new Task <TVertex, TEdge>(
                    VisitedGraph,
                    BuildWeightsDictionary(VisitedGraph, Weights),
                    path,
                    0));
        }
예제 #27
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TSP{TVertex,TEdge,TGraph}"/> class.
        /// </summary>
        /// <param name="visitedGraph">Graph to visit.</param>
        /// <param name="edgeWeights">Function that computes the weight for a given edge.</param>
        public TSP(
            [NotNull] TGraph visitedGraph,
            [NotNull] Func <TEdge, double> edgeWeights)
            : base(null, visitedGraph, edgeWeights, DistanceRelaxers.ShortestDistance)
        {
            var path = new BidirectionalGraph <TVertex, TEdge>();

            path.AddVertexRange(visitedGraph.Vertices);

            _taskManager.AddTask(
                new Task <TVertex, TEdge>(
                    visitedGraph,
                    BuildWeightsDictionary(visitedGraph, edgeWeights),
                    path,
                    0));
        }
예제 #28
0
        public void ComputeWithRootAndTarget()
        {
            const int start = 0;
            const int end   = 1;

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

            graph.AddVertexRange(new[] { start, end });
            var algorithm = new HoffmanPavleyRankedShortestPathAlgorithm <int, Edge <int> >(graph, edge => 1.0);

            Assert.DoesNotThrow(() => algorithm.Compute(start, end));
            Assert.IsTrue(algorithm.TryGetRootVertex(out int root));
            Assert.IsTrue(algorithm.TryGetTargetVertex(out int target));
            AssertEqual(start, root);
            AssertEqual(end, target);
        }
예제 #29
0
        public static BidirectionalGraph <TVertex, TEdge> CopyToBidirectionalGraph <TVertex, TEdge>(
            [NotNull] this IVertexAndEdgeListGraph <TVertex, TEdge> graph)
            where TEdge : IEdge <TVertex>
        {
            if (graph is null)
            {
                throw new ArgumentNullException(nameof(graph));
            }

            var newGraph = new BidirectionalGraph <TVertex, TEdge>();

            newGraph.AddVertexRange(graph.Vertices);
            newGraph.AddEdgeRange(graph.Edges);

            return(newGraph);
        }
        public static BidirectionalDepthFirstSearchAlgorithm <int, Edge <int> > CreateAlgorithmAndMaybeDoComputation(
            [NotNull] ContractScenario scenario)
        {
            var graph = new BidirectionalGraph <int, Edge <int> >();

            graph.AddVerticesAndEdgeRange(scenario.EdgesInGraph.Select(e => new Edge <int>(e.Source, e.Target)));
            graph.AddVertexRange(scenario.SingleVerticesInGraph);

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

            if (scenario.DoComputation)
            {
                algorithm.Compute(scenario.Root);
            }
            return(algorithm);
        }
        private void BuildTemporaryGraphs(
            [NotNull] ICollection <TVertex> side1,
            [NotNull] ICollection <TVertex> side2,
            [NotNull] out BidirectionalGraph <TVertex, Edge <TVertex> > graph1,
            [NotNull] out BidirectionalGraph <TVertex, TEdge> graph2)
        {
            //
            // The IN side
            //
            // on the IN side we should reverse the edges
            graph1 = new BidirectionalGraph <TVertex, Edge <TVertex> >();
            graph1.AddVertexRange(side1);
            foreach (TVertex vertex in side1)
            {
                VerticesInfos[vertex] = DoubleTreeVertexType.Backward;
                foreach (TEdge edge in VisitedGraph.InEdges(vertex))
                {
                    if (!side1.Contains(edge.Source) || edge.IsSelfEdge())
                    {
                        continue;
                    }

                    // Reverse the edge
                    graph1.AddEdge(new Edge <TVertex>(edge.Target, edge.Source));
                }
            }

            //
            // The OUT side
            //
            graph2 = new BidirectionalGraph <TVertex, TEdge>();
            graph2.AddVertexRange(side2);
            foreach (TVertex vertex in side2)
            {
                VerticesInfos[vertex] = DoubleTreeVertexType.Forward;
                foreach (TEdge edge in VisitedGraph.OutEdges(vertex))
                {
                    if (!side2.Contains(edge.Target) || edge.IsSelfEdge())
                    {
                        continue;
                    }

                    // Simply add the edge
                    graph2.AddEdge(edge);
                }
            }
        }
예제 #32
0
        // n - the number of vertices, f - min FAS, m - lower bound of the total number of arcs
        public BidirectionalGraph<int, Edge<int>> generate(int n, int f, int m)
        {
            Random rnd = new Random();
            List<int> p = Enumerable.Range(1, n).OrderBy(x => rnd.Next()).ToList<int>();
            int num_arcs = 0;
            int i, j;
            BidirectionalGraph<int, Edge<int>> graph = new BidirectionalGraph<int, Edge<int>>(false);
            graph.AddVertexRange(Enumerable.Range(1, n));

            bool fl = false;

            for (int d = 0; d < f; d++)
            {
                i = rnd.Next(2, n + 1);
                j = rnd.Next(1, i);
                if (i == j) { fl =true;}
                graph.AddEdge(new Edge<int>(p[i - 1], p[j - 1]));
                num_arcs++;
                while (j != i)
                {
                    int k = rnd.Next(j + 1, i + 1);
                    if (k == j) { fl =true;}
                    graph.AddEdge(new Edge<int>(p[j - 1], p[k - 1]));
                    num_arcs++;
                    j = k;
                }
            }

            if (num_arcs < m)
            {
                for (int d = 0; d < m - num_arcs; d++)
                {
                    i = rnd.Next(1, n);
                    j = rnd.Next(i + 1, n + 1);
                    if (i == j) { fl = true; }
                    graph.AddEdge(new Edge<int>(p[i - 1], p[j - 1]));
                }
            }
            return graph;
        }
        public BidirectionalGraph<AssemblyVertex, EquatableEdge<AssemblyVertex>> GenerateAssemblyReferenceGraph(IEnumerable<Regex> exclusions, ConcurrentBag<string> files, bool verbose)
        {
            if (verbose) Console.WriteLine("Processing {0} files.", files.Count);
            var edges = new ConcurrentBag<EquatableEdge<AssemblyVertex>>();
            var current = 0;
            var total = files.Count;
            Parallel.ForEach(files, file =>
                {
                    if (verbose) Console.Write("\rProcessing file: {0} of {1}", ++current, total);
                    AssemblyDefinition assembly;
                    try
                    {
                        assembly = AssemblyDefinition.ReadAssembly(new MemoryStream(_fileSystem.File.ReadAllBytes(file)));
                    }
                    catch (Exception)
                    {
                        if (verbose) Console.WriteLine("Skipping file as it does not appear to be a .Net assembly: {0}", file);
                        return;
                    }
                    foreach (var reference in assembly.MainModule.AssemblyReferences)
                    {
                        var exists = files.Any(f =>
                            {
                                var fileInfo = new FileInfo(f);
                                return reference.Name.Equals(fileInfo.Name.Replace(fileInfo.Extension, ""), StringComparison.OrdinalIgnoreCase);
                            });
                        if (!exists)
                        {
                            string assemblyPath;
                            exists = _gacResolver.AssemblyExists(reference.FullName, out assemblyPath);
                        }
                        var assemblyName = new AssemblyName(assembly.FullName);
                        edges.Add(CreateNewEdge(reference, exists, assemblyName, exclusions));
                    }
                });

            if (verbose) Console.WriteLine();
            if (verbose) Console.WriteLine("Creating Graph...");
            var graph = new BidirectionalGraph<AssemblyVertex, EquatableEdge<AssemblyVertex>>();
            var allVertices = edges.Select(e => e.Source).Concat(edges.Select(e => e.Target));
            var distinctVertices = allVertices.Distinct();
            graph.AddVertexRange(distinctVertices);
            graph.AddEdgeRange(edges);
            return graph;
        }
예제 #34
0
        public IBidirectionalGraph<GlobalCorrespondencesGraphVertex, GlobalCorrespondencesGraphEdge> GenerateGlobalCorrespondencesGraph(SyllablePosition syllablePosition, IEnumerable<Variety> varieties)
        {
            var varietiesSet = new HashSet<Variety>(varieties);
            CogProject project = _projectService.Project;
            var graph = new BidirectionalGraph<GlobalCorrespondencesGraphVertex, GlobalCorrespondencesGraphEdge>();
            var vertices = new Dictionary<object, GlobalSegmentVertex>();
            var edges = new Dictionary<UnorderedTuple<object, object>, GlobalCorrespondencesGraphEdge>();
            int maxFreq = 0;
            if (syllablePosition == SyllablePosition.Nucleus)
            {
                graph.AddVertexRange(new GlobalCorrespondencesGraphVertex[]
                    {
                        new VowelBacknessVertex(VowelBackness.Front),
                        new VowelBacknessVertex(VowelBackness.Central),
                        new VowelBacknessVertex(VowelBackness.Back),

                        new VowelHeightVertex(VowelHeight.Close),
                        new VowelHeightVertex(VowelHeight.CloseMid),
                        new VowelHeightVertex(VowelHeight.OpenMid),
                        new VowelHeightVertex(VowelHeight.Open)
                    });

                foreach (VarietyPair vp in project.VarietyPairs.Where(vp => varietiesSet.Contains(vp.Variety1) && varietiesSet.Contains(vp.Variety2)))
                {
                    foreach (SoundCorrespondence corr in vp.CognateSoundCorrespondencesByPosition[CogFeatureSystem.Nucleus])
                    {
                        VowelHeight height1, height2;
                        VowelBackness backness1, backness2;
                        bool round1, round2;
                        if (GetVowelInfo(corr.Segment1, out height1, out backness1, out round1) && GetVowelInfo(corr.Segment2, out height2, out backness2, out round2)
                            && (height1 != height2 || backness1 != backness2 || round1 != round2))
                        {
                            Tuple<VowelHeight, VowelBackness, bool> key1 = Tuple.Create(height1, backness1, round1);
                            GlobalSegmentVertex vertex1 = vertices.GetValue(key1, () => new GlobalVowelVertex(height1, backness1, round1));
                            vertex1.StrReps.Add(corr.Segment1.StrRep);
                            Tuple<VowelHeight, VowelBackness, bool> key2 = Tuple.Create(height2, backness2, round2);
                            GlobalSegmentVertex vertex2 = vertices.GetValue(key2, () => new GlobalVowelVertex(height2, backness2, round2));
                            vertex2.StrReps.Add(corr.Segment2.StrRep);
                            int freq = AddEdge(edges, corr, key1, vertex1, key2, vertex2);
                            maxFreq = Math.Max(freq, maxFreq);
                        }
                    }
                }
            }
            else
            {
                graph.AddVertexRange(new GlobalCorrespondencesGraphVertex[]
                    {
                        new ConsonantPlaceVertex(ConsonantPlace.Bilabial),
                        new ConsonantPlaceVertex(ConsonantPlace.Labiodental),
                        new ConsonantPlaceVertex(ConsonantPlace.Dental),
                        new ConsonantPlaceVertex(ConsonantPlace.Alveolar),
                        new ConsonantPlaceVertex(ConsonantPlace.Postalveolar),
                        new ConsonantPlaceVertex(ConsonantPlace.Retroflex),
                        new ConsonantPlaceVertex(ConsonantPlace.Palatal),
                        new ConsonantPlaceVertex(ConsonantPlace.Velar),
                        new ConsonantPlaceVertex(ConsonantPlace.Uvular),
                        new ConsonantPlaceVertex(ConsonantPlace.Pharyngeal),
                        new ConsonantPlaceVertex(ConsonantPlace.Glottal),

                        new ConsonantMannerVertex(ConsonantManner.Nasal),
                        new ConsonantMannerVertex(ConsonantManner.Stop),
                        new ConsonantMannerVertex(ConsonantManner.Affricate),
                        new ConsonantMannerVertex(ConsonantManner.Fricative),
                        new ConsonantMannerVertex(ConsonantManner.Approximant),
                        new ConsonantMannerVertex(ConsonantManner.FlapOrTap),
                        new ConsonantMannerVertex(ConsonantManner.Trill),
                        new ConsonantMannerVertex(ConsonantManner.LateralFricative),
                        new ConsonantMannerVertex(ConsonantManner.LateralApproximant)
                    });

                foreach (VarietyPair vp in project.VarietyPairs.Where(vp => varietiesSet.Contains(vp.Variety1) && varietiesSet.Contains(vp.Variety2)))
                {
                    SoundCorrespondenceCollection corrs = null;
                    switch (syllablePosition)
                    {
                        case SyllablePosition.Onset:
                            corrs = vp.CognateSoundCorrespondencesByPosition[CogFeatureSystem.Onset];
                            break;
                        case SyllablePosition.Coda:
                            corrs = vp.CognateSoundCorrespondencesByPosition[CogFeatureSystem.Coda];
                            break;
                    }
                    Debug.Assert(corrs != null);
                    foreach (SoundCorrespondence corr in corrs)
                    {
                        ConsonantPlace place1, place2;
                        ConsonantManner manner1, manner2;
                        bool voiced1, voiced2;
                        if (GetConsonantPosition(corr.Segment1, out place1, out manner1, out voiced1) && GetConsonantPosition(corr.Segment2, out place2, out manner2, out voiced2)
                            && (place1 != place2 || manner1 != manner2 || voiced1 != voiced2))
                        {
                            Tuple<ConsonantPlace, ConsonantManner, bool> key1 = Tuple.Create(place1, manner1, voiced1);
                            GlobalSegmentVertex vertex1 = vertices.GetValue(key1, () => new GlobalConsonantVertex(place1, manner1, voiced1));
                            vertex1.StrReps.Add(corr.Segment1.StrRep);
                            Tuple<ConsonantPlace, ConsonantManner, bool> key2 = Tuple.Create(place2, manner2, voiced2);
                            GlobalSegmentVertex vertex2 = vertices.GetValue(key2, () => new GlobalConsonantVertex(place2, manner2, voiced2));
                            vertex2.StrReps.Add(corr.Segment2.StrRep);

                            int freq = AddEdge(edges, corr, key1, vertex1, key2, vertex2);
                            maxFreq = Math.Max(freq, maxFreq);
                        }
                    }
                }
            }

            graph.AddVertexRange(vertices.Values);
            foreach (GlobalCorrespondencesGraphEdge edge in edges.Values)
            {
                edge.NormalizedFrequency = (double) edge.Frequency / maxFreq;
                graph.AddEdge(edge);
            }

            return graph;
        }
        public BidirectionalGraph<AssemblyVertex, EquatableEdge<AssemblyVertex>> GenerateAssemblyReferenceGraph(IEnumerable<Regex> exclusions, IEnumerable<Regex> ignoring, ConcurrentBag<string> files, bool verbose, bool checkAssemblyVersionMatch = true)
        {
            if (verbose) Console.WriteLine("Processing {0} files.", files.Count);
            var edges = new ConcurrentBag<EquatableEdge<AssemblyVertex>>();
            var vertices = new List<AssemblyVertex>();
            var ignoreList = ignoring.ToList();
            var excludeList = exclusions.ToList();

            var current = 0;
            var total = files.Count;
            Parallel.ForEach(files, file =>
                {
                    if (verbose) Console.Write("\rProcessing file: {0} of {1}", ++current, total);
                    AssemblyDefinition assembly;
                    try
                    {
                        assembly = AssemblyDefinition.ReadAssembly(new MemoryStream(_fileSystem.File.ReadAllBytes(file)));
                    }       
                    catch (Exception)
                    {
                        if (verbose) Console.WriteLine("Skipping file as it does not appear to be a .Net assembly: {0}", file);
                        return;
                    }
                    //We need to load the assembly to ensure that the assembly name is the same as the file name (to be exact)
                    if (ignoreList.Any(i => i.IsMatch(assembly.Name.Name.ToLowerInvariant())))
                    {
                        if (verbose) Console.WriteLine("Ignoring file: {0}", file);
                        return;
                    }

                    //Check for 32bitness on our source assembly
                    var required32Bit = Required32BitSet(assembly);
                    var assemblyName = new AssemblyName(assembly.FullName);
 
                    //If we dont have references (I know, unlikely right?)
                    if (!assembly.MainModule.AssemblyReferences.Any())
                    {
                        vertices.Add(CreateAssemblyVertex(assemblyName.FullName, assemblyName.Name, true, Required32BitSet(assembly), excludeList));
                        return;
                    }

                    //Otherwise create edges for them...
                    foreach (var reference in assembly.MainModule.AssemblyReferences)
                    {
                        var foundFileMatch = files.Any(f => CheckDependentFileMatchesManifest(f, reference, checkAssemblyVersionMatch, required32Bit));

                        if (!foundFileMatch)
                        {
                            foundFileMatch = _gacResolver.AssemblyExists(reference.FullName);
                        }
                        if (!ignoreList.Any(i => i.IsMatch(reference.Name.ToLowerInvariant())))
                            edges.Add(CreateNewEdge(reference, foundFileMatch, required32Bit, assemblyName, excludeList));
                        else
                            if (verbose) Console.WriteLine("Ignoring: {0}",assemblyName.Name);
                    }
                });

            if (verbose) Console.WriteLine();
            if (verbose) Console.WriteLine("Creating Graph...");
            var graph = new BidirectionalGraph<AssemblyVertex, EquatableEdge<AssemblyVertex>>();
            var allVertices = edges.Select(e => e.Source).Concat(edges.Select(e => e.Target)).Concat(vertices);
            var distinctVertices = allVertices.Distinct();
            graph.AddVertexRange(distinctVertices);
            graph.AddEdgeRange(edges);
            return graph;
        }