Exemplo n.º 1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="node"></param>
        protected void RemoveNode(NodeVertex node)
        {
            if (graph.ContainsVertex(node))
            {
                // TODO Need a better way to removing incoming edges
                var edgesToRemove = AssociatedObject.EdgesList.Values.Where(x => ((NodeEdge)x.Edge).Source == node || ((NodeEdge)x.Edge).Target == node).ToList();
                foreach (var control in edgesToRemove)
                {
                    var edge = (NodeEdge)control.Edge;
                    graph.RemoveEdge(edge);
                    AssociatedObject.RemoveEdge(edge);
                }

                // Disconnect control
                VertexControl vertexControl;
                if (AssociatedObject.VertexList.TryGetValue(node, out vertexControl))
                {
                    node.DisconnectControl(vertexControl);
                }

                // Then remove the vertex
                graph.RemoveVertex(node);
                AssociatedObject.RemoveVertex(node);
            }
        }
Exemplo n.º 2
0
 private bool check()
 {
     if (_graph.EdgeCount == 1)
     {
         Path.AddEdge(_graph.Edges.First());
         if (Path.IsDirectedAcyclicGraph())
         {
             Path.RemoveEdge(_graph.Edges.First());
             return(false);
         }
         return(true);
     }
     return(false);
 }
Exemplo n.º 3
0
        // Original Source: https://www.youtube.com/watch?v=VTbuvkaPGxE
        private void RefreshGraph()
        {
            while (_graphToVisualize.Edges.Count() > 0)
            {
                _graphToVisualize.RemoveEdge(_graphToVisualize.Edges.First());
            }

            _graphToVisualize.AddVertex("SinglyLinkedList");
            _graphToVisualize.AddVertex("null");
            foreach (SinglyLinkedListNode <string> node in SinglyLinkedListNode <string> .allNodes)
            {
                _graphToVisualize.AddVertex(node.ToString());
            }

            foreach (SinglyLinkedListNode <string> node in SinglyLinkedListNode <string> .allNodes)
            {
                if (node.Next == null)
                {
                    _graphToVisualize.AddEdge(new Edge <object>(node.ToString(), "null"));
                }
                else
                {
                    _graphToVisualize.AddEdge(new Edge <object>(node.ToString(), node.Next.ToString()));
                }
            }
            try
            {
                _graphToVisualize.AddEdge(new Edge <object>("SinglyLinkedList", linkedList.First() ?? "null"));
            }
            catch (NotImplementedException)
            {
                _graphToVisualize.AddEdge(new Edge <object>("SinglyLinkedList", "null"));
            }
        }
Exemplo n.º 4
0
        private static void ApplyStudentTransformation(BidirectionalGraph <Resource, AssociationViewEdge> resourceGraph)
        {
            var resources = resourceGraph.Vertices.ToList();

            var studentResource = resources.FirstOrDefault(x => x.FullName == new FullName(EdFiConventions.PhysicalSchemaName, "Student"));
            var studentSchoolAssociationResource = resources.FirstOrDefault(x => x.FullName == new FullName(EdFiConventions.PhysicalSchemaName, "StudentSchoolAssociation"));

            // No student entity in the graph, nothing to do.
            if (studentResource == null)
            {
                return;
            }

            if (studentSchoolAssociationResource == null)
            {
                throw new EdFiSecurityException(
                          "Unable to transform resource load graph as StudentSchoolAssociation was not found in the graph.");
            }

            // Get direct student dependencies
            var studentDependencies = resourceGraph.OutEdges(studentResource)
                                      .Where(e => e.Target != studentSchoolAssociationResource)
                                      .ToList();

            // Add dependency on primaryRelationship path
            foreach (var directStudentDependency in studentDependencies)
            {
                // Re-point the edge to the primary relationships
                resourceGraph.RemoveEdge(directStudentDependency);
                resourceGraph.AddEdge(new AssociationViewEdge(studentSchoolAssociationResource, directStudentDependency.Target, directStudentDependency.AssociationView));
            }
        }
            /// <summary>
            /// Applies the changes in the current change to the given history object.
            /// </summary>
            /// <param name="historyObject">The object to which the changes should be applied.</param>
            /// <exception cref="ArgumentNullException">
            ///     Thrown if <paramref name="historyObject"/> is <see langword="null" />.
            /// </exception>
            public void ApplyTo(BidirectionalGraph <TVertex, TEdge> historyObject)
            {
                {
                    Lokad.Enforce.Argument(() => historyObject);
                }

                historyObject.RemoveEdge(m_Edge);
            }
 private void Button_Click_3(object sender, RoutedEventArgs e)
 {
     if (!edge1.Text.Equals(edge2.Text))
     {
         matrixAj[Convert.ToInt32(edge1.Text), Convert.ToInt32(edge2.Text)] = 0;
         matrixAj[Convert.ToInt32(edge2.Text), Convert.ToInt32(edge1.Text)] = 0;
         try
         {
             IEdge <Object> myEdge;
             g.TryGetEdge(edge1.Text, edge2.Text, out myEdge);
             g.RemoveEdge(myEdge);
             g.TryGetEdge(edge2.Text, edge1.Text, out myEdge);
             g.RemoveEdge(myEdge);
         }
         catch
         {
             MessageBox.Show("Edge already deleted !!");
         }
     }
 }
        public bool RemoveEdge(TEdge edge)
        {
            bool edgeWasRemoved;

            lock (SyncRoot)
                edgeWasRemoved = Graph.RemoveEdge(edge);

            if (edgeWasRemoved)
            {
                EdgeRemoved?.Invoke(edge);
            }

            return(edgeWasRemoved);
        }
