Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2521_ProblemRefactoring/HeuristicLab.Parameters/3.3/LookupParameter.cs @ 17257

Last change on this file since 17257 was 17257, checked in by abeham, 5 years ago

#2521: Refactored ContextLookupParameter with suggestions from mkommend

  • Add StorableType attribute to some types
File size: 7.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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 HEAL.Attic;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26
27namespace HeuristicLab.Parameters {
28  /// <summary>
29  /// A parameter whose value is retrieved from the scope.
30  /// </summary>
31  [Item("LookupParameter", "A parameter whose value is retrieved from or written to a scope.")]
32  [StorableType("84FE5F33-94B8-4E30-B1CB-CD15314FB83B")]
33  public class LookupParameter<T> : ContextParameter, ILookupParameter<T> where T : class, IItem {
34    [Storable]
35    private string actualName;
36    public string ActualName {
37      get { return actualName; }
38      set {
39        if (value == null) throw new ArgumentNullException();
40        if (string.IsNullOrWhiteSpace(value)) {
41          actualName = Name;
42          OnActualNameChanged();
43        } else if (!actualName.Equals(value)) {
44          actualName = value;
45          OnActualNameChanged();
46        }
47      }
48    }
49    public string TranslatedName {
50      get {
51        string translatedName = Name;
52        GetValueParameterAndTranslateName(ExecutionContext, ref translatedName);
53        return translatedName;
54      }
55    }
56    public new T ActualValue {
57      get { return (T)base.ActualValue; }
58      set { base.ActualValue = value; }
59    }
60
61    [StorableConstructor]
62    protected LookupParameter(StorableConstructorFlag _) : base(_) { }
63    protected LookupParameter(LookupParameter<T> original, Cloner cloner)
64      : base(original, cloner) {
65      actualName = original.actualName;
66    }
67    public LookupParameter()
68      : base("Anonymous", typeof(T)) {
69      this.actualName = Name;
70    }
71    public LookupParameter(string name)
72      : base(name, typeof(T)) {
73      this.actualName = Name;
74    }
75    public LookupParameter(string name, string description)
76      : base(name, description, typeof(T)) {
77      this.actualName = Name;
78    }
79    public LookupParameter(string name, string description, string actualName)
80      : base(name, description, typeof(T)) {
81      this.actualName = string.IsNullOrWhiteSpace(actualName) ? Name : actualName;
82    }
83
84    public override IDeepCloneable Clone(Cloner cloner) {
85      return new LookupParameter<T>(this, cloner);
86    }
87
88    public override string ToString() {
89      if (Name.Equals(ActualName))
90        return Name;
91      else
92        return Name + ": " + ActualName;
93    }
94
95    protected static IValueParameter GetValueParameterAndTranslateName(IExecutionContext executionContext, ref string translatedName) {
96      IValueParameter valueParam;
97      ILookupParameter lookupParam;
98      IExecutionContext currentExecutionContext = executionContext;
99
100      while (currentExecutionContext != null) {
101        IParameter param = null;
102        while (currentExecutionContext != null && (!currentExecutionContext.Parameters.TryGetValue(translatedName, out param)
103          || param is IContextParameter))
104          currentExecutionContext = currentExecutionContext.Parent;
105        if (currentExecutionContext == null) break;
106
107        valueParam = param as IValueParameter;
108        lookupParam = param as ILookupParameter;
109
110        if (valueParam == null && lookupParam == null)
111          throw new InvalidOperationException(
112            string.Format("Parameter look-up chain broken. Parameter \"{0}\" is neither an \"{1}\" nor an \"{2}\".",
113                          translatedName, typeof(IValueParameter).GetPrettyName(), typeof(ILookupParameter).GetPrettyName())
114          );
115
116        if (valueParam != null) {
117          if (valueParam.Value != null) return valueParam;
118          else if (lookupParam == null) return valueParam;
119        }
120        translatedName = lookupParam.ActualName;
121
122        currentExecutionContext = currentExecutionContext.Parent;
123      }
124      return null;
125    }
126    protected static IVariable LookupVariable(IScope scope, string name) {
127      IVariable variable = null;
128      while (scope != null && !scope.Variables.TryGetValue(name, out variable))
129        scope = scope.Parent;
130      return scope != null ? variable : null;
131    }
132
133    protected override IItem GetActualValueFromContext() {
134      string translatedName = Name;
135      var value = GetValue(ExecutionContext, ref translatedName);
136      if (value != null && !(value is T))
137        throw new InvalidOperationException(
138          string.Format("Type mismatch. Variable \"{0}\" does not contain a \"{1}\".",
139                        translatedName,
140                        typeof(T).GetPrettyName())
141        );
142      return value;
143    }
144
145    protected static IItem GetValue(IExecutionContext executionContext, ref string name) {
146      // try to get value from context stack
147      IValueParameter param = GetValueParameterAndTranslateName(executionContext, ref name);
148      if (param != null) return param.Value;
149
150      // try to get variable from scope
151      IVariable var = LookupVariable(executionContext.Scope, name);
152      return var != null ? var.Value : null;
153    }
154
155    protected override void SetActualValue(IItem value) {
156      if (!(value is T))
157        throw new InvalidOperationException(
158          string.Format("Type mismatch. Value is not a \"{0}\".",
159                        typeof(T).GetPrettyName())
160        );
161      CachedActualValue = value;
162
163      string translatedName = Name;
164      SetValue(ExecutionContext, ref translatedName, value);
165    }
166
167    protected static void SetValue(IExecutionContext executionContext, ref string name, IItem value) {
168      // try to set value in context stack
169      IValueParameter param = GetValueParameterAndTranslateName(executionContext, ref name);
170      if (param != null) {
171        param.Value = value;
172        return;
173      }
174
175      // try to set value in scope
176      IVariable var = LookupVariable(executionContext.Scope, name);
177      if (var != null) {
178        var.Value = value;
179        return;
180      }
181
182      // create new variable
183      executionContext.Scope.Variables.Add(new Variable(name, value));
184    }
185
186    public event EventHandler ActualNameChanged;
187    protected virtual void OnActualNameChanged() {
188      EventHandler handler = ActualNameChanged;
189      if (handler != null) handler(this, EventArgs.Empty);
190      OnToStringChanged();
191    }
192  }
193}
Note: See TracBrowser for help on using the repository browser.