Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3303 was 3303, checked in by swagner, 12 years ago

Removed unnecessary checks if the application manager is not null (#954).

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