Exemplo n.º 8
0
        private void OnRemoveEdgeClick(object sender, RoutedEventArgs args)
        {
            if (_graph is null || _graph.EdgeCount < 1)
            {
                return;
            }

            var random = new Random(DateTime.Now.Millisecond);

            for (int i = 0; i < 10 && _graph.EdgeCount > 0; ++i)
            {
                int index = random.Next(_graph.EdgeCount);
                _graph.RemoveEdge(_graph.Edges.ElementAt(index));
            }
        }
        private void RedirectCommonDependencyToNexus(InternalEventVertex nexusVertex, IEnumerable <InternalEventVertex> depndents, InternalEventVertex commonDependency)
        {
            bool isAddedEdgeCritical = false;
            IEnumerable <InternalActivityEdge> edgesOutOfDependency;

            if (arrowGraph.TryGetOutEdges(commonDependency, out edgesOutOfDependency))
            {
                // Remove the edges between the dependency and the dependents of the nexus vertex
                var edgesToRemove = edgesOutOfDependency.Where(e => depndents.Contains(e.Target)).ToList();
                foreach (var edgeToRemove in edgesToRemove)
                {
                    arrowGraph.RemoveEdge(edgeToRemove);

                    // Replacing even one critical edge means the new edge would be also critical
                    isAddedEdgeCritical = isAddedEdgeCritical || edgeToRemove.IsCritical;
                }
            }
            // Else should never happen

            // This dependency should point at nexus vertex
            var edgeToAdd = new InternalActivityEdge(commonDependency, nexusVertex, isAddedEdgeCritical);

            arrowGraph.AddEdge(edgeToAdd);
        }
Exemplo n.º 10
0
        private void removeCycles()
        {
            List <TEdge> edgesToRemove = new List <TEdge>();

            foreach (var edge in _graph.Edges)
            {
                Path.AddEdge(edge);
                if (!Path.IsDirectedAcyclicGraph())
                {
                    edgesToRemove.Add(edge);
                    _weight.Remove(edge);
                }
                Path.RemoveEdge(edge);
            }
            edgesToRemove.ForEach(edge => _graph.RemoveEdge(edge));
        }
Exemplo n.º 11
0
        protected override void InternalCompute()
        {
            // Clone the visited graph
            transitiveReduction.AddVerticesAndEdgeRange(this.VisitedGraph.Edges);

            // Get the topological sorted graph
            var topoSort = this.VisitedGraph.TopologicalSort();

            // Iterate in topo order, track indirect ancestors and remove edges from them to the visited vertex
            var ancestorsOfVertices = new Dictionary <TVertex, HashSet <TVertex> >();

            foreach (var vertexId in this.VisitedGraph.TopologicalSort())
            {
                var thisVertexPredecessors = new List <TVertex>();
                var thisVertexAncestors    = new HashSet <TVertex>();
                ancestorsOfVertices[vertexId] = thisVertexAncestors;

                // Get indirect ancestors
                foreach (var inEdge in this.VisitedGraph.InEdges(vertexId))
                {
                    var predecessor = inEdge.Source;
                    thisVertexPredecessors.Add(predecessor);

                    // Add all the ancestors of the predeccessors
                    foreach (var ancestorId in ancestorsOfVertices[predecessor])
                    {
                        thisVertexAncestors.Add(ancestorId);
                    }
                }

                // Remove indirect edges
                foreach (var indirectAncestor in thisVertexAncestors)
                {
                    Edge foundIndirectEdge;
                    if (transitiveReduction.TryGetEdge(indirectAncestor, vertexId, out foundIndirectEdge))
                    {
                        transitiveReduction.RemoveEdge(foundIndirectEdge);
                    }
                }

                // Add predecessors to ancestors list
                foreach (var pred in thisVertexPredecessors)
                {
                    thisVertexAncestors.Add(pred);
                }
            }
        }
