Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PerformanceComparison/HeuristicLab.Optimization/3.3/Algorithms/EngineAlgorithm.cs @ 12771

Last change on this file since 12771 was 12771, checked in by abeham, 9 years ago

#2431:

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