Free cookie consent management tool by TermsFeed Policy Generator

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.

File:
1 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);
Note: See TracChangeset for help on using the changeset viewer.