Exemplo n.º 12
0
        public bool Split(out Task <TVertex, TEdge> taskTake, out Task <TVertex, TEdge> taskDrop)
        {
            if (!CanSplit())
            {
                taskTake = null;
                taskDrop = null;
                return(false);
            }

            TEdge   edgeForSplit = ChooseEdgeForSplit();
            TVertex v1           = edgeForSplit.Source;
            TVertex v2           = edgeForSplit.Target;

            BidirectionalGraph <TVertex, TEdge> graphTake = _graph.Clone();
            var weightsTake = new Dictionary <EquatableEdge <TVertex>, double>(_weight);
            var reverseEdge = new EquatableEdge <TVertex>(edgeForSplit.Target, edgeForSplit.Source);

            weightsTake.Remove(reverseEdge);
            graphTake.RemoveEdgeIf(edge => edge.Equals(reverseEdge));

            foreach (TEdge outEdge in graphTake.OutEdges(v1))
            {
                weightsTake.Remove(outEdge);
            }

            foreach (TEdge inEdge in graphTake.InEdges(v2))
            {
                weightsTake.Remove(inEdge);
            }

            graphTake.ClearOutEdges(v1);
            graphTake.ClearInEdges(v2);
            var pathTake = new BidirectionalGraph <TVertex, TEdge>(Path);

            pathTake.AddEdge(edgeForSplit);
            taskTake = new Task <TVertex, TEdge>(graphTake, weightsTake, pathTake, MinCost, $"Take{edgeForSplit}");

            BidirectionalGraph <TVertex, TEdge> graphDrop = _graph.Clone();
            var weightsDrop = new Dictionary <EquatableEdge <TVertex>, double>(_weight);

            weightsDrop.Remove(edgeForSplit);
            graphDrop.RemoveEdge(edgeForSplit);
            taskDrop = new Task <TVertex, TEdge>(graphDrop, weightsDrop, new BidirectionalGraph <TVertex, TEdge>(Path), MinCost, $"Drop{edgeForSplit}");

            return(true);
        }
Exemplo n.º 13
0
        private void RemoveEdge_Click(object sender, RoutedEventArgs e)
        {
            if (graph == null)
            {
                return;
            }

            if (graph.EdgeCount < 1)
            {
                return;
            }
            var rnd = new Random(DateTime.Now.Millisecond);

            for (int i = 0; i < 10 && graph.EdgeCount > 0; i++)
            {
                graph.RemoveEdge(graph.Edges.ElementAt(rnd.Next(graph.EdgeCount)));
            }
        }
