Free cookie consent management tool by TermsFeed Policy Generator

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

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

Operator architecture refactoring (#95)

  • corrected several bugs in order to get SGA working
File size: 7.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      ExecutionContext 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.Operator.Parameters.ContainsKey(name))
85          current = current.Parent;
86
87        if (current != null) {
88          valueParam = current.Operator.Parameters[name] as IValueParameter;
89          lookupParam = current.Operator.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    private IValueParameter GetProblemParameter(string name) {
111      IValueParameter param = null;
112      if (ExecutionContext.Problem.Parameters.ContainsKey(name)) {
113        param = ExecutionContext.Problem.Parameters[name] as IValueParameter;
114        if (param == null)
115          throw new InvalidOperationException(
116            string.Format("Parameter look-up chain broken. Parameter \"{0}\" is not an \"{1}\".",
117                          name,
118                          typeof(IValueParameter).GetPrettyName())
119          );
120      }
121      return param;
122    }
123    protected override IItem GetActualValue() {
124      string name;
125      // try to get value from context stack
126      IValueParameter param = GetParameter(out name);
127      if (param != null) return param.Value;
128
129      // try to get variable from scope
130      IVariable var = LookupVariable(name);
131      if (var != null) {
132        T value = var.Value as T;
133        if (value == null)
134          throw new InvalidOperationException(
135            string.Format("Type mismatch. Variable \"{0}\" does not contain a \"{1}\".",
136                          name,
137                          typeof(T).GetPrettyName())
138          );
139        return value;
140      }
141
142      // try to get value from problem
143      IValueParameter problemParam = GetProblemParameter(name);
144      if (problemParam != null) return problemParam.Value;
145
146      return null;
147    }
148    protected override void SetActualValue(IItem value) {
149      T val = value as T;
150      if (val == null)
151        throw new InvalidOperationException(
152          string.Format("Type mismatch. Value is not a \"{0}\".",
153                        typeof(T).GetPrettyName())
154        );
155      // try to set value in context stack
156      string name;
157      IValueParameter param = GetParameter(out name);
158      if (param != null) {
159        param.Value = val;
160        return;
161      }
162
163      // try to set value in scope
164      IVariable var = LookupVariable(name);
165      if (var != null) {
166        var.Value = val;
167        return;
168      }
169
170      // try to set value in problem
171      IValueParameter problemParam = GetProblemParameter(name);
172      if (problemParam != null) {
173        problemParam.Value = val;
174        return;
175      }
176
177      // create new variable
178      ExecutionContext.Scope.Variables.Add(new Variable(name, value));
179    }
180
181    public event EventHandler ActualNameChanged;
182    private void OnActualNameChanged() {
183      if (ActualNameChanged != null)
184        ActualNameChanged(this, EventArgs.Empty);
185      OnChanged();
186    }
187
188    public static string TranslateName(string name, ExecutionContext context) {
189      string currentName = name;
190      ExecutionContext currentContext = context;
191      IParameter param;
192      ILookupParameter lookupParam;
193
194      while (currentContext != null) {
195        currentContext.Operator.Parameters.TryGetValue(currentName, out param);
196        if (param != null) {
197          lookupParam = param as ILookupParameter;
198          if (lookupParam == null)
199            throw new InvalidOperationException(
200              string.Format("Parameter look-up chain broken. Parameter \"{0}\" is not an \"{1}\".",
201                            currentName,
202                            typeof(ILookupParameter).GetPrettyName())
203            );
204          currentName = lookupParam.ActualName;
205        }
206        currentContext = currentContext.Parent;
207      }
208      return currentName;
209    }
210  }
211}
Note: See TracBrowser for help on using the repository browser.