Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ParameterBinding/HeuristicLab.Analysis/3.3/AlleleFrequencyAnalyzer.cs @ 5469

Last change on this file since 5469 was 4722, checked in by swagner, 14 years ago

Merged cloning refactoring branch back into trunk (#922)

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