Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2521: Added context lookup parameter

  • Refactored tests
  • Fixed duplicate GUID
File size: 10.3 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 System.Threading;
24using HEAL.Attic;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27
28namespace HeuristicLab.Parameters {
29  /// <summary>
30  /// A parameter whose value is retrieved from the scope.
31  /// </summary>
32  [Item("LookupParameter", "A parameter whose value is retrieved from or written to a scope.")]
33  [StorableType("84FE5F33-94B8-4E30-B1CB-CD15314FB83B")]
34  public class LookupParameter<T> : Parameter, IStatefulItem, ILookupParameter<T> where T : class, IItem {
35    [Storable]
36    private string actualName;
37    public string ActualName {
38      get { return actualName; }
39      set {
40        if (value == null) throw new ArgumentNullException();
41        if (string.IsNullOrWhiteSpace(value)) {
42          actualName = Name;
43          OnActualNameChanged();
44        } else if (!actualName.Equals(value)) {
45          actualName = value;
46          OnActualNameChanged();
47        }
48      }
49    }
50    public string TranslatedName {
51      get {
52        string translatedName = Name;
53        GetValueParameterAndTranslateName(ExecutionContext, ref translatedName);
54        return translatedName;
55      }
56    }
57    public new T ActualValue {
58      get { return (T)base.ActualValue; }
59      set { base.ActualValue = value; }
60    }
61
62    private Lazy<ThreadLocal<IItem>> cachedActualValues;
63    protected IItem CachedActualValue {
64      get { return cachedActualValues.Value.Value; }
65      set { cachedActualValues.Value.Value = value; }
66    }
67
68    private Lazy<ThreadLocal<IExecutionContext>> executionContexts;
69    public IExecutionContext ExecutionContext {
70      get { return executionContexts.Value.Value; }
71      set {
72        if (value != executionContexts.Value.Value) {
73          executionContexts.Value.Value = value;
74          cachedActualValues.Value.Value = null;
75        }
76      }
77    }
78
79    [StorableConstructor]
80    protected LookupParameter(StorableConstructorFlag _) : base(_) {
81      cachedActualValues = new Lazy<ThreadLocal<IItem>>(() => { return new ThreadLocal<IItem>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
82      executionContexts = new Lazy<ThreadLocal<IExecutionContext>>(() => { return new ThreadLocal<IExecutionContext>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
83    }
84    protected LookupParameter(LookupParameter<T> original, Cloner cloner)
85      : base(original, cloner) {
86      actualName = original.actualName;
87      this.Hidden = original.Hidden;
88      cachedActualValues = new Lazy<ThreadLocal<IItem>>(() => { return new ThreadLocal<IItem>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
89      executionContexts = new Lazy<ThreadLocal<IExecutionContext>>(() => { return new ThreadLocal<IExecutionContext>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
90    }
91    public LookupParameter()
92      : base("Anonymous", typeof(T)) {
93      this.actualName = Name;
94      this.Hidden = false;
95      cachedActualValues = new Lazy<ThreadLocal<IItem>>(() => { return new ThreadLocal<IItem>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
96      executionContexts = new Lazy<ThreadLocal<IExecutionContext>>(() => { return new ThreadLocal<IExecutionContext>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
97    }
98    public LookupParameter(string name)
99      : base(name, typeof(T)) {
100      this.actualName = Name;
101      this.Hidden = false;
102      cachedActualValues = new Lazy<ThreadLocal<IItem>>(() => { return new ThreadLocal<IItem>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
103      executionContexts = new Lazy<ThreadLocal<IExecutionContext>>(() => { return new ThreadLocal<IExecutionContext>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
104    }
105    public LookupParameter(string name, string description)
106      : base(name, description, typeof(T)) {
107      this.actualName = Name;
108      this.Hidden = false;
109      cachedActualValues = new Lazy<ThreadLocal<IItem>>(() => { return new ThreadLocal<IItem>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
110      executionContexts = new Lazy<ThreadLocal<IExecutionContext>>(() => { return new ThreadLocal<IExecutionContext>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
111    }
112    public LookupParameter(string name, string description, string actualName)
113      : base(name, description, typeof(T)) {
114      this.actualName = string.IsNullOrWhiteSpace(actualName) ? Name : actualName;
115      this.Hidden = false;
116      cachedActualValues = new Lazy<ThreadLocal<IItem>>(() => { return new ThreadLocal<IItem>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
117      executionContexts = new Lazy<ThreadLocal<IExecutionContext>>(() => { return new ThreadLocal<IExecutionContext>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
118    }
119
120    public override IDeepCloneable Clone(Cloner cloner) {
121      return new LookupParameter<T>(this, cloner);
122    }
123
124    public override string ToString() {
125      if (Name.Equals(ActualName))
126        return Name;
127      else
128        return Name + ": " + ActualName;
129    }
130
131    protected static IValueParameter GetValueParameterAndTranslateName(IExecutionContext executionContext, ref string translatedName) {
132      IValueParameter valueParam;
133      ILookupParameter lookupParam;
134      IExecutionContext currentExecutionContext = executionContext;
135
136      while (currentExecutionContext != null) {
137        IParameter param = null;
138        while (currentExecutionContext != null && (!currentExecutionContext.Parameters.TryGetValue(translatedName, out param)
139          || param is IContextLookupParameter))
140          currentExecutionContext = currentExecutionContext.Parent;
141        if (currentExecutionContext == null) break;
142
143        valueParam = param as IValueParameter;
144        lookupParam = param as ILookupParameter;
145
146        if (valueParam == null && lookupParam == null)
147          throw new InvalidOperationException(
148            string.Format("Parameter look-up chain broken. Parameter \"{0}\" is neither an \"{1}\" nor an \"{2}\".",
149                          translatedName, typeof(IValueParameter).GetPrettyName(), typeof(ILookupParameter).GetPrettyName())
150          );
151
152        if (valueParam != null) {
153          if (valueParam.Value != null) return valueParam;
154          else if (lookupParam == null) return valueParam;
155        }
156        translatedName = lookupParam.ActualName;
157
158        currentExecutionContext = currentExecutionContext.Parent;
159      }
160      return null;
161    }
162    protected static IVariable LookupVariable(IScope scope, string name) {
163      IVariable variable = null;
164      while (scope != null && !scope.Variables.TryGetValue(name, out variable))
165        scope = scope.Parent;
166      return scope != null ? variable : null;
167    }
168
169    protected override IItem GetActualValue() {
170      if (CachedActualValue != null) return CachedActualValue;
171
172      string translatedName = Name;
173      var value = GetValue(ExecutionContext, ref translatedName);
174      if (value != null && !(value is T))
175        throw new InvalidOperationException(
176          string.Format("Type mismatch. Variable \"{0}\" does not contain a \"{1}\".",
177                        translatedName,
178                        typeof(T).GetPrettyName())
179        );
180      CachedActualValue = value;
181      return value;
182    }
183
184    protected static IItem GetValue(IExecutionContext executionContext, ref string name) {
185      // try to get value from context stack
186      IValueParameter param = GetValueParameterAndTranslateName(executionContext, ref name);
187      if (param != null) return param.Value;
188
189      // try to get variable from scope
190      IVariable var = LookupVariable(executionContext.Scope, name);
191      return var != null ? var.Value : null;
192    }
193
194    protected override void SetActualValue(IItem value) {
195      if (!(value is T))
196        throw new InvalidOperationException(
197          string.Format("Type mismatch. Value is not a \"{0}\".",
198                        typeof(T).GetPrettyName())
199        );
200      CachedActualValue = value;
201
202      string translatedName = Name;
203      SetValue(ExecutionContext, ref translatedName, value);
204    }
205
206    protected static void SetValue(IExecutionContext executionContext, ref string name, IItem value) {
207      // try to set value in context stack
208      IValueParameter param = GetValueParameterAndTranslateName(executionContext, ref name);
209      if (param != null) {
210        param.Value = value;
211        return;
212      }
213
214      // try to set value in scope
215      IVariable var = LookupVariable(executionContext.Scope, name);
216      if (var != null) {
217        var.Value = value;
218        return;
219      }
220
221      // create new variable
222      executionContext.Scope.Variables.Add(new Variable(name, value));
223    }
224
225    public virtual void InitializeState() {
226    }
227    public virtual void ClearState() {
228      if (cachedActualValues.IsValueCreated) {
229        cachedActualValues.Value.Dispose();
230        cachedActualValues = new Lazy<ThreadLocal<IItem>>(() => { return new ThreadLocal<IItem>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
231      }
232      if (executionContexts.IsValueCreated) {
233        executionContexts.Value.Dispose();
234        executionContexts = new Lazy<ThreadLocal<IExecutionContext>>(() => { return new ThreadLocal<IExecutionContext>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
235      }
236    }
237
238    public event EventHandler ActualNameChanged;
239    protected virtual void OnActualNameChanged() {
240      EventHandler handler = ActualNameChanged;
241      if (handler != null) handler(this, EventArgs.Empty);
242      OnToStringChanged();
243    }
244  }
245}
Note: See TracBrowser for help on using the repository browser.