Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ALPS/HeuristicLab.Analysis/3.3/BestScopeSolutionAnalyzer.cs @ 11677

Last change on this file since 11677 was 11677, checked in by pfleck, 9 years ago

#2269 Merged trunk. Updated .net version of ALPS plugin.

File size: 6.5 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
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      if (!Parameters.ContainsKey("BestSolution ResultName"))
76        Parameters.Add(new FixedValueParameter<StringValue>("BestSolution ResultName", "The name of the result for storing the best solution.", new StringValue("Best Solution")));
77    }
78    #endregion
79    public BestScopeSolutionAnalyzer()
80      : base() {
81      Parameters.Add(new LookupParameter<BoolValue>("Maximization", "True if the problem is a maximization problem."));
82      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("Quality", "The qualities of the solutions."));
83      Parameters.Add(new FixedValueParameter<StringValue>("BestSolution ResultName", "The name of the result for storing the best solution.", new StringValue("Best Solution")));
84      Parameters.Add(new LookupParameter<DoubleValue>("BestKnownQuality", "The quality of the best known solution."));
85      Parameters.Add(new ValueLookupParameter<ResultCollection>("Results", "The result collection where the solution should be stored."));
86    }
87
88    public override IOperation Apply() {
89      ItemArray<DoubleValue> qualities = QualityParameter.ActualValue;
90      ResultCollection results = ResultsParameter.ActualValue;
91      bool max = MaximizationParameter.ActualValue.Value;
92      DoubleValue bestKnownQuality = BestKnownQualityParameter.ActualValue;
93
94      if (results.ContainsKey(BestSolutionResultName) && !typeof(IScope).IsAssignableFrom(results[BestSolutionResultName].DataType)) {
95        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));
96      }
97
98      int i = -1;
99      if (!max)
100        i = qualities.Select((x, index) => new { index, x.Value }).OrderBy(x => x.Value).First().index;
101      else i = qualities.Select((x, index) => new { index, x.Value }).OrderByDescending(x => x.Value).First().index;
102
103      IEnumerable<IScope> scopes = new IScope[] { ExecutionContext.Scope };
104      for (int j = 0; j < QualityParameter.Depth; j++)
105        scopes = scopes.SelectMany(x => x.SubScopes);
106      IScope currentBestScope = scopes.ToList()[i];
107
108      if (bestKnownQuality == null ||
109          max && qualities[i].Value > bestKnownQuality.Value
110          || !max && qualities[i].Value < bestKnownQuality.Value) {
111        BestKnownQualityParameter.ActualValue = new DoubleValue(qualities[i].Value);
112      }
113
114      if (!results.ContainsKey(BestSolutionResultName)) {
115        var cloner = new Cloner();
116        //avoid cloning of subscopes
117        cloner.RegisterClonedObject(currentBestScope.SubScopes, new ScopeList());
118        var solution = cloner.Clone(currentBestScope);
119
120        results.Add(new Result(BestSolutionResultName, solution));
121      } else {
122        var bestSolution = (IScope)results[BestSolutionResultName].Value;
123        string qualityName = QualityParameter.TranslatedName;
124        if (bestSolution.Variables.ContainsKey(qualityName)) {
125          double bestQuality = ((DoubleValue)bestSolution.Variables[qualityName].Value).Value;
126          if (max && qualities[i].Value > bestQuality
127              || !max && qualities[i].Value < bestQuality) {
128            var cloner = new Cloner();
129            //avoid cloning of subscopes
130            cloner.RegisterClonedObject(currentBestScope.SubScopes, new ScopeList());
131            var solution = cloner.Clone(currentBestScope);
132
133            results[BestSolutionResultName].Value = solution;
134          }
135        }
136      }
137      return base.Apply();
138    }
139  }
140}
Note: See TracBrowser for help on using the repository browser.