Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Analysis/3.3/BestScopeSolutionAnalyzer.cs @ 11615

Last change on this file since 11615 was 11615, checked in by mkommend, 9 years ago

#2249: Refactored best scope solution analyzer.

File size: 5.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2014 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;
23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Operators;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32
33namespace HeuristicLab.Analysis {
34  /// <summary>
35  /// An operator that extracts (clones) the scope containing the best quality.
36  /// </summary>
37  [Item("BestScopeSolutionAnalyzer", "An operator that extracts the scope containing the best quality.")]
38  [StorableClass]
39  public class BestScopeSolutionAnalyzer : SingleSuccessorOperator, IAnalyzer {
40    private const string BestSolutionResultName = "Best Solution";
41
42    public virtual bool EnabledByDefault {
43      get { return true; }
44    }
45    public LookupParameter<BoolValue> MaximizationParameter {
46      get { return (LookupParameter<BoolValue>)Parameters["Maximization"]; }
47    }
48    public ScopeTreeLookupParameter<DoubleValue> QualityParameter {
49      get { return (ScopeTreeLookupParameter<DoubleValue>)Parameters["Quality"]; }
50    }
51    public ILookupParameter<DoubleValue> BestKnownQualityParameter {
52      get { return (ILookupParameter<DoubleValue>)Parameters["BestKnownQuality"]; }
53    }
54    public IValueLookupParameter<ResultCollection> ResultsParameter {
55      get { return (IValueLookupParameter<ResultCollection>)Parameters["Results"]; }
56    }
57
58    #region Storing & Cloning
59    [StorableConstructor]
60    protected BestScopeSolutionAnalyzer(bool deserializing) : base(deserializing) { }
61    protected BestScopeSolutionAnalyzer(BestScopeSolutionAnalyzer original, Cloner cloner) : base(original, cloner) { }
62    public override IDeepCloneable Clone(Cloner cloner) {
63      return new BestScopeSolutionAnalyzer(this, cloner);
64    }
65    #endregion
66    public BestScopeSolutionAnalyzer()
67      : base() {
68      Parameters.Add(new LookupParameter<BoolValue>("Maximization", "True if the problem is a maximization problem."));
69      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("Quality", "The qualities of the solutions."));
70      Parameters.Add(new LookupParameter<DoubleValue>("BestKnownQuality", "The quality of the best known solution."));
71      Parameters.Add(new ValueLookupParameter<ResultCollection>("Results", "The result collection where the solution should be stored."));
72    }
73
74    public override IOperation Apply() {
75      ItemArray<DoubleValue> qualities = QualityParameter.ActualValue;
76      ResultCollection results = ResultsParameter.ActualValue;
77      bool max = MaximizationParameter.ActualValue.Value;
78      DoubleValue bestKnownQuality = BestKnownQualityParameter.ActualValue;
79
80      if (results.ContainsKey(BestSolutionResultName) && !typeof(IScope).IsAssignableFrom(results[BestSolutionResultName].DataType)) {
81        throw new InvalidOperationException(string.Format("Could not add best solution result, because there is already a result with the name \"{0}\" present in the result collecdtion.", BestSolutionResultName));
82      }
83
84      int i = -1;
85      if (!max)
86        i = qualities.Select((x, index) => new { index, x.Value }).OrderBy(x => x.Value).First().index;
87      else i = qualities.Select((x, index) => new { index, x.Value }).OrderByDescending(x => x.Value).First().index;
88
89      IEnumerable<IScope> scopes = new IScope[] { ExecutionContext.Scope };
90      for (int j = 0; j < QualityParameter.Depth; j++)
91        scopes = scopes.SelectMany(x => x.SubScopes);
92      IScope currentBestScope = scopes.ToList()[i];
93
94      if (bestKnownQuality == null ||
95          max && qualities[i].Value > bestKnownQuality.Value
96          || !max && qualities[i].Value < bestKnownQuality.Value) {
97        BestKnownQualityParameter.ActualValue = new DoubleValue(qualities[i].Value);
98      }
99
100      if (!results.ContainsKey(BestSolutionResultName)) {
101        var cloner = new Cloner();
102        //avoid cloning of subscopes
103        cloner.RegisterClonedObject(currentBestScope.SubScopes, new ScopeList());
104        var solution = cloner.Clone(currentBestScope);
105
106        results.Add(new Result(BestSolutionResultName, solution));
107      } else {
108        var bestSolution = (IScope)results[BestSolutionResultName].Value;
109        string qualityName = QualityParameter.TranslatedName;
110        if (bestSolution.Variables.ContainsKey(qualityName)) {
111          double bestQuality = ((DoubleValue)bestSolution.Variables[qualityName].Value).Value;
112          if (max && qualities[i].Value > bestQuality
113              || !max && qualities[i].Value < bestQuality) {
114            var cloner = new Cloner();
115            //avoid cloning of subscopes
116            cloner.RegisterClonedObject(currentBestScope.SubScopes, new ScopeList());
117            var solution = cloner.Clone(currentBestScope);
118
119            results[BestSolutionResultName].Value = solution;
120          }
121        }
122      }
123      return base.Apply();
124    }
125  }
126}
Note: See TracBrowser for help on using the repository browser.