Exemplo n.º 14
0
        private static void ApplyStaffTransformation(BidirectionalGraph <Resource, AssociationViewEdge> resourceGraph)
        {
            var resources = resourceGraph.Vertices.ToList();

            var staffResource = resources.FirstOrDefault(x => x.FullName == new FullName(EdFiConventions.PhysicalSchemaName, "Staff"));

            var staffEdOrgEmployAssoc =
                resources.FirstOrDefault(
                    x => x.FullName == new FullName(EdFiConventions.PhysicalSchemaName, "StaffEducationOrganizationEmploymentAssociation"));

            var staffEdOrgAssignAssoc =
                resources.FirstOrDefault(
                    x => x.FullName == new FullName(EdFiConventions.PhysicalSchemaName, "StaffEducationOrganizationAssignmentAssociation"));

            // No staff entity in the graph, nothing to do.
            if (staffResource == null)
            {
                return;
            }

            if (staffEdOrgEmployAssoc == null && staffEdOrgAssignAssoc == null)
            {
                throw new EdFiSecurityException(
                          "Unable to transform resource load graph since StaffEducationOrganizationAssignmentAssociation and" +
                          " StaffEducationOrganizationEmploymentAssociation were not found in the graph.");
            }

            // Get direct staff dependencies
            var directStaffDependencies = resourceGraph.OutEdges(staffResource)
                                          .Where(e => e.Target != staffEdOrgEmployAssoc && e.Target != staffEdOrgAssignAssoc)
                                          .ToList();

            // Add dependency on primaryRelationship path
            foreach (var directStaffDependency in directStaffDependencies)
            {
                // Re-point the edge to the primary relationships
                resourceGraph.RemoveEdge(directStaffDependency);

                resourceGraph.AddEdge(new AssociationViewEdge(staffEdOrgAssignAssoc, directStaffDependency.Target, directStaffDependency.AssociationView));
                resourceGraph.AddEdge(new AssociationViewEdge(staffEdOrgEmployAssoc, directStaffDependency.Target, directStaffDependency.AssociationView));
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Adds a new coercion rule. Trys to avoid cyclic implicit casts chains.
        /// </summary>
        /// <typeparam name="TOriginalType"></typeparam>
        /// <typeparam name="TCastingType"></typeparam>
        /// <param name="kind"></param>
        /// <param name="cast"></param>
        public void AddCoercionRule <TOriginalType, TCastingType>(CoercionKind kind, Func <TOriginalType, TCastingType> cast)
        {
            var original = typeof(TOriginalType);
            var casting  = typeof(TCastingType);

            if (GetTypeByNative(original) == null)
            {
                throw new UnknownTypeException(original);
            }
            if (GetTypeByNative(casting) == null)
            {
                throw new UnknownTypeException(casting);
            }
            var rule = new CoercionRule(kind, original, casting, a => cast((TOriginalType)a));

            if (allCoercionRules.TryGetEdge(original, casting, out TaggedEdge <Type, CoercionRule> existingEdge))
            {
                throw new InvalidOperationException("Such a rule does already exist!");
            }
            var edge = new TaggedEdge <System.Type, CoercionRule>(original, casting, rule);

            if (kind == CoercionKind.Implicit)
            {
                implicitCoercionRules.AddVertex(original);
                implicitCoercionRules.AddVertex(casting);
                implicitCoercionRules.AddEdge(edge);
                if (implicitCoercionRules.StronglyConnectedComponents(out IDictionary <Type, int> components) != implicitCoercionRules.Vertices.Count())
                {
                    implicitCoercionRules.RemoveEdge(edge);
                    throw new InvalidOperationException("This action would create an implicit conversion cycle!");
                }
            }
            allCoercionRules.AddVertex(original);
            allCoercionRules.AddVertex(casting);
            allCoercionRules.AddEdge(edge);
            Debug.WriteLine($"- added coercion rule from '{original.Name}' to '{casting.Name}'");
        }
Exemplo n.º 16
0
 public void RemoveEdge(string Source, string Target)
 {
     graph.RemoveEdge(new Edge <string>(Source, Target));
 }
        /// <summary>
        /// Attempts to break cycles in the graph by removing the deepest remove edge, as defined
        /// by the supplied predicate function.
        /// </summary>
        /// <param name="graph">The bidirectional graph to be processed.</param>
        /// <param name="isRemovable">A function indicating whether or not a particular edge can be removed (i.e. is a "soft" dependency).</param>
        /// <typeparam name="TVertex">The <see cref="Type" /> of the vertices of the graph.</typeparam>
        /// <typeparam name="TEdge">The <see cref="Type" /> of the edges of the graph.</typeparam>
        /// <returns>The list of edges that were removed to break the cycle(s).</returns>
        /// <exception cref="NonAcyclicGraphException">Occurs if one or more of the cycles present in the graph cannot be broken by removing one of its edges.</exception>
        public static IReadOnlyList <TEdge> BreakCycles <TVertex, TEdge>(this BidirectionalGraph <TVertex, TEdge> graph, Func <TEdge, bool> isRemovable)
            where TEdge : IEdge <TVertex>
        {
            var removedEdges = new List <TEdge>();

            // Get cyclical dependencies found in the graph
            var cycles = graph.GetCycles();

            // Break circular dependencies
            foreach (var cycle in cycles)
            {
                // Last element of Path repeats first element (so ignore duplicate)
                var distinctPathVertices = cycle.Path.Take(cycle.Path.Count - 1).ToArray();

                var sacrificialDependency = distinctPathVertices
                                            .Select(
                    (e, i) =>
                {
                    // Get the next entity in the path (circling around to the first entity on the last item)
                    var dependentVertex = distinctPathVertices[(i + 1) % distinctPathVertices.Length];

                    return(new
                    {
                        DependentVertex = dependentVertex,
                        CycleEdges = graph.InEdges(dependentVertex).Where(IsCycleEdge)
                    });
                })
                                            .Reverse()
                                            .FirstOrDefault(x => x.CycleEdges.All(isRemovable));

                if (sacrificialDependency == null)
                {
                    graph.ValidateGraph();

                    // Should never get here in this situation, but throw an exception to satisfy code analysis warnings
                    throw new NonAcyclicGraphException();
                }

                // Remove the chosen graph edge(s) to break the cyclical dependency
                foreach (TEdge edge in sacrificialDependency.CycleEdges.ToArray())
                {
                    if (_logger.IsDebugEnabled)
                    {
                        _logger.Debug($"Edge '{edge.ToString()}' removed to prevent the following cycle: {string.Join(" --> ", cycle.Path.Select(x => x.ToString()))}");
                    }

                    graph.RemoveEdge(edge);
                    removedEdges.Add(edge);
                }

                bool IsCycleEdge(TEdge edge) => distinctPathVertices.Contains(edge.Source);
            }

            if (_logger.IsDebugEnabled)
            {
                _logger.Debug($@"The following edges were removed from the graph to prevent cycles:
{string.Join(Environment.NewLine, removedEdges.Select(x => x.ToString()))}");
            }

            return(removedEdges);
        }