Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OaaS/HeuristicLab.Analysis/3.3/AlleleFrequencyAnalysis/AlleleFrequencyAnalyzer.cs @ 9070

Last change on this file since 9070 was 7259, checked in by swagner, 13 years ago

Updated year of copyrights to 2012 (#1716)

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