Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 13234 was 12009, checked in by ascheibe, 10 years ago

#2212 updated copyright year

File size: 7.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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, ISingleObjectiveOperator {
40
41    public virtual bool EnabledByDefault {
42      get { return true; }
43    }
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    }
50    public IFixedValueParameter<StringValue> BestSolutionResultNameParameter {
51      get { return (IFixedValueParameter<StringValue>)Parameters["BestSolution ResultName"]; }
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
60    public string BestSolutionResultName {
61      get { return BestSolutionResultNameParameter.Value.Value; }
62      set { BestSolutionResultNameParameter.Value.Value = value; }
63    }
64
65    #region Storing & Cloning
66    [StorableConstructor]
67    protected BestScopeSolutionAnalyzer(bool deserializing) : base(deserializing) { }
68    protected BestScopeSolutionAnalyzer(BestScopeSolutionAnalyzer original, Cloner cloner) : base(original, cloner) { }
69    public override IDeepCloneable Clone(Cloner cloner) {
70      return new BestScopeSolutionAnalyzer(this, cloner);
71    }
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    }
83    #endregion
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."));
88      Parameters.Add(new FixedValueParameter<StringValue>("BestSolution ResultName", "The name of the result for storing the best solution.", new StringValue("Best Solution")));
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
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
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;
107
108      IEnumerable<IScope> scopes = new IScope[] { ExecutionContext.Scope };
109      for (int j = 0; j < QualityParameter.Depth; j++)
110        scopes = scopes.SelectMany(x => x.SubScopes);
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
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));
127      } else {
128        var bestSolution = (IScope)results[BestSolutionResultName].Value;
129        string qualityName = QualityParameter.TranslatedName;
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;
141          }
142        }
143      }
144      return base.Apply();
145    }
146  }
147}
Note: See TracBrowser for help on using the repository browser.