Free cookie consent management tool by TermsFeed Policy Generator

source: branches/1614_GeneralizedQAP/HeuristicLab.Optimization/3.3/Algorithms/EngineAlgorithm.cs @ 16003

Last change on this file since 16003 was 15721, checked in by abeham, 7 years ago

#1614:

  • reverted r15603 by reverse merging
  • added expert system plugins from #2457
File size: 9.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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    public OperatorGraph OperatorGraph {
39      get { return operatorGraph; }
40      protected 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    [StorableHook(HookType.AfterDeserialization)]
117    private void AfterDeserialization() {
118      Initialize();
119
120      // BackwardsCompatibility3.3
121      #region Backwards compatible code (remove with 3.4)
122      // clear global scope if it contains any sub-scopes or additional variables
123      if ((ExecutionState == Core.ExecutionState.Stopped) && ((globalScope.SubScopes.Count > 0) || (globalScope.Variables.Count > 1))) {
124        ResultCollection results = Results;
125        globalScope.Clear();
126        globalScope.Variables.Add(new Variable("Results", results));
127      }
128      #endregion
129    }
130
131    protected EngineAlgorithm(EngineAlgorithm original, Cloner cloner)
132      : base(original, cloner) {
133      globalScope = cloner.Clone(original.globalScope);
134      engine = cloner.Clone(original.engine);
135      operatorGraph = cloner.Clone(original.operatorGraph);
136      Initialize();
137    }
138
139    private void Initialize() {
140      operatorGraph.InitialOperatorChanged += new EventHandler(OperatorGraph_InitialOperatorChanged);
141      if (engine == null) {
142        var types = ApplicationManager.Manager.GetTypes(typeof(IEngine));
143        Type t = types.FirstOrDefault(x => x.Name.Equals("SequentialEngine"));
144        if (t == null) t = types.FirstOrDefault();
145        if (t != null) engine = (IEngine)Activator.CreateInstance(t);
146      }
147      if (engine != null) RegisterEngineEvents();
148    }
149
150    public virtual IAlgorithm CreateUserDefinedAlgorithm() {
151      return new UserDefinedAlgorithm(this, new Cloner());
152    }
153
154    public override void Prepare() {
155      base.Prepare();
156      globalScope.Clear();
157      globalScope.Variables.Add(new Variable("Results", new ResultCollection()));
158
159      if ((engine != null) && (operatorGraph.InitialOperator != null)) {
160        ExecutionContext context = null;
161        if (Problem != null) {
162          foreach (var item in Problem.ExecutionContextItems)
163            context = new ExecutionContext(context, item, globalScope);
164        }
165        context = new ExecutionContext(context, this, globalScope);
166        context = new ExecutionContext(context, operatorGraph.InitialOperator, globalScope);
167        engine.Prepare(context);
168        engine.Log.Clear();
169      }
170    }
171    public override void Start(System.Threading.CancellationToken cancellationToken) {
172      base.Start(cancellationToken);
173      if (engine != null) engine.Start(cancellationToken);
174    }
175    public override void Pause() {
176      base.Pause();
177      if (engine != null) engine.Pause();
178    }
179    public override void Stop() {
180      base.Stop();
181      if (engine != null) engine.Stop();
182    }
183
184    #region Events
185    public event EventHandler EngineChanged;
186    protected virtual void OnEngineChanged() {
187      EventHandler handler = EngineChanged;
188      if (handler != null) handler(this, EventArgs.Empty);
189    }
190    public event EventHandler OperatorGraphChanged;
191    protected virtual void OnOperatorGraphChanged() {
192      EventHandler handler = OperatorGraphChanged;
193      if (handler != null) handler(this, EventArgs.Empty);
194    }
195
196    private void RegisterEngineEvents() {
197      Engine.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(Engine_ExceptionOccurred);
198      Engine.ExecutionTimeChanged += new EventHandler(Engine_ExecutionTimeChanged);
199      Engine.Paused += new EventHandler(Engine_Paused);
200      Engine.Prepared += new EventHandler(Engine_Prepared);
201      Engine.Started += new EventHandler(Engine_Started);
202      Engine.Stopped += new EventHandler(Engine_Stopped);
203    }
204    private void DeregisterEngineEvents() {
205      Engine.ExceptionOccurred -= new EventHandler<EventArgs<Exception>>(Engine_ExceptionOccurred);
206      Engine.ExecutionTimeChanged -= new EventHandler(Engine_ExecutionTimeChanged);
207      Engine.Paused -= new EventHandler(Engine_Paused);
208      Engine.Prepared -= new EventHandler(Engine_Prepared);
209      Engine.Started -= new EventHandler(Engine_Started);
210      Engine.Stopped -= new EventHandler(Engine_Stopped);
211    }
212    private void Engine_ExceptionOccurred(object sender, EventArgs<Exception> e) {
213      OnExceptionOccurred(e.Value);
214    }
215    private void Engine_ExecutionTimeChanged(object sender, EventArgs e) {
216      ExecutionTime = Engine.ExecutionTime;
217    }
218    private void Engine_Paused(object sender, EventArgs e) {
219      OnPaused();
220    }
221    private void Engine_Prepared(object sender, EventArgs e) {
222      OnPrepared();
223    }
224    private void Engine_Started(object sender, EventArgs e) {
225      OnStarted();
226    }
227    private void Engine_Stopped(object sender, EventArgs e) {
228      ResultCollection results = Results;
229      globalScope.Clear();
230      globalScope.Variables.Add(new Variable("Results", results));
231      OnStopped();
232    }
233
234    private void OperatorGraph_InitialOperatorChanged(object sender, EventArgs e) {
235      Prepare();
236    }
237    #endregion
238  }
239}
Note: See TracBrowser for help on using the repository browser.