Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2931_OR-Tools_LP_MIP/HeuristicLab.Parameters/3.3/LookupParameter.cs @ 16752

Last change on this file since 16752 was 16720, checked in by ddorfmei, 6 years ago

#2931: Merged revision(s) 16235-16719 from trunk

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