Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2521_ProblemRefactoring/HeuristicLab.Optimization/3.3/Algorithms/EngineAlgorithm.cs @ 17513

Last change on this file since 17513 was 17513, checked in by mkommend, 4 years ago

#2521: Splitted problems into several problem and encoded problems.

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