Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 17614 was 17614, checked in by abeham, 4 years ago

#2521: work in progress (removed solution creator parameter from encoding), OrienteeringProblem and test functions are broken

File size: 9.3 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    protected EngineAlgorithm()
79      : base() {
80      globalScope = new Scope("Global Scope");
81      globalScope.Variables.Add(new Variable("Results", Results));
82      operatorGraph = new OperatorGraph();
83      Initialize();
84    }
85    protected EngineAlgorithm(string name)
86      : base(name) {
87      globalScope = new Scope("Global Scope");
88      globalScope.Variables.Add(new Variable("Results", Results));
89      operatorGraph = new OperatorGraph();
90      Initialize();
91    }
92    protected EngineAlgorithm(string name, ParameterCollection parameters)
93      : base(name, parameters) {
94      globalScope = new Scope("Global Scope");
95      globalScope.Variables.Add(new Variable("Results", Results));
96      operatorGraph = new OperatorGraph();
97      Initialize();
98    }
99    protected EngineAlgorithm(string name, string description)
100      : base(name, description) {
101      globalScope = new Scope("Global Scope");
102      globalScope.Variables.Add(new Variable("Results", Results));
103      operatorGraph = new OperatorGraph();
104      Initialize();
105    }
106    protected EngineAlgorithm(string name, string description, ParameterCollection parameters)
107      : base(name, description, parameters) {
108      globalScope = new Scope("Global Scope");
109      globalScope.Variables.Add(new Variable("Results", Results));
110      operatorGraph = new OperatorGraph();
111      Initialize();
112    }
113    [StorableConstructor]
114    protected EngineAlgorithm(StorableConstructorFlag _) : base(_) { }
115    [StorableHook(HookType.AfterDeserialization)]
116    private void AfterDeserialization() {
117      Initialize();
118
119      // BackwardsCompatibility3.3
120      #region Backwards compatible code (remove with 3.4)
121      // clear global scope if it contains any sub-scopes or additional variables
122      if ((ExecutionState == Core.ExecutionState.Stopped) && ((globalScope.SubScopes.Count > 0) || (globalScope.Variables.Count > 1))) {
123        ResultCollection results = Results;
124        globalScope.Clear();
125        globalScope.Variables.Add(new Variable("Results", results));
126      }
127      #endregion
128    }
129
130    protected EngineAlgorithm(EngineAlgorithm original, Cloner cloner)
131      : base(original, cloner) {
132      globalScope = cloner.Clone(original.globalScope);
133      engine = cloner.Clone(original.engine);
134      operatorGraph = cloner.Clone(original.operatorGraph);
135      Initialize();
136    }
137
138    private void Initialize() {
139      operatorGraph.InitialOperatorChanged += new EventHandler(OperatorGraph_InitialOperatorChanged);
140      if (engine == null) {
141        var types = ApplicationManager.Manager.GetTypes(typeof(IEngine));
142        Type t = types.FirstOrDefault(x => x.Name.Equals("SequentialEngine"));
143        if (t == null) t = types.FirstOrDefault();
144        if (t != null) engine = (IEngine)Activator.CreateInstance(t);
145      }
146      if (engine != null) RegisterEngineEvents();
147    }
148
149    public virtual IAlgorithm CreateUserDefinedAlgorithm() {
150      return new UserDefinedAlgorithm(this, new Cloner());
151    }
152
153    public override void Prepare() {
154      base.Prepare();
155      globalScope.Clear();
156      globalScope.Variables.Add(new Variable("Results", Results));
157
158      if ((engine != null) && (operatorGraph.InitialOperator != null)) {
159        ExecutionContext context = null;
160        if (Problem != null) {
161          foreach (var item in Problem.ExecutionContextItems)
162            context = new ExecutionContext(context, item, globalScope);
163        }
164        context = new ExecutionContext(context, this, globalScope);
165        context = new ExecutionContext(context, operatorGraph.InitialOperator, globalScope);
166        engine.Prepare(context);
167      }
168    }
169    public override void Start(System.Threading.CancellationToken cancellationToken) {
170      base.Start(cancellationToken);
171      if (engine != null) engine.Start(cancellationToken);
172    }
173    public override void Pause() {
174      base.Pause();
175      if (engine != null) engine.Pause();
176    }
177    public override void Stop() {
178      base.Stop();
179      if (engine != null) engine.Stop();
180    }
181
182
183
184    #region Events
185    protected override void DeregisterProblemEvents() {
186      Problem.Reset -= new EventHandler(Problem_Reset);
187      Problem.OperatorsChanged -= new EventHandler(Problem_OperatorsChanged);
188    }
189    protected override void RegisterProblemEvents() {
190      Problem.Reset += new EventHandler(Problem_Reset);
191      Problem.OperatorsChanged += new EventHandler(Problem_OperatorsChanged);
192    }
193    protected virtual void Problem_OperatorsChanged(object sender, EventArgs e) { }
194
195
196    public event EventHandler EngineChanged;
197    protected virtual void OnEngineChanged() {
198      EventHandler handler = EngineChanged;
199      if (handler != null) handler(this, EventArgs.Empty);
200    }
201    public event EventHandler OperatorGraphChanged;
202    protected virtual void OnOperatorGraphChanged() {
203      EventHandler handler = OperatorGraphChanged;
204      if (handler != null) handler(this, EventArgs.Empty);
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      ResultCollection results = Results;
240      globalScope.Clear();
241      globalScope.Variables.Add(new Variable("Results", results));
242      OnStopped();
243    }
244
245    private void OperatorGraph_InitialOperatorChanged(object sender, EventArgs e) {
246      Prepare();
247    }
248    #endregion
249  }
250}
Note: See TracBrowser for help on using the repository browser.