Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2895_PushGP_GenealogyAnalysis/HeuristicLab.Problems.ProgramSynthesis.GenealogyAnalysis/GenealogyGraph/GenealogyGraph.cs @ 17035

Last change on this file since 17035 was 15771, checked in by bburlacu, 7 years ago

#2895: Add solution skeleton for PushGP with genealogy analysis.

File size: 8.6 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.IO;
26using System.Linq;
27using System.Text;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
32namespace HeuristicLab.Problems.ProgramSynthesis {
33  [StorableClass]
34  [Item("GenealogyGraph", "A class representing a genealogy graph")]
35  public class GenealogyGraph : DirectedGraph, IGenealogyGraph {
36    private Dictionary<object, IGenealogyGraphNode> contentMap;
37    private Dictionary<string, IGenealogyGraphNode> idMap;
38
39    private readonly Comparison<IArc<IDeepCloneable>> compareArcs = (a, b) => {
40      var da = a.Data;
41      var db = b.Data;
42
43      if ((da == null && db == null) || (da != null && db != null))
44        return 0;
45
46      if (da == null)
47        return -1;
48
49      return 1;
50    };
51
52    protected Dictionary<double, List<IGenealogyGraphNode>> ranks;
53    public IEnumerable<KeyValuePair<double, IEnumerable<IGenealogyGraphNode>>> Ranks {
54      get { return ranks.Select(x => new KeyValuePair<double, IEnumerable<IGenealogyGraphNode>>(x.Key, x.Value)); }
55    }
56    public IEnumerable<IGenealogyGraphNode> GetByRank(double rank) {
57      return ranks.ContainsKey(rank) ? ranks[rank] : Enumerable.Empty<IGenealogyGraphNode>();
58    }
59    protected GenealogyGraph(GenealogyGraph original, Cloner cloner)
60      : base(original, cloner) {
61      RebuildDictionaries();
62      // sort arcs so that in the case of crossover (child vertex with two parents)
63      // the arc which holds the fragment information is always last
64      foreach (var arcList in base.Vertices.Select(v => (List<IArc>)v.InArcs)) {
65        arcList.Sort((a, b) => compareArcs((IGenealogyGraphArc)a, (IGenealogyGraphArc)b));
66      }
67    }
68    public override IDeepCloneable Clone(Cloner cloner) {
69      return new GenealogyGraph(this, cloner);
70    }
71
72    [StorableConstructor]
73    protected GenealogyGraph(bool deserializing)
74      : base(deserializing) {
75    }
76    [StorableHook(HookType.AfterDeserialization)]
77    private void AfterDeserialization() {
78      RebuildDictionaries();
79      foreach (var arcList in base.Vertices.Select(v => (List<IArc>)v.InArcs)) {
80        arcList.Sort((a, b) => compareArcs((IGenealogyGraphArc)a, (IGenealogyGraphArc)b));
81      }
82    }
83    public GenealogyGraph() {
84      ranks = new Dictionary<double, List<IGenealogyGraphNode>>();
85      contentMap = new Dictionary<object, IGenealogyGraphNode>();
86      idMap = new Dictionary<string, IGenealogyGraphNode>();
87    }
88    new public IEnumerable<IGenealogyGraphNode> Vertices {
89      get { return base.Vertices.Select(x => (IGenealogyGraphNode)x); }
90    }
91    new public IEnumerable<IGenealogyGraphArc> Arcs {
92      get { return base.Arcs.Select(x => (IGenealogyGraphArc)x); }
93    }
94    public override IArc AddArc(IVertex source, IVertex target) {
95      var arc = new GenealogyGraphArc((IGenealogyGraphNode)source, (IGenealogyGraphNode)target);
96      base.AddArc(arc);
97      return arc;
98    }
99    public override void AddVertex(IVertex vertex) {
100      base.AddVertex(vertex);
101      var genealogyGraphNode = (IGenealogyGraphNode)vertex;
102
103      if (contentMap.ContainsKey(genealogyGraphNode.Data))
104        throw new InvalidOperationException("Duplicate content is not allowed in the genealogy graph.");
105      contentMap[genealogyGraphNode.Data] = genealogyGraphNode;
106
107      if (idMap.ContainsKey(genealogyGraphNode.Id))
108        throw new InvalidOperationException("Duplicate ids are not allowed in the genealogy graph.");
109      idMap[genealogyGraphNode.Id] = genealogyGraphNode;
110
111      if (!ranks.ContainsKey(genealogyGraphNode.Rank))
112        ranks[genealogyGraphNode.Rank] = new List<IGenealogyGraphNode>();
113      ranks[genealogyGraphNode.Rank].Add(genealogyGraphNode);
114    }
115    public override void RemoveVertex(IVertex vertex) {
116      var node = (IGenealogyGraphNode)vertex;
117      contentMap.Remove(node.Data);
118      idMap.Remove(node.Id);
119      if (ranks.ContainsKey(node.Rank)) {
120        ranks[node.Rank].Remove(node); // this call will be slow, use with caution
121        if (!ranks[node.Rank].Any())
122          ranks.Remove(node.Rank);
123      }
124      base.RemoveVertex(vertex);
125    }
126
127    public override void RemoveVertices(IEnumerable<IVertex> vertices) {
128      foreach (var v in vertices)
129        this.RemoveVertex(v);
130    }
131
132    public IGenealogyGraphNode GetByContent(object content) {
133      IGenealogyGraphNode result;
134      contentMap.TryGetValue(content, out result);
135      return result;
136    }
137    public IGenealogyGraphNode GetById(string id) {
138      IGenealogyGraphNode result;
139      idMap.TryGetValue(id, out result);
140      return result;
141    }
142    public bool Contains(object content) {
143      return contentMap.ContainsKey(content);
144    }
145    public event EventHandler GraphUpdated;
146    private void OnGraphUpdated(object sender, EventArgs args) {
147      var updated = GraphUpdated;
148      if (updated != null) updated(sender, args);
149    }
150    public override void Clear() {
151      base.Clear();
152      ranks.Clear();
153      contentMap.Clear();
154      idMap.Clear();
155    }
156    private void RebuildDictionaries() {
157      contentMap = new Dictionary<object, IGenealogyGraphNode>();
158      idMap = new Dictionary<string, IGenealogyGraphNode>();
159      ranks = new Dictionary<double, List<IGenealogyGraphNode>>();
160
161      foreach (var v in Vertices) {
162        contentMap[v.Data] = v;
163        idMap[v.Id] = v;
164        if (ranks.ContainsKey(v.Rank)) {
165          ranks[v.Rank].Add(v);
166        } else {
167          ranks[v.Rank] = new List<IGenealogyGraphNode> { v };
168        }
169      }
170    }
171    public void ExportDot(string path) {
172      var sb = new StringBuilder();
173      sb.AppendLine("graph fragmentgraph {");
174      foreach (var v in Vertices) {
175        double width = Math.Max(0.5, v.Degree);
176        sb.AppendLine("\"" + v.Id + "\"[shape=circle, style = filled, width = " + width + ", label = " + v.Rank + "\n" + String.Format("{0:00}", v.Quality) + ", fillcolor = \"" + ColorTranslator.ToHtml(GetColor(v)) + "\"]");
177      }
178      foreach (var a in Arcs) {
179        sb.AppendLine("\"" + a.Source.Id + "\" -- \"" + a.Target.Id + "\"");
180      }
181
182      sb.AppendLine("}");
183      File.WriteAllText(path, sb.ToString());
184    }
185    private Color GetColor(IGenealogyGraphNode node) {
186      var colorIndex = (int)Math.Round(node.Quality * ColorGradient.Colors.Count);
187      if (colorIndex >= ColorGradient.Colors.Count) return ColorGradient.Colors.Last();
188      return ColorGradient.Colors[colorIndex];
189    }
190  }
191
192  [Item("GenealogyGraph", "A genealogy graph in which the vertex data is of type T")]
193  [StorableClass]
194  public class GenealogyGraph<T> : GenealogyGraph, IGenealogyGraph<T> where T : class, IItem {
195    public GenealogyGraph() { }
196    private GenealogyGraph(GenealogyGraph original, Cloner cloner)
197      : base(original, cloner) {
198    }
199    public override IDeepCloneable Clone(Cloner cloner) {
200      return new GenealogyGraph<T>(this, cloner);
201    }
202    new public IEnumerable<IGenealogyGraphNode<T>> Vertices {
203      get { return base.Vertices.Select(x => (IGenealogyGraphNode<T>)x); }
204    }
205    new public IGenealogyGraphNode<T> GetByContent(object content) {
206      return (IGenealogyGraphNode<T>)base.GetByContent(content);
207    }
208    new public IGenealogyGraphNode<T> GetById(string id) {
209      return (IGenealogyGraphNode<T>)base.GetById(id);
210    }
211    new public IEnumerable<IGenealogyGraphNode<T>> GetByRank(double rank) {
212      return base.GetByRank(rank).Select(x => (IGenealogyGraphNode<T>)x);
213    }
214    public new IEnumerable<KeyValuePair<double, IEnumerable<IGenealogyGraphNode<T>>>> Ranks {
215      get { return base.Ranks.Select(x => new KeyValuePair<double, IEnumerable<IGenealogyGraphNode<T>>>(x.Key, x.Value.Select(n => (IGenealogyGraphNode<T>)n))); }
216    }
217  }
218}
Note: See TracBrowser for help on using the repository browser.