Free cookie consent management tool by TermsFeed Policy Generator

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

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

Operator architecture refactoring (#95)

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