Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Parameters/3.3/LookupParameter.cs @ 11552

Last change on this file since 11552 was 11171, checked in by ascheibe, 10 years ago

#2115 merged r11170 (copyright update) into trunk

File size: 9.7 KB
RevLine 
[2756]1#region License Information
2/* HeuristicLab
[11171]3 * Copyright (C) 2002-2014 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;
[9195]87      cachedActualValues = new Lazy<ThreadLocal<IItem>>(() => { return new ThreadLocal<IItem>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
88      executionContexts = new Lazy<ThreadLocal<IExecutionContext>>(() => { return new ThreadLocal<IExecutionContext>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
[4722]89    }
[2756]90    public LookupParameter()
91      : base("Anonymous", typeof(T)) {
[3080]92      this.actualName = Name;
[5784]93      this.Hidden = true;
[9195]94      cachedActualValues = new Lazy<ThreadLocal<IItem>>(() => { return new ThreadLocal<IItem>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
95      executionContexts = new Lazy<ThreadLocal<IExecutionContext>>(() => { return new ThreadLocal<IExecutionContext>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
[2756]96    }
97    public LookupParameter(string name)
98      : base(name, typeof(T)) {
[3080]99      this.actualName = Name;
[5784]100      this.Hidden = true;
[9195]101      cachedActualValues = new Lazy<ThreadLocal<IItem>>(() => { return new ThreadLocal<IItem>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
102      executionContexts = new Lazy<ThreadLocal<IExecutionContext>>(() => { return new ThreadLocal<IExecutionContext>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
[2756]103    }
104    public LookupParameter(string name, string description)
105      : base(name, description, typeof(T)) {
[3080]106      this.actualName = Name;
[5784]107      this.Hidden = true;
[9195]108      cachedActualValues = new Lazy<ThreadLocal<IItem>>(() => { return new ThreadLocal<IItem>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
109      executionContexts = new Lazy<ThreadLocal<IExecutionContext>>(() => { return new ThreadLocal<IExecutionContext>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
[2756]110    }
[3080]111    public LookupParameter(string name, string description, string actualName)
112      : base(name, description, typeof(T)) {
[5215]113      this.actualName = string.IsNullOrWhiteSpace(actualName) ? Name : actualName;
[5784]114      this.Hidden = true;
[9195]115      cachedActualValues = new Lazy<ThreadLocal<IItem>>(() => { return new ThreadLocal<IItem>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
116      executionContexts = new Lazy<ThreadLocal<IExecutionContext>>(() => { return new ThreadLocal<IExecutionContext>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
[3080]117    }
[2756]118
119    public override IDeepCloneable Clone(Cloner cloner) {
[4722]120      return new LookupParameter<T>(this, cloner);
[2756]121    }
122
123    public override string ToString() {
[3688]124      if (Name.Equals(ActualName))
125        return Name;
126      else
127        return Name + ": " + ActualName;
[2756]128    }
129
[3075]130    private IValueParameter GetValueParameterAndTranslateName(out string actualName) {
131      IValueParameter valueParam;
132      ILookupParameter lookupParam;
133      IExecutionContext currentExecutionContext = ExecutionContext;
[2773]134
[3075]135      actualName = Name;
136      while (currentExecutionContext != null) {
137        valueParam = currentExecutionContext.Parameters[actualName] as IValueParameter;
138        lookupParam = currentExecutionContext.Parameters[actualName] as ILookupParameter;
[2773]139
[3075]140        if ((valueParam == null) && (lookupParam == null))
141          throw new InvalidOperationException(
142            string.Format("Parameter look-up chain broken. Parameter \"{0}\" is not an \"{1}\" or an \"{2}\".",
143                          actualName, typeof(IValueParameter).GetPrettyName(), typeof(ILookupParameter).GetPrettyName())
144          );
[2773]145
[3075]146        if (valueParam != null) {
147          if (valueParam.Value != null) return valueParam;
148          else if (lookupParam == null) return valueParam;
[2773]149        }
[3075]150        if (lookupParam != null) actualName = lookupParam.ActualName;
151
152        currentExecutionContext = currentExecutionContext.Parent;
153        while ((currentExecutionContext != null) && !currentExecutionContext.Parameters.ContainsKey(actualName))
154          currentExecutionContext = currentExecutionContext.Parent;
[2773]155      }
156      return null;
157    }
[2756]158    private IVariable LookupVariable(string name) {
159      IScope scope = ExecutionContext.Scope;
160      while ((scope != null) && !scope.Variables.ContainsKey(name))
161        scope = scope.Parent;
[3077]162      return scope != null ? scope.Variables[name] : null;
[2756]163    }
[2757]164    protected override IItem GetActualValue() {
[9195]165      if (CachedActualValue != null) return CachedActualValue;
[2773]166      string name;
[2805]167      // try to get value from context stack
[3075]168      IValueParameter param = GetValueParameterAndTranslateName(out name);
[3091]169      if (param != null) return param.Value;
[2805]170
171      // try to get variable from scope
172      IVariable var = LookupVariable(name);
173      if (var != null) {
[2852]174        if (!(var.Value is T))
[2805]175          throw new InvalidOperationException(
176            string.Format("Type mismatch. Variable \"{0}\" does not contain a \"{1}\".",
177                          name,
178                          typeof(T).GetPrettyName())
179          );
[9195]180        cachedActualValues.Value.Value = var.Value;
[2852]181        return var.Value;
[2756]182      }
183      return null;
184    }
[2757]185    protected override void SetActualValue(IItem value) {
[2852]186      if (!(value is T))
[2757]187        throw new InvalidOperationException(
188          string.Format("Type mismatch. Value is not a \"{0}\".",
189                        typeof(T).GetPrettyName())
190        );
[9195]191      cachedActualValues.Value.Value = value;
192
[2805]193      // try to set value in context stack
[2773]194      string name;
[3075]195      IValueParameter param = GetValueParameterAndTranslateName(out name);
[2805]196      if (param != null) {
[2852]197        param.Value = value;
[2805]198        return;
[2773]199      }
[2805]200
201      // try to set value in scope
202      IVariable var = LookupVariable(name);
203      if (var != null) {
[2852]204        var.Value = value;
[2805]205        return;
206      }
207
208      // create new variable
209      ExecutionContext.Scope.Variables.Add(new Variable(name, value));
[2756]210    }
211
[9195]212    public virtual void InitializeState() {
213    }
214    public virtual void ClearState() {
215      if (cachedActualValues.IsValueCreated) {
216        cachedActualValues.Value.Dispose();
217        cachedActualValues = new Lazy<ThreadLocal<IItem>>(() => { return new ThreadLocal<IItem>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
218      }
219      if (executionContexts.IsValueCreated) {
220        executionContexts.Value.Dispose();
221        executionContexts = new Lazy<ThreadLocal<IExecutionContext>>(() => { return new ThreadLocal<IExecutionContext>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
222      }
223    }
224
[2756]225    public event EventHandler ActualNameChanged;
[4332]226    protected virtual void OnActualNameChanged() {
227      EventHandler handler = ActualNameChanged;
228      if (handler != null) handler(this, EventArgs.Empty);
[2932]229      OnToStringChanged();
[2756]230    }
231  }
232}
Note: See TracBrowser for help on using the repository browser.