Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Analyzers/SymbolicDataAnalysisSingleObjectivePruningAnalyzer.cs @ 12358

Last change on this file since 12358 was 12358, checked in by mkommend, 10 years ago

#2359: Refactored pruning operators and analyzers.

File size: 13.6 KB
Line 
1#region License Information
2
3/* HeuristicLab
4 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
5 *
6 * This file is part of HeuristicLab.
7 *
8 * HeuristicLab is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * HeuristicLab is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22#endregion
23
24using System;
25using System.Linq;
26using HeuristicLab.Analysis;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Operators;
31using HeuristicLab.Optimization.Operators;
32using HeuristicLab.Parameters;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
34
35namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
36  [StorableClass]
37  [Item("SymbolicDataAnalysisSingleObjectivePruningAnalyzer", "An analyzer that prunes introns from trees in single objective symbolic data analysis problems.")]
38  public abstract class SymbolicDataAnalysisSingleObjectivePruningAnalyzer : SymbolicDataAnalysisSingleObjectiveAnalyzer {
39    #region parameter names
40    private const string ProblemDataParameterName = "ProblemData";
41    private const string UpdateIntervalParameterName = "UpdateInverval";
42    private const string UpdateCounterParameterName = "UpdateCounter";
43    private const string PopulationSliceParameterName = "PopulationSlice";
44    private const string PruningProbabilityParameterName = "PruningProbability";
45    private const string TotalNumberOfPrunedSubtreesParameterName = "Number of pruned subtrees";
46    private const string TotalNumberOfPrunedTreesParameterName = "Number of pruned trees";
47    private const string RandomParameterName = "Random";
48    private const string PruneOnlyZeroImpactNodesParameterName = "PruneOnlyZeroImpactNodes";
49    private const string NodeImpactThresholdParameterName = "ImpactThreshold";
50    private const string PruningOperatorParameterName = "PruningOperator";
51    private const string ResultsParameterName = "Results";
52    private const string PopulationSizeParameterName = "PopulationSize";
53    #endregion
54
55    #region private members
56    private DataReducer prunedSubtreesReducer;
57    private DataReducer prunedTreesReducer;
58    private DataTableValuesCollector valuesCollector;
59    private ResultsCollector resultsCollector;
60    #endregion
61
62    #region parameter properties
63    public ILookupParameter<IRandom> RandomParameter {
64      get { return (ILookupParameter<IRandom>)Parameters[RandomParameterName]; }
65    }
66    public IFixedValueParameter<IntValue> UpdateIntervalParameter {
67      get { return (IFixedValueParameter<IntValue>)Parameters[UpdateIntervalParameterName]; }
68    }
69    public IFixedValueParameter<IntValue> UpdateCounterParameter {
70      get { return (IFixedValueParameter<IntValue>)Parameters[UpdateCounterParameterName]; }
71    }
72    public IFixedValueParameter<DoubleRange> PopulationSliceParameter {
73      get { return (IFixedValueParameter<DoubleRange>)Parameters[PopulationSliceParameterName]; }
74    }
75    public IFixedValueParameter<DoubleValue> PruningProbabilityParameter {
76      get { return (IFixedValueParameter<DoubleValue>)Parameters[PruningProbabilityParameterName]; }
77    }
78    public ILookupParameter<IntValue> PopulationSizeParameter {
79      get { return (ILookupParameter<IntValue>)Parameters[PopulationSizeParameterName]; }
80    }
81    #endregion
82
83    #region properties
84    protected abstract SymbolicDataAnalysisExpressionPruningOperator PruningOperator { get; }
85    protected int UpdateInterval { get { return UpdateIntervalParameter.Value.Value; } }
86
87    protected int UpdateCounter {
88      get { return UpdateCounterParameter.Value.Value; }
89      set { UpdateCounterParameter.Value.Value = value; }
90    }
91
92    protected double PopulationSliceStart {
93      get { return PopulationSliceParameter.Value.Start; }
94      set { PopulationSliceParameter.Value.Start = value; }
95    }
96
97    protected double PopulationSliceEnd {
98      get { return PopulationSliceParameter.Value.End; }
99      set { PopulationSliceParameter.Value.End = value; }
100    }
101
102    protected double PruningProbability {
103      get { return PruningProbabilityParameter.Value.Value; }
104      set { PruningProbabilityParameter.Value.Value = value; }
105    }
106    #endregion
107
108    #region IStatefulItem members
109    public override void InitializeState() {
110      base.InitializeState();
111      UpdateCounter = 0;
112    }
113    public override void ClearState() {
114      base.ClearState();
115      UpdateCounter = 0;
116    }
117    #endregion
118
119    [StorableConstructor]
120    protected SymbolicDataAnalysisSingleObjectivePruningAnalyzer(bool deserializing) : base(deserializing) { }
121
122    protected SymbolicDataAnalysisSingleObjectivePruningAnalyzer(SymbolicDataAnalysisSingleObjectivePruningAnalyzer original, Cloner cloner)
123      : base(original, cloner) {
124      if (original.prunedSubtreesReducer != null)
125        this.prunedSubtreesReducer = (DataReducer)original.prunedSubtreesReducer.Clone();
126      if (original.prunedTreesReducer != null)
127        this.prunedTreesReducer = (DataReducer)original.prunedTreesReducer.Clone();
128      if (original.valuesCollector != null)
129        this.valuesCollector = (DataTableValuesCollector)original.valuesCollector.Clone();
130      if (original.resultsCollector != null)
131        this.resultsCollector = (ResultsCollector)original.resultsCollector.Clone();
132    }
133
134    [StorableHook(HookType.AfterDeserialization)]
135    private void AfterDeserialization() {
136      if (!Parameters.ContainsKey(PopulationSizeParameterName)) {
137        Parameters.Add(new LookupParameter<IntValue>(PopulationSizeParameterName, "The population of individuals."));
138      }
139      if (Parameters.ContainsKey(UpdateCounterParameterName)) {
140        var fixedValueParameter = Parameters[UpdateCounterParameterName] as FixedValueParameter<IntValue>;
141        if (fixedValueParameter == null) {
142          var valueParameter = (ValueParameter<IntValue>)Parameters[UpdateCounterParameterName];
143          Parameters.Remove(UpdateCounterParameterName);
144          Parameters.Add(new FixedValueParameter<IntValue>(UpdateCounterParameterName, valueParameter.Value));
145        }
146      }
147      if (Parameters.ContainsKey(UpdateIntervalParameterName)) {
148        var fixedValueParameter = Parameters[UpdateIntervalParameterName] as FixedValueParameter<IntValue>;
149        if (fixedValueParameter == null) {
150          var valueParameter = (ValueParameter<IntValue>)Parameters[UpdateIntervalParameterName];
151          Parameters.Remove(UpdateIntervalParameterName);
152          Parameters.Add(new FixedValueParameter<IntValue>(UpdateIntervalParameterName, valueParameter.Value));
153        }
154      }
155      if (Parameters.ContainsKey(PopulationSliceParameterName)) {
156        var fixedValueParameter = Parameters[PopulationSliceParameterName] as FixedValueParameter<DoubleRange>;
157        if (fixedValueParameter == null) {
158          var valueParameter = (ValueParameter<DoubleRange>)Parameters[PopulationSliceParameterName];
159          Parameters.Remove(PopulationSliceParameterName);
160          Parameters.Add(new FixedValueParameter<DoubleRange>(PopulationSliceParameterName, valueParameter.Value));
161        }
162      }
163      if (Parameters.ContainsKey(PruningProbabilityParameterName)) {
164        var fixedValueParameter = Parameters[PruningProbabilityParameterName] as FixedValueParameter<DoubleValue>;
165        if (fixedValueParameter == null) {
166          var valueParameter = (ValueParameter<DoubleValue>)Parameters[PruningProbabilityParameterName];
167          Parameters.Remove(PruningProbabilityParameterName);
168          Parameters.Add(new FixedValueParameter<DoubleValue>(PruningProbabilityParameterName, valueParameter.Value));
169        }
170      }
171    }
172
173    protected SymbolicDataAnalysisSingleObjectivePruningAnalyzer() {
174      #region add parameters
175      Parameters.Add(new FixedValueParameter<DoubleRange>(PopulationSliceParameterName, "The slice of the population where pruning should be applied.", new DoubleRange(0.75, 1)));
176      Parameters.Add(new FixedValueParameter<DoubleValue>(PruningProbabilityParameterName, "The probability for pruning an individual.", new DoubleValue(0.5)));
177      Parameters.Add(new FixedValueParameter<IntValue>(UpdateIntervalParameterName, "The interval in which the tree length analysis should be applied.", new IntValue(1)));
178      Parameters.Add(new FixedValueParameter<IntValue>(UpdateCounterParameterName, "The value which counts how many times the operator was called", new IntValue(0)));
179      Parameters.Add(new LookupParameter<IRandom>(RandomParameterName, "The random number generator."));
180      Parameters.Add(new LookupParameter<IDataAnalysisProblemData>(ProblemDataParameterName, "The problem data."));
181      Parameters.Add(new LookupParameter<IntValue>(PopulationSizeParameterName, "The population of individuals."));
182      #endregion
183    }
184
185    //
186    /// <summary>
187    /// Computes the closed interval bounding the portion of the population that is to be pruned.
188    /// </summary>
189    /// <returns>Returns an int range [start, end]</returns>
190    private IntRange GetSliceBounds() {
191      if (PopulationSliceStart < 0 || PopulationSliceEnd < 0) throw new ArgumentOutOfRangeException("The slice bounds cannot be negative.");
192      if (PopulationSliceStart > 1 || PopulationSliceEnd > 1) throw new ArgumentOutOfRangeException("The slice bounds should be expressed as unit percentages.");
193      var count = PopulationSizeParameter.ActualValue.Value;
194      var start = (int)Math.Round(PopulationSliceStart * count);
195      var end = (int)Math.Round(PopulationSliceEnd * count);
196      if (end > count) end = count;
197
198      if (start >= end) throw new ArgumentOutOfRangeException("Invalid PopulationSlice bounds.");
199      return new IntRange(start, end);
200    }
201
202    private IOperation CreatePruningOperation() {
203      var operations = new OperationCollection { Parallel = true };
204      var range = GetSliceBounds();
205      var qualities = Quality.Select(x => x.Value).ToArray();
206      var indices = Enumerable.Range(0, qualities.Length).ToArray();
207      Array.Sort(qualities, indices);
208      if (!Maximization.Value) Array.Reverse(indices);
209
210      var subscopes = ExecutionContext.Scope.SubScopes;
211      var random = RandomParameter.ActualValue;
212
213      var empty = new EmptyOperator();
214
215      for (int i = 0; i < subscopes.Count; ++i) {
216        IOperator @operator;
217        if (range.Start <= i && i < range.End && random.NextDouble() <= PruningProbability)
218          @operator = PruningOperator;
219        else @operator = empty;
220        var index = indices[i];
221        var subscope = subscopes[index];
222        operations.Add(ExecutionContext.CreateChildOperation(@operator, subscope));
223      }
224      return operations;
225    }
226
227    public override IOperation Apply() {
228      UpdateCounter++;
229      if (UpdateCounter != UpdateInterval) return base.Apply();
230      UpdateCounter = 0;
231
232      if (prunedSubtreesReducer == null || prunedTreesReducer == null || valuesCollector == null || resultsCollector == null) { InitializeOperators(); }
233
234      var prune = CreatePruningOperation();
235      var reducePrunedSubtrees = ExecutionContext.CreateChildOperation(prunedSubtreesReducer);
236      var reducePrunedTrees = ExecutionContext.CreateChildOperation(prunedTreesReducer);
237      var collectValues = ExecutionContext.CreateChildOperation(valuesCollector);
238      var collectResults = ExecutionContext.CreateChildOperation(resultsCollector);
239
240      return new OperationCollection { prune, reducePrunedSubtrees, reducePrunedTrees, collectValues, collectResults, base.Apply() };
241    }
242
243    private void InitializeOperators() {
244      prunedSubtreesReducer = new DataReducer();
245      prunedSubtreesReducer.ParameterToReduce.ActualName = PruningOperator.PrunedSubtreesParameter.ActualName;
246      prunedSubtreesReducer.ReductionOperation.Value = new ReductionOperation(ReductionOperations.Sum); // sum all the pruned subtrees parameter values
247      prunedSubtreesReducer.TargetOperation.Value = new ReductionOperation(ReductionOperations.Assign); // asign the sum to the target parameter
248      prunedSubtreesReducer.TargetParameter.ActualName = TotalNumberOfPrunedSubtreesParameterName;
249
250      prunedTreesReducer = new DataReducer();
251      prunedTreesReducer.ParameterToReduce.ActualName = PruningOperator.PrunedTreesParameter.ActualName;
252      prunedTreesReducer.ReductionOperation.Value = new ReductionOperation(ReductionOperations.Sum);
253      prunedTreesReducer.TargetOperation.Value = new ReductionOperation(ReductionOperations.Assign);
254      prunedTreesReducer.TargetParameter.ActualName = TotalNumberOfPrunedTreesParameterName;
255
256      valuesCollector = new DataTableValuesCollector();
257      valuesCollector.CollectedValues.Add(new LookupParameter<IntValue>(TotalNumberOfPrunedSubtreesParameterName));
258      valuesCollector.CollectedValues.Add(new LookupParameter<IntValue>(TotalNumberOfPrunedTreesParameterName));
259      valuesCollector.DataTableParameter.ActualName = "Population pruning";
260
261      resultsCollector = new ResultsCollector();
262      resultsCollector.CollectedValues.Add(new LookupParameter<DataTable>("Population pruning"));
263      resultsCollector.ResultsParameter.ActualName = ResultsParameterName;
264    }
265  }
266}
Note: See TracBrowser for help on using the repository browser.