Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Async/HeuristicLab.Optimization/3.3/Algorithms/EngineAlgorithm.cs @ 14042

Last change on this file since 14042 was 13349, checked in by jkarder, 9 years ago

#2258: added StartAsync to IExecutable

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