Free cookie consent management tool by TermsFeed Policy Generator

source: branches/CloningRefactoring/HeuristicLab.Analysis/3.3/AlleleFrequencyAnalyzer.cs @ 4680

Last change on this file since 4680 was 4677, checked in by abeham, 14 years ago

#922

  • Refactored HeuristicLab.Analysis
File size: 10.6 KB
Line 
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
22using System.Collections.Generic;
23using System.Linq;
24using HeuristicLab.Core;
25using HeuristicLab.Data;
26using HeuristicLab.Operators;
27using HeuristicLab.Optimization;
28using HeuristicLab.Parameters;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30using HeuristicLab.Common;
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    }
48    public LookupParameter<T> BestKnownSolutionParameter {
49      get { return (LookupParameter<T>)Parameters["BestKnownSolution"]; }
50    }
51    public ValueLookupParameter<ResultCollection> ResultsParameter {
52      get { return (ValueLookupParameter<ResultCollection>)Parameters["Results"]; }
53    }
54    public ValueParameter<BoolValue> StoreAlleleFrequenciesHistoryParameter {
55      get { return (ValueParameter<BoolValue>)Parameters["StoreAlleleFrequenciesHistory"]; }
56    }
57    public ValueParameter<IntValue> UpdateIntervalParameter {
58      get { return (ValueParameter<IntValue>)Parameters["UpdateInterval"]; }
59    }
60    public LookupParameter<IntValue> UpdateCounterParameter {
61      get { return (LookupParameter<IntValue>)Parameters["UpdateCounter"]; }
62    }
63
64    #region Storing & Cloning
65    [StorableConstructor]
66    protected AlleleFrequencyAnalyzer(bool deserializing) : base(deserializing) { }
67    protected AlleleFrequencyAnalyzer(AlleleFrequencyAnalyzer<T> original, Cloner cloner) : base(original, cloner) { }
68    #endregion
69    public AlleleFrequencyAnalyzer()
70      : base() {
71      Parameters.Add(new LookupParameter<BoolValue>("Maximization", "True if the problem is a maximization problem."));
72      Parameters.Add(new ScopeTreeLookupParameter<T>("Solution", "The solutions whose alleles should be analyzed."));
73      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("Quality", "The qualities of the solutions which should be analyzed."));
74      Parameters.Add(new LookupParameter<T>("BestKnownSolution", "The best known solution."));
75      Parameters.Add(new ValueLookupParameter<ResultCollection>("Results", "The result collection where the allele frequency analysis results should be stored."));
76      Parameters.Add(new ValueParameter<BoolValue>("StoreAlleleFrequenciesHistory", "True if the history of all allele frequencies should be stored.", new BoolValue(false)));
77      Parameters.Add(new ValueParameter<IntValue>("UpdateInterval", "The interval in which the allele frequency analysis should be applied.", new IntValue(1)));
78      Parameters.Add(new LookupParameter<IntValue>("UpdateCounter", "The value which counts how many times the operator was called since the last update.", "AlleleFrequencyAnalyzerUpdateCounter"));
79    }
80
81    #region AlleleFrequencyIdEqualityComparer
82    private class AlleleFrequencyIdEqualityComparer : IEqualityComparer<AlleleFrequency> {
83      public bool Equals(AlleleFrequency x, AlleleFrequency y) {
84        return x.Id == y.Id;
85      }
86      public int GetHashCode(AlleleFrequency obj) {
87        return obj.Id.GetHashCode();
88      }
89    }
90    #endregion
91
92    public override IOperation Apply() {
93      int updateInterval = UpdateIntervalParameter.Value.Value;
94      IntValue updateCounter = UpdateCounterParameter.ActualValue;
95      if (updateCounter == null) {
96        updateCounter = new IntValue(updateInterval);
97        UpdateCounterParameter.ActualValue = updateCounter;
98      } else updateCounter.Value++;
99
100      if (updateCounter.Value == updateInterval) {
101        updateCounter.Value = 0;
102
103        bool max = MaximizationParameter.ActualValue.Value;
104        ItemArray<T> solutions = SolutionParameter.ActualValue;
105        ItemArray<DoubleValue> qualities = QualityParameter.ActualValue;
106        T bestKnownSolution = BestKnownSolutionParameter.ActualValue;
107        bool storeHistory = StoreAlleleFrequenciesHistoryParameter.Value.Value;
108
109        // calculate index of current best solution
110        int bestIndex = -1;
111        if (!max) bestIndex = qualities.Select((x, index) => new { index, x.Value }).OrderBy(x => x.Value).First().index;
112        else bestIndex = qualities.Select((x, index) => new { index, x.Value }).OrderByDescending(x => x.Value).First().index;
113
114        // calculate allels of current best and (if available) best known solution
115        Allele[] bestAlleles = CalculateAlleles(solutions[bestIndex]);
116        Allele[] bestKnownAlleles = null;
117        if (bestKnownSolution != null)
118          bestKnownAlleles = CalculateAlleles(bestKnownSolution);
119
120        // calculate allele frequencies
121        var frequencies = solutions.SelectMany((s, index) => CalculateAlleles(s).Select(a => new { Allele = a, Quality = qualities[index] })).
122                          GroupBy(x => x.Allele.Id).
123                          Select(x => new AlleleFrequency(x.Key,
124                                                          x.Count() / ((double)solutions.Length),
125                                                          x.Average(a => a.Allele.Impact),
126                                                          x.Average(a => a.Quality.Value),
127                                                          bestKnownAlleles == null ? false : bestKnownAlleles.Any(a => a.Id == x.Key),
128                                                          bestAlleles.Any(a => a.Id == x.Key)));
129
130        // calculate dummy allele frequencies of alleles of best known solution which did not occur
131        if (bestKnownAlleles != null) {
132          var bestKnownFrequencies = bestKnownAlleles.Select(x => new AlleleFrequency(x.Id, 0, x.Impact, 0, true, false)).Except(frequencies, new AlleleFrequencyIdEqualityComparer());
133          frequencies = frequencies.Concat(bestKnownFrequencies);
134        }
135
136        // fetch results collection
137        ResultCollection results;
138        if (!ResultsParameter.ActualValue.ContainsKey("Allele Frequency Analysis Results")) {
139          results = new ResultCollection();
140          ResultsParameter.ActualValue.Add(new Result("Allele Frequency Analysis Results", results));
141        } else {
142          results = (ResultCollection)ResultsParameter.ActualValue["Allele Frequency Analysis Results"].Value;
143        }
144
145        // store allele frequencies
146        AlleleFrequencyCollection frequenciesCollection = new AlleleFrequencyCollection(frequencies);
147        if (!results.ContainsKey("Allele Frequencies"))
148          results.Add(new Result("Allele Frequencies", frequenciesCollection));
149        else
150          results["Allele Frequencies"].Value = frequenciesCollection;
151
152        // store allele frequencies history
153        if (storeHistory) {
154          if (!results.ContainsKey("Allele Frequencies History")) {
155            AlleleFrequencyCollectionHistory history = new AlleleFrequencyCollectionHistory();
156            history.Add(frequenciesCollection);
157            results.Add(new Result("Allele Frequencies History", history));
158          } else {
159            ((AlleleFrequencyCollectionHistory)results["Allele Frequencies History"].Value).Add(frequenciesCollection);
160          }
161        }
162
163        // store alleles data table
164        DataTable allelesTable;
165        if (!results.ContainsKey("Alleles")) {
166          allelesTable = new DataTable("Alleles");
167          results.Add(new Result("Alleles", allelesTable));
168          allelesTable.Rows.Add(new DataRow("Unique Alleles"));
169          DataRowVisualProperties visualProperties = new DataRowVisualProperties();
170          visualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Line;
171          visualProperties.SecondYAxis = true;
172          visualProperties.StartIndexZero = true;
173          allelesTable.Rows.Add(new DataRow("Unique Alleles of Best Known Solution", null, visualProperties));
174          allelesTable.Rows.Add(new DataRow("Fixed Alleles", null, visualProperties));
175          allelesTable.Rows.Add(new DataRow("Fixed Alleles of Best Known Solution", null, visualProperties));
176          allelesTable.Rows.Add(new DataRow("Lost Alleles of Best Known Solution", null, visualProperties));
177        } else {
178          allelesTable = (DataTable)results["Alleles"].Value;
179        }
180
181        int fixedAllelesCount = frequenciesCollection.Where(x => x.Frequency == 1).Count();
182        var relevantAlleles = frequenciesCollection.Where(x => x.ContainedInBestKnownSolution);
183        int relevantAllelesCount = relevantAlleles.Count();
184        int fixedRelevantAllelesCount = relevantAlleles.Where(x => x.Frequency == 1).Count();
185        int lostRelevantAllelesCount = relevantAlleles.Where(x => x.Frequency == 0).Count();
186        int uniqueRelevantAllelesCount = relevantAllelesCount - lostRelevantAllelesCount;
187        allelesTable.Rows["Unique Alleles"].Values.Add(frequenciesCollection.Count);
188        allelesTable.Rows["Unique Alleles of Best Known Solution"].Values.Add(uniqueRelevantAllelesCount);
189        allelesTable.Rows["Fixed Alleles"].Values.Add(fixedAllelesCount);
190        allelesTable.Rows["Fixed Alleles of Best Known Solution"].Values.Add(fixedRelevantAllelesCount);
191        allelesTable.Rows["Lost Alleles of Best Known Solution"].Values.Add(lostRelevantAllelesCount);
192      }
193      return base.Apply();
194    }
195
196    protected abstract Allele[] CalculateAlleles(T solution);
197  }
198}
Note: See TracBrowser for help on using the repository browser.