Free cookie consent management tool by TermsFeed Policy Generator

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

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

Worked on allele frequency analysis (#1234)

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