Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ProblemRefactoring/HeuristicLab.Parameters/3.3/LookupParameter.cs @ 15301

Last change on this file since 15301 was 13404, checked in by abeham, 9 years ago

#2521:

  • Adapted Knapsack problem to new problem infrastructure
  • Introduced additional interfaces in binary vector encoding
  • Improved KnapsackImprovementOperator which requires less evaluated solutions in case of an infeasible start solution

Loosely related change:

  • All LookupParameters are now shown by default
  • Wiring code should make sure that wired parameters are hidden
File size: 9.8 KB
RevLine 
[2756]1#region License Information
2/* HeuristicLab
[12012]3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[2756]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;
[9195]23using System.Threading;
[2756]24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
27
28namespace HeuristicLab.Parameters {
29  /// <summary>
30  /// A parameter whose value is retrieved from the scope.
31  /// </summary>
[3822]32  [Item("LookupParameter", "A parameter whose value is retrieved from or written to a scope.")]
[3017]33  [StorableClass]
[9195]34  public class LookupParameter<T> : Parameter, IStatefulItem, ILookupParameter<T> where T : class, IItem {
[2756]35    [Storable]
36    private string actualName;
37    public string ActualName {
38      get { return actualName; }
39      set {
40        if (value == null) throw new ArgumentNullException();
[5215]41        if (string.IsNullOrWhiteSpace(value)) {
42          actualName = Name;
43          OnActualNameChanged();
44        } else if (!actualName.Equals(value)) {
[2756]45          actualName = value;
46          OnActualNameChanged();
47        }
48      }
49    }
[3687]50    public string TranslatedName {
51      get {
52        string translatedName;
53        GetValueParameterAndTranslateName(out translatedName);
54        return translatedName;
55      }
56    }
[2757]57    public new T ActualValue {
[5193]58      get { return (T)base.ActualValue; }
59      set { base.ActualValue = value; }
[2756]60    }
61
[9195]62    private Lazy<ThreadLocal<IItem>> cachedActualValues;
63    private IItem CachedActualValue {
64      get { return cachedActualValues.Value.Value; }
65    }
66
67    private Lazy<ThreadLocal<IExecutionContext>> executionContexts;
68    public IExecutionContext ExecutionContext {
69      get { return executionContexts.Value.Value; }
70      set {
71        if (value != executionContexts.Value.Value) {
72          executionContexts.Value.Value = value;
73          cachedActualValues.Value.Value = null;
74        }
75      }
76    }
77
[4722]78    [StorableConstructor]
[9195]79    protected LookupParameter(bool deserializing)
80      : base(deserializing) {
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    }
[4722]84    protected LookupParameter(LookupParameter<T> original, Cloner cloner)
85      : base(original, cloner) {
86      actualName = original.actualName;
[13404]87      this.Hidden = original.Hidden;
[9195]88      cachedActualValues = new Lazy<ThreadLocal<IItem>>(() => { return new ThreadLocal<IItem>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
89      executionContexts = new Lazy<ThreadLocal<IExecutionContext>>(() => { return new ThreadLocal<IExecutionContext>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
[4722]90    }
[2756]91    public LookupParameter()
92      : base("Anonymous", typeof(T)) {
[3080]93      this.actualName = Name;
[13404]94      this.Hidden = false;
[9195]95      cachedActualValues = new Lazy<ThreadLocal<IItem>>(() => { return new ThreadLocal<IItem>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
96      executionContexts = new Lazy<ThreadLocal<IExecutionContext>>(() => { return new ThreadLocal<IExecutionContext>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
[2756]97    }
98    public LookupParameter(string name)
99      : base(name, typeof(T)) {
[3080]100      this.actualName = Name;
[13404]101      this.Hidden = false;
[9195]102      cachedActualValues = new Lazy<ThreadLocal<IItem>>(() => { return new ThreadLocal<IItem>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
103      executionContexts = new Lazy<ThreadLocal<IExecutionContext>>(() => { return new ThreadLocal<IExecutionContext>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
[2756]104    }
105    public LookupParameter(string name, string description)
106      : base(name, description, typeof(T)) {
[3080]107      this.actualName = Name;
[13404]108      this.Hidden = false;
[9195]109      cachedActualValues = new Lazy<ThreadLocal<IItem>>(() => { return new ThreadLocal<IItem>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
110      executionContexts = new Lazy<ThreadLocal<IExecutionContext>>(() => { return new ThreadLocal<IExecutionContext>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
[2756]111    }
[3080]112    public LookupParameter(string name, string description, string actualName)
113      : base(name, description, typeof(T)) {
[5215]114      this.actualName = string.IsNullOrWhiteSpace(actualName) ? Name : actualName;
[13404]115      this.Hidden = false;
[9195]116      cachedActualValues = new Lazy<ThreadLocal<IItem>>(() => { return new ThreadLocal<IItem>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
117      executionContexts = new Lazy<ThreadLocal<IExecutionContext>>(() => { return new ThreadLocal<IExecutionContext>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
[3080]118    }
[2756]119
120    public override IDeepCloneable Clone(Cloner cloner) {
[4722]121      return new LookupParameter<T>(this, cloner);
[2756]122    }
123
124    public override string ToString() {
[3688]125      if (Name.Equals(ActualName))
126        return Name;
127      else
128        return Name + ": " + ActualName;
[2756]129    }
130
[3075]131    private IValueParameter GetValueParameterAndTranslateName(out string actualName) {
132      IValueParameter valueParam;
133      ILookupParameter lookupParam;
134      IExecutionContext currentExecutionContext = ExecutionContext;
[2773]135
[3075]136      actualName = Name;
137      while (currentExecutionContext != null) {
138        valueParam = currentExecutionContext.Parameters[actualName] as IValueParameter;
139        lookupParam = currentExecutionContext.Parameters[actualName] as ILookupParameter;
[2773]140
[3075]141        if ((valueParam == null) && (lookupParam == null))
142          throw new InvalidOperationException(
143            string.Format("Parameter look-up chain broken. Parameter \"{0}\" is not an \"{1}\" or an \"{2}\".",
144                          actualName, typeof(IValueParameter).GetPrettyName(), typeof(ILookupParameter).GetPrettyName())
145          );
[2773]146
[3075]147        if (valueParam != null) {
148          if (valueParam.Value != null) return valueParam;
149          else if (lookupParam == null) return valueParam;
[2773]150        }
[3075]151        if (lookupParam != null) actualName = lookupParam.ActualName;
152
153        currentExecutionContext = currentExecutionContext.Parent;
154        while ((currentExecutionContext != null) && !currentExecutionContext.Parameters.ContainsKey(actualName))
155          currentExecutionContext = currentExecutionContext.Parent;
[2773]156      }
157      return null;
158    }
[2756]159    private IVariable LookupVariable(string name) {
160      IScope scope = ExecutionContext.Scope;
161      while ((scope != null) && !scope.Variables.ContainsKey(name))
162        scope = scope.Parent;
[3077]163      return scope != null ? scope.Variables[name] : null;
[2756]164    }
[2757]165    protected override IItem GetActualValue() {
[9195]166      if (CachedActualValue != null) return CachedActualValue;
[2773]167      string name;
[2805]168      // try to get value from context stack
[3075]169      IValueParameter param = GetValueParameterAndTranslateName(out name);
[3091]170      if (param != null) return param.Value;
[2805]171
172      // try to get variable from scope
173      IVariable var = LookupVariable(name);
174      if (var != null) {
[2852]175        if (!(var.Value is T))
[2805]176          throw new InvalidOperationException(
177            string.Format("Type mismatch. Variable \"{0}\" does not contain a \"{1}\".",
178                          name,
179                          typeof(T).GetPrettyName())
180          );
[9195]181        cachedActualValues.Value.Value = var.Value;
[2852]182        return var.Value;
[2756]183      }
184      return null;
185    }
[2757]186    protected override void SetActualValue(IItem value) {
[2852]187      if (!(value is T))
[2757]188        throw new InvalidOperationException(
189          string.Format("Type mismatch. Value is not a \"{0}\".",
190                        typeof(T).GetPrettyName())
191        );
[9195]192      cachedActualValues.Value.Value = value;
193
[2805]194      // try to set value in context stack
[2773]195      string name;
[3075]196      IValueParameter param = GetValueParameterAndTranslateName(out name);
[2805]197      if (param != null) {
[2852]198        param.Value = value;
[2805]199        return;
[2773]200      }
[2805]201
202      // try to set value in scope
203      IVariable var = LookupVariable(name);
204      if (var != null) {
[2852]205        var.Value = value;
[2805]206        return;
207      }
208
209      // create new variable
210      ExecutionContext.Scope.Variables.Add(new Variable(name, value));
[2756]211    }
212
[9195]213    public virtual void InitializeState() {
214    }
215    public virtual void ClearState() {
216      if (cachedActualValues.IsValueCreated) {
217        cachedActualValues.Value.Dispose();
218        cachedActualValues = new Lazy<ThreadLocal<IItem>>(() => { return new ThreadLocal<IItem>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
219      }
220      if (executionContexts.IsValueCreated) {
221        executionContexts.Value.Dispose();
222        executionContexts = new Lazy<ThreadLocal<IExecutionContext>>(() => { return new ThreadLocal<IExecutionContext>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
223      }
224    }
225
[2756]226    public event EventHandler ActualNameChanged;
[4332]227    protected virtual void OnActualNameChanged() {
228      EventHandler handler = ActualNameChanged;
229      if (handler != null) handler(this, EventArgs.Empty);
[2932]230      OnToStringChanged();
[2756]231    }
232  }
233}
Note: See TracBrowser for help on using the repository browser.