source: trunk/sources/HeuristicLab.Core/3.3/Collections/DirectedGraph/DirectedGraph.cs @ 11391

Last change on this file since 11391 was 11391, checked in by bburlacu, 8 years ago

#2223: Added RemoveVertices method.

File size: 7.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Drawing;
25using System.Linq;
26using HeuristicLab.Common;
27using HeuristicLab.Common.Resources;
28using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
29
30namespace HeuristicLab.Core {
31  [Item("DirectedGraph", "Generic class representing a directed graph with custom vertices and content")]
32  [StorableClass]
33  public class DirectedGraph : Item, IDirectedGraph {
34    public override Image ItemImage { get { return VSImageLibrary.Graph; } }
35
36    private HashSet<IVertex> vertices;
37    [Storable]
38    public IEnumerable<IVertex> Vertices {
39      get { return vertices; }
40      private set { vertices = new HashSet<IVertex>(value); }
41    }
42
43    private HashSet<IArc> arcs;
44    [Storable]
45    public IEnumerable<IArc> Arcs {
46      get { return arcs; }
47      private set { arcs = new HashSet<IArc>(value); }
48    }
49
50    public DirectedGraph() {
51      vertices = new HashSet<IVertex>();
52      arcs = new HashSet<IArc>();
53    }
54
55    protected DirectedGraph(DirectedGraph original, Cloner cloner)
56      : base(original, cloner) {
57      vertices = new HashSet<IVertex>(original.vertices.Select(cloner.Clone));
58      arcs = new HashSet<IArc>(original.arcs.Select(cloner.Clone));
59
60      // add the arcs to the newly cloned vertices
61      foreach (var arc in arcs) {
62        arc.Source.AddArc(arc);
63        arc.Target.AddArc(arc);
64      }
65    }
66
67    public override IDeepCloneable Clone(Cloner cloner) {
68      return new DirectedGraph(this, cloner);
69    }
70
71    [StorableConstructor]
72    protected DirectedGraph(bool serializing)
73      : base(serializing) {
74    }
75
76    [StorableHook(HookType.AfterDeserialization)]
77    private void AfterDeserialization() {
78      foreach (var vertex in vertices) {
79        vertex.ArcAdded += Vertex_ArcAdded;
80        vertex.ArcRemoved += Vertex_ArcRemoved;
81      }
82
83      foreach (var arc in arcs) {
84        var source = arc.Source;
85        var target = arc.Target;
86        source.AddArc(arc);
87        target.AddArc(arc);
88      }
89    }
90
91    public virtual void Clear() {
92      vertices.Clear();
93      arcs.Clear();
94    }
95
96    public virtual void AddVertex(IVertex vertex) {
97      if (!vertices.Contains(vertex) && vertex.Degree > 0)
98        throw new ArgumentException("New vertices cannot have any arcs.");
99
100      if (vertices.Add(vertex)) {
101        // register event handlers
102        vertex.ArcAdded += Vertex_ArcAdded;
103        vertex.ArcRemoved += Vertex_ArcRemoved;
104        OnVertedAdded(this, new EventArgs<IVertex>(vertex));
105      }
106    }
107
108    public virtual void AddVertices(IEnumerable<IVertex> vertexList) {
109      var hash = new HashSet<IVertex>(vertexList);
110      var arcList = vertexList.SelectMany(v => v.InArcs.Concat(v.OutArcs));
111      if (arcList.Any(x => !hash.Contains(x.Source) || !hash.Contains(x.Target)))
112        throw new ArgumentException("Vertex arcs are connected to vertices not in the graph.");
113      // if everything is in order, add the vertices to the directed graph
114      foreach (var v in vertexList)
115        vertices.Add(v);
116      foreach (var a in arcList)
117        arcs.Add(a);
118    }
119
120    public virtual void RemoveVertices(IEnumerable<IVertex> vertexList) {
121      foreach (var v in vertexList)
122        RemoveVertex(v);
123    }
124
125    public virtual void RemoveVertex(IVertex vertex) {
126      vertices.Remove(vertex);
127      // remove connections to/from the removed vertex
128      var arcList = vertex.InArcs.Concat(vertex.OutArcs).ToList(); // avoid invalid operation exception: "collection was modified" below
129      foreach (var arc in arcList)
130        RemoveArc(arc);
131      // deregister event handlers
132      vertex.ArcAdded -= Vertex_ArcAdded;
133      vertex.ArcRemoved -= Vertex_ArcRemoved;
134      OnVertexRemoved(this, new EventArgs<IVertex>(vertex));
135    }
136
137    public virtual IArc AddArc(IVertex source, IVertex target) {
138      var arc = new Arc(source, target);
139      AddArc(arc);
140      return arc;
141    }
142
143    public virtual void AddArc(IArc arc) {
144      var source = arc.Source;
145      var target = arc.Target;
146
147      if (!vertices.Contains(source) || !vertices.Contains(target))
148        throw new InvalidOperationException("Cannot add arc connecting vertices that are not in the graph.");
149
150      source.AddArc(arc);
151      target.AddArc(arc);
152      arcs.Add(arc);
153    }
154
155    public virtual void RemoveArc(IArc arc) {
156      arcs.Remove(arc);
157      var source = (Vertex)arc.Source;
158      var target = (Vertex)arc.Target;
159      source.RemoveArc(arc);
160      target.RemoveArc(arc);
161    }
162
163    protected virtual void Vertex_ArcAdded(object sender, EventArgs<IArc> args) {
164      // the ArcAdded event is fired by a vertex when an arc from/to another vertex is added to its list of connections
165      // because the arc is added in both directions by both the source and the target, this event will get fired twice here
166      var arc = args.Value;
167      if (arcs.Add(arc)) OnArcAdded(this, new EventArgs<IArc>(arc));
168    }
169
170    protected virtual void Vertex_ArcRemoved(object sender, EventArgs<IArc> args) {
171      var arc = args.Value;
172      if (arcs.Remove(arc)) OnArcRemoved(this, new EventArgs<IArc>(arc));
173    }
174
175    // events
176    public event EventHandler<EventArgs<IVertex>> VertexAdded;
177    protected virtual void OnVertedAdded(object sender, EventArgs<IVertex> args) {
178      var added = VertexAdded;
179      if (added != null)
180        added(sender, args);
181    }
182
183    public event EventHandler<EventArgs<IVertex>> VertexRemoved;
184    protected virtual void OnVertexRemoved(object sender, EventArgs<IVertex> args) {
185      var removed = VertexRemoved;
186      if (removed != null)
187        removed(sender, args);
188    }
189
190    public event EventHandler<EventArgs<IArc>> ArcAdded;
191    protected virtual void OnArcAdded(object sender, EventArgs<IArc> args) {
192      var added = ArcAdded;
193      if (added != null)
194        added(sender, args);
195    }
196
197    public event EventHandler<EventArgs<IArc>> ArcRemoved;
198    protected virtual void OnArcRemoved(object sender, EventArgs<IArc> args) {
199      var removed = ArcRemoved;
200      if (removed != null)
201        removed(sender, args);
202    }
203  }
204}
Note: See TracBrowser for help on using the repository browser.