Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.DebugEngine/DebugEngine.cs @ 4946

Last change on this file since 4946 was 4946, checked in by mkommend, 14 years ago

Minor changes in DebugEngine (ticket #47).

File size: 11.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.Collections.Generic;
24using System.Linq;
25using System.Threading;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
29
30namespace HeuristicLab.DebugEngine {
31
32  [StorableClass]
33  [Item("Debug Engine", "Engine for debugging algorithms.")]
34  public class DebugEngine : Executable, IEngine {
35
36    #region Construction and Cloning
37
38    [StorableConstructor]
39    protected DebugEngine(bool deserializing)
40      : base(deserializing) {
41      pausePending = stopPending = false;
42      InitializeTimer();
43    }
44
45    protected DebugEngine(DebugEngine original, Cloner cloner)
46      : base(original, cloner) {
47      if (original.ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
48      Log = cloner.Clone(original.Log);
49      ExecutionStack = cloner.Clone(original.ExecutionStack);
50      OperatorTrace = cloner.Clone(OperatorTrace);
51      operatorParents = original.operatorParents.ToDictionary(kvp => cloner.Clone(kvp.Key), kvp => cloner.Clone(kvp.Value));
52      pausePending = original.pausePending;
53      stopPending = original.stopPending;
54      InitializeTimer();
55      currentOperation = cloner.Clone(original.currentOperation);
56      currentOperator = cloner.Clone(original.currentOperator);
57    }
58    public DebugEngine()
59      : base() {
60      Log = new Log();
61      ExecutionStack = new ExecutionStack();
62      OperatorTrace = new ItemList<IOperator>();
63      operatorParents = new Dictionary<IAtomicOperation, IAtomicOperation>();
64      pausePending = stopPending = false;
65      InitializeTimer();
66    }
67
68    public override IDeepCloneable Clone(Cloner cloner) {
69      return new DebugEngine(this, cloner);
70    }
71
72    private void InitializeTimer() {
73      timer = new System.Timers.Timer(100);
74      timer.AutoReset = true;
75      timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
76    }
77
78    #endregion
79
80    #region Fields and Properties
81
82    [Storable]
83    public ILog Log { get; protected set; }
84
85    [Storable]
86    public ExecutionStack ExecutionStack { get; protected set; }
87
88    private bool pausePending, stopPending;
89    private DateTime lastUpdateTime;
90    private System.Timers.Timer timer;
91
92    [Storable]
93    private IOperator currentOperator;
94
95    [Storable]
96    private bool ignoreNextBreakpoint;
97
98    [Storable]
99    private IOperation currentOperation;
100    public virtual IOperation CurrentOperation {
101      get { return currentOperation; }
102      private set {
103        if (value != currentOperation) {
104          currentOperation = value;
105          OnOperationChanged(value);
106        }
107      }
108    }
109
110    public virtual IAtomicOperation CurrentAtomicOperation {
111      get { return CurrentOperation as IAtomicOperation; }
112    }
113
114    public virtual IExecutionContext CurrentExecutionContext {
115      get { return CurrentOperation as IExecutionContext; }
116    }
117
118    [Storable]
119    public ItemList<IOperator> OperatorTrace { get; private set; }
120
121    [Storable]
122    private Dictionary<IAtomicOperation, IAtomicOperation> operatorParents;
123
124    #endregion
125
126    #region Events
127
128    public event EventHandler<OperationChangedEventArgs> CurrentOperationChanged;
129    protected virtual void OnOperationChanged(IOperation newOperation) {
130      EventHandler<OperationChangedEventArgs> handler = CurrentOperationChanged;
131      if (handler != null) {
132        handler(this, new OperationChangedEventArgs(newOperation));
133      }
134    }
135
136    #endregion
137
138    #region Std Methods
139    public sealed override void Prepare() {
140      base.Prepare();
141      ExecutionStack.Clear();
142      ignoreNextBreakpoint = false;
143      CurrentOperation = null;
144      OperatorTrace.Clear();
145      operatorParents.Clear();
146      OnPrepared();
147    }
148    public void Prepare(IOperation initialOperation) {
149      base.Prepare();
150      ExecutionStack.Clear();
151      if (initialOperation != null)
152        ExecutionStack.Add(initialOperation);
153      ignoreNextBreakpoint = false;
154      CurrentOperation = null;
155      OperatorTrace.Clear();
156      operatorParents.Clear();
157      OnPrepared();
158    }
159    protected override void OnPrepared() {
160      Log.LogMessage("Engine prepared");
161      base.OnPrepared();
162    }
163
164    public virtual void Step(bool skipStackOperations) {
165      OnStarted();
166      lastUpdateTime = DateTime.Now;
167      ignoreNextBreakpoint = true;
168      timer.Start();
169      ProcessNextOperation();
170      while (skipStackOperations && !(CurrentOperation is IAtomicOperation) && CanContinue)
171        ProcessNextOperation();
172      timer.Stop();
173      ExecutionTime += DateTime.Now - lastUpdateTime;
174      ignoreNextBreakpoint = false;
175      OnPaused();
176    }
177
178    public override void Start() {
179      base.Start();
180      ThreadPool.QueueUserWorkItem(new WaitCallback(Run), null);
181    }
182
183    protected override void OnStarted() {
184      Log.LogMessage("Engine started");
185      base.OnStarted();
186    }
187
188    public override void Pause() {
189      base.Pause();
190      pausePending = true;
191      if (currentOperator != null) currentOperator.Abort();
192    }
193
194    protected override void OnPaused() {
195      Log.LogMessage("Engine paused");
196      base.OnPaused();
197    }
198
199    public override void Stop() {
200      CurrentOperation = null;
201      base.Stop();
202      stopPending = true;
203      if (currentOperator != null) currentOperator.Abort();
204      ignoreNextBreakpoint = false;
205      if (ExecutionState == ExecutionState.Paused) OnStopped();
206    }
207
208    protected override void OnStopped() {
209      Log.LogMessage("Engine stopped");
210      base.OnStopped();
211    }
212
213    protected override void OnExceptionOccurred(Exception exception) {
214      Log.LogException(exception);
215      base.OnExceptionOccurred(exception);
216    }
217
218    private void Run(object state) {
219      OnStarted();
220      pausePending = stopPending = false;
221
222      lastUpdateTime = DateTime.Now;
223      timer.Start();
224      while (!pausePending && !stopPending && CanContinue) {
225        ProcessNextOperation();
226      }
227      timer.Stop();
228      ExecutionTime += DateTime.Now - lastUpdateTime;
229
230      if (pausePending) OnPaused();
231      else OnStopped();
232    }
233
234    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
235      DateTime now = DateTime.Now;
236      ExecutionTime += now - lastUpdateTime;
237      lastUpdateTime = now;
238    }
239    #endregion
240
241    #region Methods
242
243    public virtual bool CanContinue {
244      get { return CurrentOperation != null || ExecutionStack.Count > 0; }
245    }
246
247    /// <summary>
248    /// Deals with the next operation, if it is an <see cref="AtomicOperation"/> it is executed,
249    /// if it is a <see cref="CompositeOperation"/> its single operations are pushed on the execution stack.
250    /// </summary>
251    /// <remarks>If an error occurs during the execution the operation is aborted and the operation
252    /// is pushed on the stack again.<br/>
253    /// If the execution was successful <see cref="EngineBase.OnOperationExecuted"/> is called.</remarks>
254    protected virtual void ProcessNextOperation() {
255      try {
256        IAtomicOperation atomicOperation = CurrentOperation as IAtomicOperation;
257        OperationCollection operations = CurrentOperation as OperationCollection;
258        if (atomicOperation != null && operations != null)
259          throw new InvalidOperationException("Current operation is both atomic and an operation collection");
260
261        if (atomicOperation != null) {
262          Log.LogMessage(string.Format("Performing atomic operation {0}", Name(atomicOperation)));
263          PerformAtomicOperation(atomicOperation);
264        } else if (operations != null) {
265          Log.LogMessage("Expanding operation collection");
266          ExecutionStack.AddRange(operations.Reverse());
267          CurrentOperation = null;
268        } else if (ExecutionStack.Count > 0) {
269          Log.LogMessage("Popping execution stack");
270          CurrentOperation = ExecutionStack.Last();
271          ExecutionStack.RemoveAt(ExecutionStack.Count - 1);
272        } else {
273          Log.LogMessage("Nothing to do");
274        }
275        GenerateOperationTrace();
276      }
277      catch (Exception x) {
278        OnExceptionOccurred(x);
279      }
280    }
281
282    private void GenerateOperationTrace() {
283      var operation = CurrentOperation as IAtomicOperation;
284      if (operation != null) {
285        List<IOperator> trace = new List<IOperator>();
286        while (operation != null) {
287          trace.Add(operation.Operator);
288          IAtomicOperation parent = null;
289          operatorParents.TryGetValue(operation, out parent);
290          operation = parent;
291        }
292        trace.Reverse();
293        OperatorTrace.Clear();
294        OperatorTrace.AddRange(trace);
295      }
296    }
297
298    protected virtual void PerformAtomicOperation(IAtomicOperation operation) {
299      if (operation != null) {
300        if (operation.Operator.Breakpoint) {
301          if (ignoreNextBreakpoint) {
302            ignoreNextBreakpoint = false;
303          } else {
304            ignoreNextBreakpoint = true;
305            Log.LogMessage(string.Format("Breaking before: {0}", Name(operation)));
306            Pause();
307            return;
308          }
309        }
310        try {
311          currentOperator = operation.Operator;
312          IOperation successor = operation.Operator.Execute((IExecutionContext)operation);
313          if (successor != null) {
314            AssignParents(operation, successor);
315            ExecutionStack.Add(successor);
316          }
317          currentOperator = null;
318          CurrentOperation = null;
319        }
320        catch (Exception ex) {
321          OnExceptionOccurred(new OperatorExecutionException(operation.Operator, ex));
322          Pause();
323        }
324      }
325    }
326
327    private void AssignParents(IAtomicOperation parent, IOperation successor) {
328      OperationCollection operations = successor as OperationCollection;
329      if (operations != null)
330        foreach (var op in operations)
331          AssignParents(parent, op);
332      IAtomicOperation atomicOperation = successor as IAtomicOperation;
333      if (atomicOperation != null && atomicOperation.Operator != null && !operatorParents.ContainsKey(atomicOperation))
334        operatorParents[atomicOperation] = parent;
335    }
336
337    protected virtual string Name(IAtomicOperation operation) {
338      return string.IsNullOrEmpty(operation.Operator.Name) ? operation.Operator.ItemName : operation.Operator.Name;
339    }
340
341    #endregion
342  }
343}
Note: See TracBrowser for help on using the repository browser.