Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Analysis/3.3/AlleleFrequencyAnalysis/AlleleFrequencyAnalyzer.cs @ 5287

Last change on this file since 5287 was 4991, checked in by swinkler, 14 years ago

Renamed results collections of population diversity and allele frequency analyzers. (#1303)

File size: 12.8 KB
RevLine 
[4623]1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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
[4639]22using System.Collections.Generic;
[4623]23using System.Linq;
[4722]24using HeuristicLab.Common;
[4623]25using HeuristicLab.Core;
26using HeuristicLab.Data;
27using HeuristicLab.Operators;
28using HeuristicLab.Optimization;
29using HeuristicLab.Parameters;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
32namespace HeuristicLab.Analysis {
33  /// <summary>
34  /// An operator for analyzing the frequency of alleles.
35  /// </summary>
36  [Item("AlleleFrequencyAnalyzer", "An operator for analyzing the frequency of alleles.")]
37  [StorableClass]
38  public abstract class AlleleFrequencyAnalyzer<T> : SingleSuccessorOperator, IAnalyzer where T : class, IItem {
39    public LookupParameter<BoolValue> MaximizationParameter {
40      get { return (LookupParameter<BoolValue>)Parameters["Maximization"]; }
41    }
42    public ScopeTreeLookupParameter<T> SolutionParameter {
43      get { return (ScopeTreeLookupParameter<T>)Parameters["Solution"]; }
44    }
45    public ScopeTreeLookupParameter<DoubleValue> QualityParameter {
46      get { return (ScopeTreeLookupParameter<DoubleValue>)Parameters["Quality"]; }
47    }
[4631]48    public LookupParameter<T> BestKnownSolutionParameter {
49      get { return (LookupParameter<T>)Parameters["BestKnownSolution"]; }
50    }
[4623]51    public ValueLookupParameter<ResultCollection> ResultsParameter {
52      get { return (ValueLookupParameter<ResultCollection>)Parameters["Results"]; }
53    }
[4704]54    public ValueParameter<BoolValue> StoreHistoryParameter {
55      get { return (ValueParameter<BoolValue>)Parameters["StoreHistory"]; }
[4623]56    }
[4631]57    public ValueParameter<IntValue> UpdateIntervalParameter {
58      get { return (ValueParameter<IntValue>)Parameters["UpdateInterval"]; }
[4623]59    }
[4631]60    public LookupParameter<IntValue> UpdateCounterParameter {
61      get { return (LookupParameter<IntValue>)Parameters["UpdateCounter"]; }
62    }
[4623]63
[4704]64    [StorableConstructor]
65    protected AlleleFrequencyAnalyzer(bool deserializing) : base(deserializing) { }
[4722]66    protected AlleleFrequencyAnalyzer(AlleleFrequencyAnalyzer<T> original, Cloner cloner) : base(original, cloner) { }
[4623]67    public AlleleFrequencyAnalyzer()
68      : base() {
69      Parameters.Add(new LookupParameter<BoolValue>("Maximization", "True if the problem is a maximization problem."));
70      Parameters.Add(new ScopeTreeLookupParameter<T>("Solution", "The solutions whose alleles should be analyzed."));
71      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("Quality", "The qualities of the solutions which should be analyzed."));
[4631]72      Parameters.Add(new LookupParameter<T>("BestKnownSolution", "The best known solution."));
[4623]73      Parameters.Add(new ValueLookupParameter<ResultCollection>("Results", "The result collection where the allele frequency analysis results should be stored."));
[4704]74      Parameters.Add(new ValueParameter<BoolValue>("StoreHistory", "True if the history of the allele frequency analysis should be stored.", new BoolValue(false)));
[4631]75      Parameters.Add(new ValueParameter<IntValue>("UpdateInterval", "The interval in which the allele frequency analysis should be applied.", new IntValue(1)));
[4641]76      Parameters.Add(new LookupParameter<IntValue>("UpdateCounter", "The value which counts how many times the operator was called since the last update.", "AlleleFrequencyAnalyzerUpdateCounter"));
[4623]77    }
78
[4641]79    #region AlleleFrequencyIdEqualityComparer
80    private class AlleleFrequencyIdEqualityComparer : IEqualityComparer<AlleleFrequency> {
[4639]81      public bool Equals(AlleleFrequency x, AlleleFrequency y) {
82        return x.Id == y.Id;
83      }
84      public int GetHashCode(AlleleFrequency obj) {
[4641]85        return obj.Id.GetHashCode();
[4639]86      }
87    }
[4641]88    #endregion
[4639]89
[4623]90    public override IOperation Apply() {
[4631]91      int updateInterval = UpdateIntervalParameter.Value.Value;
92      IntValue updateCounter = UpdateCounterParameter.ActualValue;
93      if (updateCounter == null) {
94        updateCounter = new IntValue(updateInterval);
95        UpdateCounterParameter.ActualValue = updateCounter;
96      } else updateCounter.Value++;
[4623]97
[4631]98      if (updateCounter.Value == updateInterval) {
99        updateCounter.Value = 0;
[4623]100
[4631]101        bool max = MaximizationParameter.ActualValue.Value;
102        ItemArray<T> solutions = SolutionParameter.ActualValue;
103        ItemArray<DoubleValue> qualities = QualityParameter.ActualValue;
104        T bestKnownSolution = BestKnownSolutionParameter.ActualValue;
[4704]105        bool storeHistory = StoreHistoryParameter.Value.Value;
[4623]106
[4631]107        // calculate index of current best solution
108        int bestIndex = -1;
[4849]109        if (!max) {
110          bestIndex = qualities
111            .Select((x, index) => new { index, x.Value })
112            .OrderBy(x => x.Value)
113            .First().index;
114        } else {
115          bestIndex = qualities
116            .Select((x, index) => new { index, x.Value })
117            .OrderByDescending(x => x.Value)
118            .First().index;
119        }
[4623]120
[4631]121        // calculate allels of current best and (if available) best known solution
122        Allele[] bestAlleles = CalculateAlleles(solutions[bestIndex]);
123        Allele[] bestKnownAlleles = null;
124        if (bestKnownSolution != null)
125          bestKnownAlleles = CalculateAlleles(bestKnownSolution);
[4623]126
[4631]127        // calculate allele frequencies
128        var frequencies = solutions.SelectMany((s, index) => CalculateAlleles(s).Select(a => new { Allele = a, Quality = qualities[index] })).
129                          GroupBy(x => x.Allele.Id).
130                          Select(x => new AlleleFrequency(x.Key,
131                                                          x.Count() / ((double)solutions.Length),
132                                                          x.Average(a => a.Allele.Impact),
133                                                          x.Average(a => a.Quality.Value),
134                                                          bestKnownAlleles == null ? false : bestKnownAlleles.Any(a => a.Id == x.Key),
135                                                          bestAlleles.Any(a => a.Id == x.Key)));
136
[4639]137        // calculate dummy allele frequencies of alleles of best known solution which did not occur
[4645]138        if (bestKnownAlleles != null) {
139          var bestKnownFrequencies = bestKnownAlleles.Select(x => new AlleleFrequency(x.Id, 0, x.Impact, 0, true, false)).Except(frequencies, new AlleleFrequencyIdEqualityComparer());
140          frequencies = frequencies.Concat(bestKnownFrequencies);
141        }
[4639]142
[4631]143        // fetch results collection
144        ResultCollection results;
[4991]145        if (!ResultsParameter.ActualValue.ContainsKey(Name + " Results")) {
[4631]146          results = new ResultCollection();
[4991]147          ResultsParameter.ActualValue.Add(new Result(Name + " Results", results));
[4631]148        } else {
[4991]149          results = (ResultCollection)ResultsParameter.ActualValue[Name + " Results"].Value;
[4631]150        }
151
152        // store allele frequencies
[4645]153        AlleleFrequencyCollection frequenciesCollection = new AlleleFrequencyCollection(frequencies);
[4631]154        if (!results.ContainsKey("Allele Frequencies"))
[4639]155          results.Add(new Result("Allele Frequencies", frequenciesCollection));
[4631]156        else
[4639]157          results["Allele Frequencies"].Value = frequenciesCollection;
[4631]158
159        // store allele frequencies history
160        if (storeHistory) {
161          if (!results.ContainsKey("Allele Frequencies History")) {
[4641]162            AlleleFrequencyCollectionHistory history = new AlleleFrequencyCollectionHistory();
[4639]163            history.Add(frequenciesCollection);
[4631]164            results.Add(new Result("Allele Frequencies History", history));
165          } else {
[4641]166            ((AlleleFrequencyCollectionHistory)results["Allele Frequencies History"].Value).Add(frequenciesCollection);
[4631]167          }
168        }
169
170        // store alleles data table
171        DataTable allelesTable;
172        if (!results.ContainsKey("Alleles")) {
173          allelesTable = new DataTable("Alleles");
[4870]174          allelesTable.VisualProperties.XAxisTitle = "Iteration";
175          allelesTable.VisualProperties.YAxisTitle = "Number of Alleles";
176          allelesTable.VisualProperties.SecondYAxisTitle = "Number of Alleles";
[4777]177
[4631]178          allelesTable.Rows.Add(new DataRow("Unique Alleles"));
[4778]179          allelesTable.Rows["Unique Alleles"].VisualProperties.StartIndexZero = true;
[4777]180
181          allelesTable.Rows.Add(new DataRow("Unique Alleles of Best Known Solution", null));
182          allelesTable.Rows["Unique Alleles of Best Known Solution"].VisualProperties.SecondYAxis = true;
183          allelesTable.Rows["Unique Alleles of Best Known Solution"].VisualProperties.StartIndexZero = true;
184
185          allelesTable.Rows.Add(new DataRow("Fixed Alleles", null));
186          allelesTable.Rows["Fixed Alleles"].VisualProperties.SecondYAxis = true;
187          allelesTable.Rows["Fixed Alleles"].VisualProperties.StartIndexZero = true;
188
189          allelesTable.Rows.Add(new DataRow("Fixed Alleles of Best Known Solution", null));
190          allelesTable.Rows["Fixed Alleles of Best Known Solution"].VisualProperties.SecondYAxis = true;
191          allelesTable.Rows["Fixed Alleles of Best Known Solution"].VisualProperties.StartIndexZero = true;
192
193          allelesTable.Rows.Add(new DataRow("Lost Alleles of Best Known Solution", null));
194          allelesTable.Rows["Lost Alleles of Best Known Solution"].VisualProperties.SecondYAxis = true;
195          allelesTable.Rows["Lost Alleles of Best Known Solution"].VisualProperties.StartIndexZero = true;
[4870]196
197          results.Add(new Result("Alleles", allelesTable));
[4631]198        } else {
199          allelesTable = (DataTable)results["Alleles"].Value;
200        }
[4645]201
202        int fixedAllelesCount = frequenciesCollection.Where(x => x.Frequency == 1).Count();
203        var relevantAlleles = frequenciesCollection.Where(x => x.ContainedInBestKnownSolution);
204        int relevantAllelesCount = relevantAlleles.Count();
205        int fixedRelevantAllelesCount = relevantAlleles.Where(x => x.Frequency == 1).Count();
206        int lostRelevantAllelesCount = relevantAlleles.Where(x => x.Frequency == 0).Count();
207        int uniqueRelevantAllelesCount = relevantAllelesCount - lostRelevantAllelesCount;
[4639]208        allelesTable.Rows["Unique Alleles"].Values.Add(frequenciesCollection.Count);
[4645]209        allelesTable.Rows["Unique Alleles of Best Known Solution"].Values.Add(uniqueRelevantAllelesCount);
210        allelesTable.Rows["Fixed Alleles"].Values.Add(fixedAllelesCount);
211        allelesTable.Rows["Fixed Alleles of Best Known Solution"].Values.Add(fixedRelevantAllelesCount);
212        allelesTable.Rows["Lost Alleles of Best Known Solution"].Values.Add(lostRelevantAllelesCount);
[4716]213
214        // store alleles values
215        if (!results.ContainsKey("Unique Alleles"))
216          results.Add(new Result("Unique Alleles", new DoubleValue(frequenciesCollection.Count)));
217        else
218          ((DoubleValue)results["Unique Alleles"].Value).Value = frequenciesCollection.Count;
219
220        if (!results.ContainsKey("Unique Alleles of Best Known Solution"))
221          results.Add(new Result("Unique Alleles of Best Known Solution", new DoubleValue(uniqueRelevantAllelesCount)));
222        else
223          ((DoubleValue)results["Unique Alleles of Best Known Solution"].Value).Value = uniqueRelevantAllelesCount;
224
225        if (!results.ContainsKey("Fixed Alleles"))
226          results.Add(new Result("Fixed Alleles", new DoubleValue(fixedAllelesCount)));
227        else
228          ((DoubleValue)results["Fixed Alleles"].Value).Value = fixedAllelesCount;
229
230        if (!results.ContainsKey("Fixed Alleles of Best Known Solution"))
231          results.Add(new Result("Fixed Alleles of Best Known Solution", new DoubleValue(fixedRelevantAllelesCount)));
232        else
233          ((DoubleValue)results["Fixed Alleles of Best Known Solution"].Value).Value = fixedRelevantAllelesCount;
234
235        if (!results.ContainsKey("Lost Alleles of Best Known Solution"))
236          results.Add(new Result("Lost Alleles of Best Known Solution", new DoubleValue(lostRelevantAllelesCount)));
237        else
238          ((DoubleValue)results["Lost Alleles of Best Known Solution"].Value).Value = lostRelevantAllelesCount;
[4631]239      }
[4623]240      return base.Apply();
241    }
242
243    protected abstract Allele[] CalculateAlleles(T solution);
244  }
245}
Note: See TracBrowser for help on using the repository browser.