Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 14728 was 14185, checked in by swagner, 8 years ago

#2526: Updated year of copyrights in license headers

File size: 10.3 KB
RevLine 
[2756]1#region License Information
2/* HeuristicLab
[14185]3 * Copyright (C) 2002-2016 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 {
[14037]52        string translatedName = Name;
53        GetValueParameterAndTranslateName(ExecutionContext, ref translatedName);
[3687]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;
[14037]63    protected IItem CachedActualValue {
[9195]64      get { return cachedActualValues.Value.Value; }
[14037]65      set { cachedActualValues.Value.Value = value; }
[9195]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
[4722]79    [StorableConstructor]
[9195]80    protected LookupParameter(bool deserializing)
81      : base(deserializing) {
82      cachedActualValues = new Lazy<ThreadLocal<IItem>>(() => { return new ThreadLocal<IItem>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
83      executionContexts = new Lazy<ThreadLocal<IExecutionContext>>(() => { return new ThreadLocal<IExecutionContext>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
84    }
[4722]85    protected LookupParameter(LookupParameter<T> original, Cloner cloner)
86      : base(original, cloner) {
87      actualName = original.actualName;
[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;
[5784]94      this.Hidden = true;
[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;
[5784]101      this.Hidden = true;
[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;
[5784]108      this.Hidden = true;
[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;
[5784]115      this.Hidden = true;
[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
[14037]131    protected static IValueParameter GetValueParameterAndTranslateName(IExecutionContext executionContext, ref string translatedName) {
[3075]132      IValueParameter valueParam;
133      ILookupParameter lookupParam;
[14037]134      IExecutionContext currentExecutionContext = executionContext;
[2773]135
[3075]136      while (currentExecutionContext != null) {
[14056]137        IParameter param = null;
138        while (currentExecutionContext != null && !currentExecutionContext.Parameters.TryGetValue(translatedName, out param))
139          currentExecutionContext = currentExecutionContext.Parent;
140        if (currentExecutionContext == null) break;
[2773]141
[14056]142        valueParam = param as IValueParameter;
143        lookupParam = param as ILookupParameter;
144
[3075]145        if ((valueParam == null) && (lookupParam == null))
146          throw new InvalidOperationException(
147            string.Format("Parameter look-up chain broken. Parameter \"{0}\" is not an \"{1}\" or an \"{2}\".",
[14037]148                          translatedName, typeof(IValueParameter).GetPrettyName(), typeof(ILookupParameter).GetPrettyName())
[3075]149          );
[2773]150
[3075]151        if (valueParam != null) {
152          if (valueParam.Value != null) return valueParam;
153          else if (lookupParam == null) return valueParam;
[2773]154        }
[14056]155        translatedName = lookupParam.ActualName;
[3075]156
157        currentExecutionContext = currentExecutionContext.Parent;
[2773]158      }
159      return null;
160    }
[14037]161    protected static IVariable LookupVariable(IScope scope, string name) {
[14056]162      IVariable variable = null;
163      while (scope != null && !scope.Variables.TryGetValue(name, out variable))
[2756]164        scope = scope.Parent;
[14056]165      return scope != null ? variable : null;
[2756]166    }
[14037]167
[2757]168    protected override IItem GetActualValue() {
[9195]169      if (CachedActualValue != null) return CachedActualValue;
[14037]170
171      string translatedName = Name;
172      var value = GetValue(ExecutionContext, ref translatedName);
[14057]173      if (value != null && !(value is T))
174        throw new InvalidOperationException(
175          string.Format("Type mismatch. Variable \"{0}\" does not contain a \"{1}\".",
176                        translatedName,
177                        typeof(T).GetPrettyName())
178        );
[14037]179      CachedActualValue = value;
180      return value;
181    }
182
[14057]183    protected static IItem GetValue(IExecutionContext executionContext, ref string name) {
[2805]184      // try to get value from context stack
[14037]185      IValueParameter param = GetValueParameterAndTranslateName(executionContext, ref name);
[3091]186      if (param != null) return param.Value;
[2805]187
188      // try to get variable from scope
[14037]189      IVariable var = LookupVariable(executionContext.Scope, name);
[14057]190      return var != null ? var.Value : null;
[2756]191    }
[14037]192
[2757]193    protected override void SetActualValue(IItem value) {
[2852]194      if (!(value is T))
[2757]195        throw new InvalidOperationException(
196          string.Format("Type mismatch. Value is not a \"{0}\".",
197                        typeof(T).GetPrettyName())
198        );
[14037]199      CachedActualValue = value;
[9195]200
[14037]201      string translatedName = Name;
202      SetValue(ExecutionContext, ref translatedName, value);
203    }
204
205    protected static void SetValue(IExecutionContext executionContext, ref string name, IItem value) {
[2805]206      // try to set value in context stack
[14037]207      IValueParameter param = GetValueParameterAndTranslateName(executionContext, ref name);
[2805]208      if (param != null) {
[2852]209        param.Value = value;
[2805]210        return;
[2773]211      }
[2805]212
213      // try to set value in scope
[14037]214      IVariable var = LookupVariable(executionContext.Scope, name);
[2805]215      if (var != null) {
[2852]216        var.Value = value;
[2805]217        return;
218      }
219
220      // create new variable
[14037]221      executionContext.Scope.Variables.Add(new Variable(name, value));
[2756]222    }
223
[9195]224    public virtual void InitializeState() {
225    }
226    public virtual void ClearState() {
227      if (cachedActualValues.IsValueCreated) {
228        cachedActualValues.Value.Dispose();
229        cachedActualValues = new Lazy<ThreadLocal<IItem>>(() => { return new ThreadLocal<IItem>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
230      }
231      if (executionContexts.IsValueCreated) {
232        executionContexts.Value.Dispose();
233        executionContexts = new Lazy<ThreadLocal<IExecutionContext>>(() => { return new ThreadLocal<IExecutionContext>(); }, LazyThreadSafetyMode.ExecutionAndPublication);
234      }
235    }
236
[2756]237    public event EventHandler ActualNameChanged;
[4332]238    protected virtual void OnActualNameChanged() {
239      EventHandler handler = ActualNameChanged;
240      if (handler != null) handler(this, EventArgs.Empty);
[2932]241      OnToStringChanged();
[2756]242    }
243  }
244}
Note: See TracBrowser for help on using the repository browser.