Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Analysis/3.3/BestScopeSolutionAnalyzer.cs @ 18183

Last change on this file since 18183 was 17181, checked in by swagner, 5 years ago

#2875: Merged r17180 from trunk to stable

File size: 7.1 KB
RevLine 
[3872]1#region License Information
2/* HeuristicLab
[17181]3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[3872]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
[11906]22using System;
[3872]23using System.Collections.Generic;
24using System.Linq;
[4722]25using HeuristicLab.Common;
[3872]26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Operators;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
[17097]31using HEAL.Attic;
[3872]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.")]
[17097]38  [StorableType("2E8C2770-B591-4F77-BF1D-E4DB218A2282")]
[12005]39  public class BestScopeSolutionAnalyzer : SingleSuccessorOperator, IAnalyzer, ISingleObjectiveOperator {
[11906]40
[7172]41    public virtual bool EnabledByDefault {
42      get { return true; }
43    }
[3872]44    public LookupParameter<BoolValue> MaximizationParameter {
45      get { return (LookupParameter<BoolValue>)Parameters["Maximization"]; }
46    }
47    public ScopeTreeLookupParameter<DoubleValue> QualityParameter {
48      get { return (ScopeTreeLookupParameter<DoubleValue>)Parameters["Quality"]; }
49    }
[11906]50    public IFixedValueParameter<StringValue> BestSolutionResultNameParameter {
51      get { return (IFixedValueParameter<StringValue>)Parameters["BestSolution ResultName"]; }
[3872]52    }
53    public ILookupParameter<DoubleValue> BestKnownQualityParameter {
54      get { return (ILookupParameter<DoubleValue>)Parameters["BestKnownQuality"]; }
55    }
56    public IValueLookupParameter<ResultCollection> ResultsParameter {
57      get { return (IValueLookupParameter<ResultCollection>)Parameters["Results"]; }
58    }
59
[11906]60    public string BestSolutionResultName {
61      get { return BestSolutionResultNameParameter.Value.Value; }
62      set { BestSolutionResultNameParameter.Value.Value = value; }
63    }
64
[4722]65    #region Storing & Cloning
66    [StorableConstructor]
[17097]67    protected BestScopeSolutionAnalyzer(StorableConstructorFlag _) : base(_) { }
[4722]68    protected BestScopeSolutionAnalyzer(BestScopeSolutionAnalyzer original, Cloner cloner) : base(original, cloner) { }
69    public override IDeepCloneable Clone(Cloner cloner) {
70      return new BestScopeSolutionAnalyzer(this, cloner);
71    }
[11906]72
73    [StorableHook(HookType.AfterDeserialization)]
74    private void AfterDeserialization() {
75      // BackwardsCompatibility3.3
76      #region Backwards compatible code, remove with 3.4
77      if (!Parameters.ContainsKey("BestSolution ResultName"))
78        Parameters.Add(new FixedValueParameter<StringValue>("BestSolution ResultName", "The name of the result for storing the best solution.", new StringValue("Best Solution")));
79      if (Parameters.ContainsKey("BestSolution")) Parameters.Remove("BestSolution");
80      if (Parameters.ContainsKey("BestKnownSolution")) Parameters.Remove("BestKnownSolution");
81      #endregion
82    }
[4722]83    #endregion
[3872]84    public BestScopeSolutionAnalyzer()
85      : base() {
86      Parameters.Add(new LookupParameter<BoolValue>("Maximization", "True if the problem is a maximization problem."));
87      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("Quality", "The qualities of the solutions."));
[11906]88      Parameters.Add(new FixedValueParameter<StringValue>("BestSolution ResultName", "The name of the result for storing the best solution.", new StringValue("Best Solution")));
[3872]89      Parameters.Add(new LookupParameter<DoubleValue>("BestKnownQuality", "The quality of the best known solution."));
90      Parameters.Add(new ValueLookupParameter<ResultCollection>("Results", "The result collection where the solution should be stored."));
91    }
92
93    public override IOperation Apply() {
94      ItemArray<DoubleValue> qualities = QualityParameter.ActualValue;
95      ResultCollection results = ResultsParameter.ActualValue;
96      bool max = MaximizationParameter.ActualValue.Value;
97      DoubleValue bestKnownQuality = BestKnownQualityParameter.ActualValue;
98
[11906]99      if (results.ContainsKey(BestSolutionResultName) && !typeof(IScope).IsAssignableFrom(results[BestSolutionResultName].DataType)) {
100        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 collection.", BestSolutionResultName));
101      }
102
[3901]103      int i = -1;
104      if (!max)
105        i = qualities.Select((x, index) => new { index, x.Value }).OrderBy(x => x.Value).First().index;
106      else i = qualities.Select((x, index) => new { index, x.Value }).OrderByDescending(x => x.Value).First().index;
[7172]107
[3872]108      IEnumerable<IScope> scopes = new IScope[] { ExecutionContext.Scope };
109      for (int j = 0; j < QualityParameter.Depth; j++)
[11906]110        scopes = scopes.SelectMany(x => x.SubScopes);
[3872]111      IScope currentBestScope = scopes.ToList()[i];
112
113      if (bestKnownQuality == null ||
114          max && qualities[i].Value > bestKnownQuality.Value
115          || !max && qualities[i].Value < bestKnownQuality.Value) {
116        BestKnownQualityParameter.ActualValue = new DoubleValue(qualities[i].Value);
117      }
118
[11906]119      if (!results.ContainsKey(BestSolutionResultName)) {
120        var cloner = new Cloner();
121        //avoid cloning of subscopes and the results collection that the solution is put in
122        cloner.RegisterClonedObject(results, new ResultCollection());
123        cloner.RegisterClonedObject(currentBestScope.SubScopes, new ScopeList());
124        var solution = cloner.Clone(currentBestScope);
125
126        results.Add(new Result(BestSolutionResultName, solution));
[3872]127      } else {
[11906]128        var bestSolution = (IScope)results[BestSolutionResultName].Value;
[3872]129        string qualityName = QualityParameter.TranslatedName;
[11906]130        if (bestSolution.Variables.ContainsKey(qualityName)) {
131          double bestQuality = ((DoubleValue)bestSolution.Variables[qualityName].Value).Value;
132          if (max && qualities[i].Value > bestQuality
133              || !max && qualities[i].Value < bestQuality) {
134            var cloner = new Cloner();
135            //avoid cloning of subscopes and the results collection that the solution is put in
136            cloner.RegisterClonedObject(results, new ResultCollection());
137            cloner.RegisterClonedObject(currentBestScope.SubScopes, new ScopeList());
138            var solution = cloner.Clone(currentBestScope);
139
140            results[BestSolutionResultName].Value = solution;
[3872]141          }
142        }
143      }
144      return base.Apply();
145    }
146  }
147}
Note: See TracBrowser for help on using the repository browser.