Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3660 was 3555, checked in by swagner, 14 years ago

Implemented reviewers' comments (#893)

File size: 7.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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 HeuristicLab.Common;
24using HeuristicLab.Core;
25using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
26
27namespace HeuristicLab.Parameters {
28  /// <summary>
29  /// A parameter whose value is retrieved from the scope.
30  /// </summary>
31  [Item("LookupParameter<T>", "A parameter whose value is retrieved from or written to a scope.")]
32  [StorableClass]
33  public class LookupParameter<T> : Parameter, ILookupParameter<T> where T : class, IItem {
34    [Storable]
35    private string actualName;
36    public string ActualName {
37      get { return actualName; }
38      set {
39        if (value == null) throw new ArgumentNullException();
40        if (!actualName.Equals(value)) {
41          actualName = value;
42          OnActualNameChanged();
43        }
44      }
45    }
46    public new T ActualValue {
47      get {
48        if (cachedActualValue == null) cachedActualValue = GetActualValue();
49        return (T)cachedActualValue;
50      }
51      set {
52        cachedActualValue = value;
53        SetActualValue(value);
54      }
55    }
56
57    public LookupParameter()
58      : base("Anonymous", typeof(T)) {
59      this.actualName = Name;
60    }
61    public LookupParameter(string name)
62      : base(name, typeof(T)) {
63      this.actualName = Name;
64    }
65    public LookupParameter(string name, string description)
66      : base(name, description, typeof(T)) {
67      this.actualName = Name;
68    }
69    public LookupParameter(string name, string description, string actualName)
70      : base(name, description, typeof(T)) {
71      this.actualName = actualName == null ? string.Empty : actualName;
72    }
73    [StorableConstructor]
74    protected LookupParameter(bool deserializing) : base(deserializing) { }
75
76    public override IDeepCloneable Clone(Cloner cloner) {
77      LookupParameter<T> clone = (LookupParameter<T>)base.Clone(cloner);
78      clone.actualName = actualName;
79      return clone;
80    }
81
82    public override string ToString() {
83      return string.Format("{0}: {1}", Name, ActualName);
84    }
85
86    private IValueParameter GetValueParameterAndTranslateName(out string actualName) {
87      IValueParameter valueParam;
88      ILookupParameter lookupParam;
89      IExecutionContext currentExecutionContext = ExecutionContext;
90
91      actualName = Name;
92      while (currentExecutionContext != null) {
93        valueParam = currentExecutionContext.Parameters[actualName] as IValueParameter;
94        lookupParam = currentExecutionContext.Parameters[actualName] as ILookupParameter;
95
96        if ((valueParam == null) && (lookupParam == null))
97          throw new InvalidOperationException(
98            string.Format("Parameter look-up chain broken. Parameter \"{0}\" is not an \"{1}\" or an \"{2}\".",
99                          actualName, typeof(IValueParameter).GetPrettyName(), typeof(ILookupParameter).GetPrettyName())
100          );
101
102        if (valueParam != null) {
103          if (valueParam.Value != null) return valueParam;
104          else if (lookupParam == null) return valueParam;
105        }
106        if (lookupParam != null) actualName = lookupParam.ActualName;
107
108        currentExecutionContext = currentExecutionContext.Parent;
109        while ((currentExecutionContext != null) && !currentExecutionContext.Parameters.ContainsKey(actualName))
110          currentExecutionContext = currentExecutionContext.Parent;
111      }
112      return null;
113    }
114    private IVariable LookupVariable(string name) {
115      IScope scope = ExecutionContext.Scope;
116      while ((scope != null) && !scope.Variables.ContainsKey(name))
117        scope = scope.Parent;
118      return scope != null ? scope.Variables[name] : null;
119    }
120    protected override IItem GetActualValue() {
121      string name;
122      // try to get value from context stack
123      IValueParameter param = GetValueParameterAndTranslateName(out name);
124      if (param != null) return param.Value;
125
126      // try to get variable from scope
127      IVariable var = LookupVariable(name);
128      if (var != null) {
129        if (!(var.Value is T))
130          throw new InvalidOperationException(
131            string.Format("Type mismatch. Variable \"{0}\" does not contain a \"{1}\".",
132                          name,
133                          typeof(T).GetPrettyName())
134          );
135        return var.Value;
136      }
137      return null;
138    }
139    protected override void SetActualValue(IItem value) {
140      if (!(value is T))
141        throw new InvalidOperationException(
142          string.Format("Type mismatch. Value is not a \"{0}\".",
143                        typeof(T).GetPrettyName())
144        );
145      // try to set value in context stack
146      string name;
147      IValueParameter param = GetValueParameterAndTranslateName(out name);
148      if (param != null) {
149        param.Value = value;
150        return;
151      }
152
153      // try to set value in scope
154      IVariable var = LookupVariable(name);
155      if (var != null) {
156        var.Value = value;
157        return;
158      }
159
160      // create new variable
161      ExecutionContext.Scope.Variables.Add(new Variable(name, value));
162    }
163
164    public event EventHandler ActualNameChanged;
165    private void OnActualNameChanged() {
166      if (ActualNameChanged != null)
167        ActualNameChanged(this, EventArgs.Empty);
168      OnToStringChanged();
169    }
170
171    public static string TranslateName(string name, IExecutionContext context) {
172      string currentName = name;
173      IExecutionContext currentContext = context;
174      IParameter param;
175      ILookupParameter lookupParam;
176
177      while (currentContext != null) {
178        currentContext.Parameters.TryGetValue(currentName, out param);
179        if (param != null) {
180          lookupParam = param as ILookupParameter;
181          if (lookupParam == null)
182            throw new InvalidOperationException(
183              string.Format("Parameter look-up chain broken. Parameter \"{0}\" is not an \"{1}\".",
184                            currentName,
185                            typeof(ILookupParameter).GetPrettyName())
186            );
187          currentName = lookupParam.ActualName;
188        }
189        currentContext = currentContext.Parent;
190      }
191      return currentName;
192    }
193  }
194}
Note: See TracBrowser for help on using the repository browser.