Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3.0/sources/HeuristicLab.Functions/FunctionBase.cs @ 7317

Last change on this file since 7317 was 2, checked in by swagner, 17 years ago

Added HeuristicLab 3.0 sources from former SVN repository at revision 52

File size: 11.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 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 System.Collections.Generic;
24using System.Text;
25using HeuristicLab.Data;
26using HeuristicLab.Core;
27using System.Xml;
28using HeuristicLab.DataAnalysis;
29
30namespace HeuristicLab.Functions {
31  public abstract class FunctionBase : OperatorBase, IFunction {
32    private List<IFunction> subFunctions;
33    // instance subfunctions
34    public IList<IFunction> SubFunctions {
35      get {
36        return subFunctions;
37      }
38    }
39
40    // instance variables
41    private List<IVariable> variables;
42    public ICollection<IVariable> LocalVariables {
43      get { return variables.AsReadOnly(); }
44    }
45
46    // reference to the 'type' of the function
47    private FunctionBase metaObject;
48    public IFunction MetaObject {
49      get { return metaObject; }
50    }
51
52    public FunctionBase() {
53      metaObject = this; // (FunctionBase)Activator.CreateInstance(this.GetType());
54      AddVariableInfo(new VariableInfo("Dataset", "Dataset from which to read samples", typeof(DoubleMatrixData), VariableKind.In));
55      AddVariableInfo(new VariableInfo("SampleIndex", "Gives the row index from which to read the sample", typeof(IntData), VariableKind.In));
56      AddVariableInfo(new VariableInfo("Result", "The result of the evaluation of the function", typeof(DoubleData), VariableKind.Out));
57
58      subFunctions = new List<IFunction>();
59      variables = new List<IVariable>();
60    }
61
62    public FunctionBase(FunctionBase source, IDictionary<Guid, object> clonedObjects)
63      : base() {
64      this.metaObject = source.metaObject;
65      variables = new List<IVariable>();
66      subFunctions = new List<IFunction>();
67      foreach (IFunction subFunction in source.SubFunctions) {
68        subFunctions.Add((IFunction)Auxiliary.Clone(subFunction, clonedObjects));
69      }
70      foreach (IVariable variable in source.variables) {
71        variables.Add((IVariable)Auxiliary.Clone(variable, clonedObjects));
72      }
73    }
74
75    public abstract double Evaluate(Dataset dataset, int sampleIndex);
76
77    public override IOperation Apply(IScope scope) {
78      DoubleData result = this.GetVariableValue<DoubleData>("Result", scope, false);
79      Dataset dataset = GetVariableValue<Dataset>("Dataset", scope, true);
80      IntData sampleIndex = GetVariableValue<IntData>("SampleIndex", scope, true);
81      result.Data = Evaluate(dataset, sampleIndex.Data);
82      return null;
83    }
84
85    public virtual void Accept(IFunctionVisitor visitor) {
86      visitor.Visit(this);
87    }
88
89    public override void AddSubOperator(IOperator subOperator) {
90      subFunctions.Add((IFunction)subOperator);
91    }
92
93    public override bool TryAddSubOperator(IOperator subOperator) {
94      subFunctions.Add((IFunction)subOperator);
95      bool valid = IsValid();
96      if (!valid) {
97        subFunctions.RemoveAt(subFunctions.Count - 1);
98      }
99
100      return valid;
101    }
102
103    public override bool TryAddSubOperator(IOperator subOperator, int index) {
104      subFunctions.Insert(index, (IFunction)subOperator);
105      bool valid = IsValid();
106      if (!valid) {
107        subFunctions.RemoveAt(index);
108      }
109      return valid;
110    }
111
112    public override bool TryAddSubOperator(IOperator subOperator, int index, out ICollection<IConstraint> violatedConstraints) {
113      subFunctions.Insert(index, (IFunction)subOperator);
114      bool valid = IsValid(out violatedConstraints);
115      if (!valid) {
116        subFunctions.RemoveAt(index);
117      }
118      return valid;
119    }
120
121    public override bool TryAddSubOperator(IOperator subOperator, out ICollection<IConstraint> violatedConstraints) {
122      subFunctions.Add((IFunction)subOperator);
123      bool valid = IsValid(out violatedConstraints);
124      if (!valid) {
125        subFunctions.RemoveAt(subFunctions.Count - 1);
126      }
127
128      return valid;
129    }
130
131    public override void AddSubOperator(IOperator subOperator, int index) {
132      subFunctions.Insert(index, (IFunction)subOperator);
133    }
134
135    public override void RemoveSubOperator(int index) {
136      if (index >= subFunctions.Count) throw new InvalidOperationException();
137      subFunctions.RemoveAt(index);
138    }
139
140    public override IList<IOperator> SubOperators {
141      get { return subFunctions.ConvertAll(f => (IOperator)f); }
142    }
143
144    public override ICollection<IVariable> Variables {
145      get {
146        List<IVariable> mergedVariables = new List<IVariable>(variables);
147        if (this == metaObject) {
148          foreach (IVariable variable in base.Variables) {
149            if (!IsLocalVariable(variable.Name)) {
150              mergedVariables.Add(variable);
151            }
152          }
153        } else {
154          foreach (IVariable variable in metaObject.Variables) {
155            if (!IsLocalVariable(variable.Name)) {
156              mergedVariables.Add(variable);
157            }
158          }
159        }
160        return mergedVariables;
161      }
162    }
163
164    private bool IsLocalVariable(string name) {
165      foreach (IVariable variable in variables) {
166        if (variable.Name == name) return true;
167      }
168      return false;
169    }
170
171
172    public override bool TryRemoveSubOperator(int index) {
173      IFunction removedFunction = subFunctions[index];
174      subFunctions.RemoveAt(index);
175      bool valid = IsValid();
176      if (!valid) {
177        subFunctions.Insert(index, removedFunction);
178      }
179
180      return valid;
181    }
182
183    public override bool TryRemoveSubOperator(int index, out ICollection<IConstraint> violatedConstraints) {
184      IFunction removedFunction = subFunctions[index];
185      subFunctions.RemoveAt(index);
186      bool valid = IsValid(out violatedConstraints);
187      if (!valid) {
188        subFunctions.Insert(index, removedFunction);
189      }
190
191      return valid;
192    }
193
194    public override void AddVariable(IVariable variable) {
195      if (metaObject == this) {
196        base.AddVariable(variable);
197      } else {
198        metaObject.AddVariable(variable);
199      }
200    }
201
202    public override IVariable GetVariable(string name) {
203      foreach (IVariable variable in variables) {
204        if (variable.Name == name) return variable;
205      }
206      if (metaObject == this) {
207        return base.GetVariable(name);
208      } else {
209        return metaObject.GetVariable(name);
210      }
211    }
212
213    public void AddLocalVariable(IVariable variable) {
214      variables.Add(variable);
215    }
216
217    public override void RemoveVariable(string name) {
218      foreach (IVariable variable in variables) {
219        if (variable.Name == name) {
220          variables.Remove(variable);
221          return;
222        }
223      }
224      if (metaObject == this) {
225        base.RemoveVariable(name);
226      } else {
227        metaObject.RemoveVariable(name);
228      }
229    }
230
231    public override IItem GetVariableValue(string formalName, IScope scope, bool recursiveLookup, bool throwOnError) {
232      foreach (IVariable variable in Variables) {
233        if (variable.Name == formalName) {
234          return variable.Value;
235        }
236      }
237      return metaObject.GetVariableValue(formalName, scope, recursiveLookup, throwOnError);
238    }
239
240    public override ICollection<IVariableInfo> VariableInfos {
241      get {
242        if (metaObject == this) {
243          return base.VariableInfos;
244        } else {
245          return metaObject.VariableInfos;
246        }
247      }
248    }
249
250    public override void AddVariableInfo(IVariableInfo variableInfo) {
251      if (metaObject == this) {
252        base.AddVariableInfo(variableInfo);
253      } else {
254        metaObject.AddVariableInfo(variableInfo);
255      }
256    }
257
258    public override void RemoveVariableInfo(string formalName) {
259      if (metaObject == this) {
260        base.RemoveVariableInfo(formalName);
261      } else {
262        metaObject.RemoveVariableInfo(formalName);
263      }
264    }
265
266    public override ICollection<IConstraint> Constraints {
267      get {
268        if (metaObject == this) {
269          return base.Constraints;
270        } else {
271          return metaObject.Constraints;
272        }
273      }
274    }
275
276    public override void AddConstraint(IConstraint constraint) {
277      if (metaObject == this) {
278        base.AddConstraint(constraint);
279      } else {
280        metaObject.AddConstraint(constraint);
281      }
282    }
283    public override void RemoveConstraint(IConstraint constraint) {
284      if (metaObject == this) {
285        base.RemoveConstraint(constraint);
286      } else {
287        metaObject.RemoveConstraint(constraint);
288      }
289    }
290
291    public override XmlNode GetXmlNode(string name, XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {
292      XmlNode node = base.GetXmlNode(name, document, persistedObjects);
293      if (metaObject != this) {
294        XmlNode functionTemplateNode = document.CreateElement("FunctionTemplate");
295        functionTemplateNode.AppendChild(PersistenceManager.Persist(metaObject, document, persistedObjects));
296        node.AppendChild(functionTemplateNode);
297      }
298
299      // don't need to persist the sub-functions because OperatorBase.GetXmlNode already persisted the sub-operators
300
301      // persist local variables
302      XmlNode variablesNode = document.CreateNode(XmlNodeType.Element, "LocalVariables", null);
303      foreach (IVariable variable in variables) {
304        variablesNode.AppendChild(PersistenceManager.Persist(variable, document, persistedObjects));
305      }
306      node.AppendChild(variablesNode);
307      return node;
308    }
309
310    public override void Populate(XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {
311      base.Populate(node, restoredObjects);
312      XmlNode functionTemplateNode = node.SelectSingleNode("FunctionTemplate");
313      if (functionTemplateNode != null) {
314        metaObject = (FunctionBase)PersistenceManager.Restore(functionTemplateNode.ChildNodes[0], restoredObjects);
315      } else {
316        metaObject = this;
317      }
318      // don't need to explicitly load the sub-functions because that has already been done in OperatorBase.Populate()
319
320      // load local variables
321      XmlNode variablesNode = node.SelectSingleNode("LocalVariables");
322     
323      // remove the variables that have been added in a constructor
324      variables.Clear();
325      // load the persisted variables
326      foreach (XmlNode variableNode in variablesNode.ChildNodes)
327        variables.Add((IVariable)PersistenceManager.Restore(variableNode, restoredObjects));
328    }
329
330    public override IView CreateView() {
331      return new FunctionView(this);
332    }
333  }
334}
Note: See TracBrowser for help on using the repository browser.