Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Optimization/3.3/EngineAlgorithm.cs @ 2933

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

Operator architecture refactoring (#95)

  • corrected persistence and initialization of algorithms
  • fixed SGA performance test
File size: 8.9 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 System.Linq;
24using HeuristicLab.Collections;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
28using HeuristicLab.PluginInfrastructure;
29
30namespace HeuristicLab.Optimization {
31  /// <summary>
32  /// A base class for algorithms which use an engine for execution.
33  /// </summary>
34  [Item("EngineAlgorithm", "A base class for algorithms which use an engine for execution.")]
35  public abstract class EngineAlgorithm : Algorithm {
36    private OperatorGraph operatorGraph;
37    [Storable]
38    private OperatorGraph OperatorGraphPersistence {
39      get { return operatorGraph; }
40      set {
41        if (operatorGraph != null) operatorGraph.InitialOperatorChanged -= new EventHandler(OperatorGraph_InitialOperatorChanged);
42        operatorGraph = value;
43        if (operatorGraph != null) operatorGraph.InitialOperatorChanged += new EventHandler(OperatorGraph_InitialOperatorChanged);
44      }
45    }
46    protected OperatorGraph OperatorGraph {
47      get { return operatorGraph; }
48      set {
49        if (value == null) throw new ArgumentNullException();
50        if (value != operatorGraph) {
51          if (operatorGraph != null) operatorGraph.InitialOperatorChanged -= new EventHandler(OperatorGraph_InitialOperatorChanged);
52          operatorGraph = value;
53          if (operatorGraph != null) operatorGraph.InitialOperatorChanged += new EventHandler(OperatorGraph_InitialOperatorChanged);
54          OnOperatorGraphChanged();
55          Prepare();
56        }
57      }
58    }
59
60    [Storable]
61    private IScope globalScope;
62    protected IScope GlobalScope {
63      get { return globalScope; }
64    }
65
66    private IEngine engine;
67    [Storable]
68    private IEngine EnginePersistence {
69      get { return engine; }
70      set {
71        if (engine != null) DeregisterEngineEvents();
72        engine = value;
73        if (engine != null) RegisterEngineEvents();
74      }
75    }
76    public IEngine Engine {
77      get { return engine; }
78      set {
79        if (engine != value) {
80          if (engine != null) DeregisterEngineEvents();
81          engine = value;
82          if (engine != null) RegisterEngineEvents();
83          OnEngineChanged();
84          Prepare();
85        }
86      }
87    }
88
89    private ReadOnlyObservableKeyedCollection<string, IVariable> readOnlyResults;
90    public override IObservableKeyedCollection<string, IVariable> Results {
91      get {
92        if (readOnlyResults == null)
93          readOnlyResults = ((VariableCollection)globalScope.Variables["Results"].Value).AsReadOnly();
94        return readOnlyResults;
95      }
96    }
97
98    public override TimeSpan ExecutionTime {
99      get {
100        if (engine == null) return TimeSpan.Zero;
101        else return engine.ExecutionTime;
102      }
103    }
104
105    public override bool Finished {
106      get {
107        if (engine == null) return true;
108        else return engine.Finished;
109      }
110    }
111
112    protected EngineAlgorithm()
113      : base() {
114      globalScope = new Scope("Global Scope");
115      globalScope.Variables.Add(new Variable("Results", new VariableCollection()));
116      OperatorGraph = new OperatorGraph();
117      InitializeEngine();
118    }
119    protected EngineAlgorithm(string name)
120      : base(name) {
121      globalScope = new Scope("Global Scope");
122      globalScope.Variables.Add(new Variable("Results", new VariableCollection()));
123      OperatorGraph = new OperatorGraph();
124      InitializeEngine();
125    }
126    protected EngineAlgorithm(string name, ParameterCollection parameters)
127      : base(name, parameters) {
128      globalScope = new Scope("Global Scope");
129      globalScope.Variables.Add(new Variable("Results", new VariableCollection()));
130      OperatorGraph = new OperatorGraph();
131      InitializeEngine();
132    }
133    protected EngineAlgorithm(string name, string description)
134      : base(name, description) {
135      globalScope = new Scope("Global Scope");
136      globalScope.Variables.Add(new Variable("Results", new VariableCollection()));
137      OperatorGraph = new OperatorGraph();
138      InitializeEngine();
139    }
140    protected EngineAlgorithm(string name, string description, ParameterCollection parameters)
141      : base(name, description, parameters) {
142      globalScope = new Scope("Global Scope");
143      globalScope.Variables.Add(new Variable("Results", new VariableCollection()));
144      OperatorGraph = new OperatorGraph();
145      InitializeEngine();
146    }
147
148    private void InitializeEngine() {
149      if (ApplicationManager.Manager != null) {
150        var types = ApplicationManager.Manager.GetTypes(typeof(IEngine));
151        Type t = types.FirstOrDefault(x => x.Name.Equals("SequentialEngine"));
152        if (t == null) t = types.FirstOrDefault();
153        if (t != null) Engine = (IEngine)Activator.CreateInstance(t);
154      }
155    }
156
157    public override IDeepCloneable Clone(Cloner cloner) {
158      EngineAlgorithm clone = (EngineAlgorithm)base.Clone(cloner);
159      clone.globalScope = (IScope)cloner.Clone(globalScope);
160      clone.Engine = (IEngine)cloner.Clone(engine);
161      clone.OperatorGraph = (OperatorGraph)cloner.Clone(operatorGraph);
162      return clone;
163    }
164
165    public UserDefinedAlgorithm CreateUserDefinedAlgorithm() {
166      UserDefinedAlgorithm algorithm = new UserDefinedAlgorithm(Name, Description);
167      Cloner cloner = new Cloner();
168      foreach (IParameter param in Parameters)
169        algorithm.Parameters.Add((IParameter)cloner.Clone(param));
170      algorithm.Problem = (IProblem)cloner.Clone(Problem);
171      algorithm.Engine = (IEngine)cloner.Clone(engine);
172      algorithm.OperatorGraph = (OperatorGraph)cloner.Clone(operatorGraph);
173      return algorithm;
174    }
175
176    protected override void OnCanceledChanged() {
177      if (Canceled && (engine != null))
178        engine.Stop();
179    }
180    protected override void OnPrepared() {
181      globalScope.Clear();
182      globalScope.Variables.Add(new Variable("Results", new VariableCollection()));
183      readOnlyResults = null;
184
185      if (engine != null) {
186        ExecutionContext context = null;
187        if (operatorGraph.InitialOperator != null) {
188          if (Problem != null) {
189            context = new ExecutionContext(context, Problem, globalScope);
190            foreach (IParameter param in Problem.Parameters)
191              param.ExecutionContext = context;
192          }
193          context = new ExecutionContext(context, this, globalScope);
194          foreach (IParameter param in this.Parameters)
195            param.ExecutionContext = context;
196          context = new ExecutionContext(context, operatorGraph.InitialOperator, globalScope);
197        }
198        engine.Prepare(context);
199      }
200      base.OnPrepared();
201    }
202    protected override void OnStarted() {
203      if (engine != null) engine.Start();
204      base.OnStarted();
205    }
206
207    protected virtual void OnOperatorGraphChanged() { }
208
209    public event EventHandler EngineChanged;
210    protected virtual void OnEngineChanged() {
211      if (EngineChanged != null)
212        EngineChanged(this, EventArgs.Empty);
213    }
214
215    private void OperatorGraph_InitialOperatorChanged(object sender, EventArgs e) {
216      Prepare();
217    }
218    private void RegisterEngineEvents() {
219      Engine.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(Engine_ExceptionOccurred);
220      Engine.ExecutionTimeChanged += new EventHandler(Engine_ExecutionTimeChanged);
221      Engine.Stopped += new EventHandler(Engine_Stopped);
222    }
223    private void DeregisterEngineEvents() {
224      Engine.ExceptionOccurred -= new EventHandler<EventArgs<Exception>>(Engine_ExceptionOccurred);
225      Engine.ExecutionTimeChanged -= new EventHandler(Engine_ExecutionTimeChanged);
226      Engine.Stopped -= new EventHandler(Engine_Stopped);
227    }
228
229    private void Engine_ExceptionOccurred(object sender, EventArgs<Exception> e) {
230      OnExceptionOccurred(e.Value);
231    }
232    private void Engine_ExecutionTimeChanged(object sender, EventArgs e) {
233      OnExecutionTimeChanged();
234    }
235    private void Engine_Stopped(object sender, EventArgs e) {
236      OnStopped();
237    }
238  }
239}
Note: See TracBrowser for help on using the repository browser.