Free cookie consent management tool by TermsFeed Policy Generator

Changeset 11390


Ignore:
Timestamp:
09/25/14 17:14:51 (10 years ago)
Author:
bburlacu
Message:

#1772: Simplified code in the GenealogyAnalyzer and removed useless property in BeforeCrossoverOperator.cs. Small cosmetic changes in GenealogyAnalyzer.cs and IGenealogyGraph.cs.

Location:
branches/HeuristicLab.EvolutionTracking/HeuristicLab.EvolutionTracking/3.4
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • branches/HeuristicLab.EvolutionTracking/HeuristicLab.EvolutionTracking/3.4/Analyzers/GenealogyAnalyzer.cs

    r11318 r11390  
    2020#endregion
    2121
    22 using System;
     22using System.Collections.Generic;
    2323using System.Linq;
    2424using HeuristicLab.Analysis;
     
    125125    public BoolValue EnableSolutionCreatorTracking {
    126126      get { return EnableSolutionCreatorTrackingParameter.Value; }
    127     }
    128 
    129     public IGenealogyGraph<T> GenealogyGraph {
    130       get {
    131         IResult result;
    132         var results = ResultsParameter.ActualValue;
    133         if (!results.ContainsKey(PopulationGraphParameterName)) {
    134           result = new Result(PopulationGraphParameterName, new GenealogyGraph<T>());
    135           results.Add(result);
    136         } else {
    137           result = results[PopulationGraphParameterName];
    138         }
    139         var graph = (IGenealogyGraph<T>)result.Value;
    140         return graph;
    141       }
    142127    }
    143128    #endregion
     
    242227
    243228    public override IOperation Apply() {
     229      IGenealogyGraph<T> genealogyGraph;
     230      var results = ResultsParameter.ActualValue;
     231      if (!results.ContainsKey(PopulationGraphParameterName)) {
     232        genealogyGraph = new GenealogyGraph<T>();
     233        results.Add(new Result(PopulationGraphParameterName, genealogyGraph));
     234      } else {
     235        genealogyGraph = (IGenealogyGraph<T>)results[PopulationGraphParameterName].Value;
     236      }
     237
    244238      var population = PopulationParameter.ActualValue;
    245239      var qualities = QualityParameter.ActualValue.ToList();
     
    252246          var individual = population[i];
    253247          var vertex = new GenealogyGraphNode<T>(individual) { Rank = generation };
    254           GenealogyGraph.AddVertex(vertex);
     248          genealogyGraph.AddVertex(vertex);
    255249          // save the vertex id in the individual scope (so that we can identify graph indices)
    256250          ExecutionContext.Scope.SubScopes[i].Variables.Add(new Variable("Id", new StringValue(vertex.Id)));
     
    261255
    262256        for (int i = 0; i < population.Length; ++i) {
    263           if (GenealogyGraph.GetByContent(population[i]).Rank.Equals(generation - 1)) {
     257          if (genealogyGraph.GetByContent(population[i]).Rank.Equals(generation - 1)) {
    264258            elite = population[i];
    265259            index = i;
     
    270264        #region add elite in the graph and connect it with the previous elite
    271265        if (elite != null) {
    272           var prevVertex = (IGenealogyGraphNode<T>)GenealogyGraph.GetByContent(elite);
     266          var prevVertex = genealogyGraph.GetByContent(elite);
    273267          prevVertex.IsElite = true; // mark elites in the graph retroactively
    274           var v = new GenealogyGraphNode<T>((IDeepCloneable)prevVertex.Data.Clone()) {
    275             Rank = generation,
    276             Quality = prevVertex.Quality,
    277             IsElite = false
    278           };
    279           GenealogyGraph.AddVertex(v);
    280           GenealogyGraph.AddArc(prevVertex, v);
    281 
     268          var v = (IGenealogyGraphNode<T>)prevVertex.Clone();
     269          v.Rank = generation;
     270          v.IsElite = false;
     271          population[index] = v.Data;
     272          genealogyGraph.AddVertex(v);
     273          genealogyGraph.AddArc(prevVertex, v);
    282274          // inject the graph node unique id to the scope
    283275          ExecutionContext.Scope.SubScopes[index].Variables[BeforeManipulatorOperator.ChildParameter.ActualName].Value = v.Data;
     
    286278        #endregion
    287279
    288         ComputeSuccessRatios();
     280        ComputeSuccessRatios(genealogyGraph);
    289281      }
    290282      // update qualities
    291283      for (int i = 0; i < population.Length; ++i) {
    292         var vertex = GenealogyGraph.GetByContent(population[i]);
     284        var vertex = genealogyGraph.GetByContent(population[i]);
    293285        vertex.Quality = qualities[i].Value;
    294286      }
    295287
    296288      // remove extra graph nodes (added by the instrumented operators in the case of offspring selection)
    297       RemoveUnsuccessfulOffspring();
     289      var pop = new HashSet<T>(population);
     290      var discarded = genealogyGraph.Ranks[generation].Where(x => !pop.Contains(x.Data)).ToList();
     291      for (int i = 0; i < discarded.Count; ++i) {
     292        var v = discarded[i];
     293        if (v.InDegree == 1) {
     294          var p = v.Parents.First();
     295          if (p.Rank.Equals(generation - 0.5))
     296            // the individual was a product of mutation. since it wasn't selected, we must remove both it and it's parent
     297            // ("intermediate" vertex result of crossover)
     298            discarded.Add(v.Parents.First());
     299        }
     300      }
     301      genealogyGraph.RemoveVertices(discarded);
     302      //RemoveUnsuccessfulOffspring();
    298303
    299304      return base.Apply();
    300     }
    301 
    302     private void RemoveUnsuccessfulOffspring() {
    303       int generation = GenerationsParameter.ActualValue.Value;
    304       var population = PopulationParameter.ActualValue;
    305       var discardedOffspring = GenealogyGraph.Ranks[generation].Select(x => (T)x.Data).Except(population).ToList();
    306       foreach (var vertex in discardedOffspring.Select(individual => GenealogyGraph.GetByContent(individual))) {
    307         if (vertex.InDegree == 1) {
    308           var p = vertex.Parents.First();
    309           if (!p.Rank.Equals(generation - 0.5))
    310             throw new InvalidOperationException("Parent must be an intermediate vertex");
    311           GenealogyGraph.RemoveVertex(p);
    312         }
    313         GenealogyGraph.RemoveVertex(vertex);
    314       }
    315305    }
    316306
    317307    // this method works when called before the unsuccesful offspring are removed from the genealogy graph
    318308    // so it must always be called before RemoveUnsuccessfulOffspring()
    319     private void ComputeSuccessRatios() {
     309    private void ComputeSuccessRatios(IGenealogyGraph<T> genealogyGraph) {
    320310      const string successfulOffspringRatioTableHistoryName = "Successful offspring ratios history";
    321311      const string successfulOffspringAbsoluteValuesTableHistoryName = "Successful offspring values history";
     
    327317      // compute the weight of each genealogy graph node as the ratio (produced offspring) / (surviving offspring)
    328318      foreach (var ind in population) {
    329         var v = GenealogyGraph.GetByContent(ind);
     319        var v = genealogyGraph.GetByContent(ind);
    330320        if (v.Parents.Count() == 1) {
    331321          var p = v.Parents.First();
     
    356346        VisualProperties = { ChartType = DataRowVisualProperties.DataRowChartType.Columns, StartIndexZero = true }
    357347      };
    358       successfulOffspringRatioRow.Values.Replace(GenealogyGraph.Ranks[generation - 1].OrderByDescending(x => x.Quality).Select(x => x.OutDegree > 0 ? x.Weight / x.OutDegree : 0));
     348      successfulOffspringRatioRow.Values.Replace(genealogyGraph.Ranks[generation - 1].OrderByDescending(x => x.Quality).Select(x => x.OutDegree > 0 ? x.Weight / x.OutDegree : 0));
    359349      successfulOffspringRatioTable.Rows.Add(successfulOffspringRatioRow);
    360350      successfulOffspringRatioHistory.Add(successfulOffspringRatioTable);
     
    379369        VisualProperties = { ChartType = DataRowVisualProperties.DataRowChartType.Columns, StartIndexZero = true }
    380370      };
    381       successfulOffspringValuesRow.Values.Replace(GenealogyGraph.Ranks[generation - 1].OrderByDescending(x => x.Quality).Select(x => x.Weight));
     371      successfulOffspringValuesRow.Values.Replace(genealogyGraph.Ranks[generation - 1].OrderByDescending(x => x.Quality).Select(x => x.Weight));
    382372      successfulOffspringValuesTable.Rows.Add(successfulOffspringValuesRow);
    383373      successfulOffspringAbsoluteHistory.Add(successfulOffspringValuesTable);
  • branches/HeuristicLab.EvolutionTracking/HeuristicLab.EvolutionTracking/3.4/GenealogyGraph/GenealogyGraph.cs

    r11386 r11390  
    3838
    3939    [Storable]
    40     private Dictionary<double, List<IGenealogyGraphNode>> ranks;
     40    protected Dictionary<double, List<IGenealogyGraphNode>> ranks;
    4141
    4242    public Dictionary<double, List<IGenealogyGraphNode>> Ranks {
     
    6767    }
    6868
    69     public new IEnumerable<IGenealogyGraphNode> Vertices {
    70       get { return from n in base.Vertices select (IGenealogyGraphNode)n; }
     69    new public IEnumerable<IGenealogyGraphNode> Vertices {
     70      get { return base.Vertices.Select(x => (IGenealogyGraphNode)x); }
    7171    }
    7272
     
    7979    public override void AddVertex(IVertex vertex) {
    8080      base.AddVertex(vertex);
    81       var node = (IGenealogyGraphNode)vertex;
    82       if (!Ranks.ContainsKey(node.Rank))
    83         Ranks[node.Rank] = new List<IGenealogyGraphNode>();
    84       Ranks[node.Rank].Add(node);
    85 
    86       if (contentMap.ContainsKey(node.Data))
     81      var genealogyGraphNode = (IGenealogyGraphNode)vertex;
     82      if (contentMap.ContainsKey(genealogyGraphNode.Data))
    8783        throw new InvalidOperationException("Duplicate content is not allowed in the genealogy graph.");
    88       contentMap[node.Data] = node;
    89 
    90       if (idMap.ContainsKey(node.Id))
     84      contentMap[genealogyGraphNode.Data] = genealogyGraphNode;
     85      if (idMap.ContainsKey(genealogyGraphNode.Id))
    9186        throw new InvalidOperationException("Duplicate ids are not allowed in the genealogy graph.");
    92       idMap[node.Id] = node;
     87      idMap[genealogyGraphNode.Id] = genealogyGraphNode;
     88      if (!Ranks.ContainsKey(genealogyGraphNode.Rank))
     89        Ranks[genealogyGraphNode.Rank] = new List<IGenealogyGraphNode>();
     90      Ranks[genealogyGraphNode.Rank].Add(genealogyGraphNode);
    9391    }
    9492
     
    137135  [StorableClass]
    138136  public class GenealogyGraph<T> : GenealogyGraph, IGenealogyGraph<T> where T : class, IItem {
    139     public new IEnumerable<IGenealogyGraphNode<T>> Vertices {
    140       get { return base.Vertices.Cast<IGenealogyGraphNode<T>>(); }
     137    new public IEnumerable<IGenealogyGraphNode<T>> Vertices {
     138      get { return base.Vertices.Select(x => (IGenealogyGraphNode<T>)x); }
    141139    }
    142 
    143     public new IGenealogyGraphNode<T> GetByContent(object content) {
     140    new public IGenealogyGraphNode<T> GetByContent(object content) {
    144141      return (IGenealogyGraphNode<T>)base.GetByContent(content);
    145142    }
    146 
    147     public new IGenealogyGraphNode<T> GetById(string id) {
     143    new public IGenealogyGraphNode<T> GetById(string id) {
    148144      return (IGenealogyGraphNode<T>)base.GetById(id);
    149145    }
  • branches/HeuristicLab.EvolutionTracking/HeuristicLab.EvolutionTracking/3.4/GenealogyGraph/Interfaces/IGenealogyGraph.cs

    r11386 r11390  
    2626  public interface IGenealogyGraph : IDirectedGraph {
    2727    Dictionary<double, List<IGenealogyGraphNode>> Ranks { get; }
    28     new IEnumerable<IGenealogyGraphNode> Vertices { get; }
    2928    IGenealogyGraphNode GetByContent(object content);
    3029    IGenealogyGraphNode GetById(string id);
    3130    bool Contains(object content);
     31    new IEnumerable<IGenealogyGraphNode> Vertices { get; }
    3232  }
    3333
  • branches/HeuristicLab.EvolutionTracking/HeuristicLab.EvolutionTracking/3.4/Operators/BeforeCrossoverOperator.cs

    r11253 r11390  
    2121
    2222using System;
    23 using System.Collections.Generic;
    2423using System.Linq;
    2524using HeuristicLab.Common;
     
    5049      : base(original, cloner) {
    5150    }
     51
    5252    public override IDeepCloneable Clone(Cloner cloner) {
    5353      return new BeforeCrossoverOperator<T>(this, cloner);
     
    6161      Parameters.Add(new LookupParameter<T>(ChildParameterName));
    6262      Parameters.Add(new ValueParameter<IntValue>("ExecutionCount", new IntValue(0)));
    63     }
    64 
    65     protected List<IGenealogyGraphNode<T>> CurrentGeneration {
    66       get {
    67         if (GenealogyGraph.Ranks.ContainsKey(Generations.Value))
    68           return GenealogyGraph.Ranks[Generations.Value].Cast<IGenealogyGraphNode<T>>().ToList();
    69         return null;
    70       }
    7163    }
    7264
Note: See TracChangeset for help on using the changeset viewer.