Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4945 was 4909, checked in by epitzer, 14 years ago

Several GUI improvements (#47)

  • add icons and tool tips
  • add support for suspending the operator trace view
  • faster skipping of stack-only operations
  • remove log view and execution time view
File size: 11.7 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      timer = new System.Timers.Timer(100);
43      timer.AutoReset = true;
44      timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
45    }
46    protected DebugEngine(DebugEngine original, Cloner cloner)
47      : base(original, cloner) {
48      if (original.ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
49      Log = cloner.Clone(original.Log);
50      ExecutionStack = cloner.Clone(original.ExecutionStack);
51      OperatorTrace = new ItemList<IOperator>(original.OperatorTrace.Select(op => cloner.Clone(op)));
52      operatorParents = original.operatorParents.ToDictionary(kvp => cloner.Clone(kvp.Key), kvp => cloner.Clone(kvp.Value));
53      pausePending = original.pausePending;
54      stopPending = original.stopPending;
55      timer = new System.Timers.Timer(100);
56      timer.AutoReset = true;
57      timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
58      this.currentOperation = cloner.Clone(original.currentOperation);
59      this.currentOperator = cloner.Clone(original.currentOperator);
60    }
61    public DebugEngine()
62      : base() {
63      Log = new Log();
64      ExecutionStack = new ExecutionStack();
65      OperatorTrace = new ItemList<IOperator>();
66      operatorParents = new Dictionary<IAtomicOperation, IAtomicOperation>();
67      pausePending = stopPending = false;
68      timer = new System.Timers.Timer(100);
69      timer.AutoReset = true;
70      timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
71    }
72
73    public override IDeepCloneable Clone(Cloner cloner) {
74      return new DebugEngine(this, cloner);
75    }
76
77    #endregion
78
79    #region Fields and Properties
80
81    [Storable]
82    public ILog Log { get; protected set; }
83
84    [Storable]
85    public ExecutionStack ExecutionStack { get; protected set; }
86
87    private bool pausePending, stopPending;
88    private DateTime lastUpdateTime;
89    private System.Timers.Timer timer;
90
91    [Storable]
92    private IOperator currentOperator;
93
94    [Storable]
95    private bool ignoreNextBreakpoint;
96
97    [Storable]
98    private IOperation currentOperation;
99    public virtual IOperation CurrentOperation {
100      get { return currentOperation; }
101      private set {
102        if (value == currentOperation)
103          return;
104        currentOperation = value;
105        OnOperationChanged(value);
106      }
107    }
108
109    public virtual IAtomicOperation CurrentAtomicOperation {
110      get { return CurrentOperation as IAtomicOperation; }
111    }
112
113    public virtual IExecutionContext CurrentExecutionContext {
114      get { return CurrentOperation as IExecutionContext; }
115    }
116
117    [Storable]
118    public ItemList<IOperator> OperatorTrace { get; private set; }
119
120    [Storable]
121    private Dictionary<IAtomicOperation, IAtomicOperation> operatorParents;
122
123    #endregion
124
125    #region Events
126
127    public event EventHandler<OperationChangedEventArgs> CurrentOperationChanged;
128
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          ExpandOperationCollection(operations);
267        } else if (ExecutionStack.Count > 0) {
268          Log.LogMessage("Popping execution stack");
269          CurrentOperation = ExecutionStack.Last();
270          ExecutionStack.RemoveAt(ExecutionStack.Count - 1);
271        } else {
272          Log.LogMessage("Nothing to do");
273        }
274        GenerateOperationTrace();
275      } catch (Exception x) {
276        OnExceptionOccurred(x);
277      }
278    }
279
280    private void GenerateOperationTrace() {
281      var operation = CurrentOperation as IAtomicOperation;
282      if (operation != null) {
283        List<IOperator> trace = new List<IOperator>();
284        while (operation != null) {
285          trace.Add(operation.Operator);
286          IAtomicOperation parent = null;
287          operatorParents.TryGetValue(operation, out parent);
288          operation = parent;
289        }
290        trace.Reverse();
291        OperatorTrace.Clear();
292        OperatorTrace.AddRange(trace);
293      }
294    }
295
296    protected virtual void PerformAtomicOperation(IAtomicOperation operation) {
297      if (operation != null) {
298        if (operation.Operator.Breakpoint) {
299          if (ignoreNextBreakpoint) {
300            ignoreNextBreakpoint = false;
301          } else {
302            ignoreNextBreakpoint = true;
303            Log.LogMessage(string.Format("Breaking before: {0}", Name(operation)));
304            Pause();
305            return;
306          }
307        }
308        try {
309          currentOperator = operation.Operator;
310          IOperation successor = operation.Operator.Execute((IExecutionContext)operation);
311          if (successor != null) {
312            AssignParents(operation, successor);
313            ExecutionStack.Add(successor);
314          }
315          currentOperator = null;
316          CurrentOperation = null;
317        } catch (Exception ex) {
318          OnExceptionOccurred(new OperatorExecutionException(operation.Operator, ex));
319          Pause();
320        }
321      }
322    }
323
324    private void AssignParents(IAtomicOperation parent, IOperation successor) {
325      OperationCollection operations = successor as OperationCollection;
326      if (operations != null)
327        foreach (var op in operations)
328          AssignParents(parent, op);
329      IAtomicOperation atomicOperation = successor as IAtomicOperation;
330      if (atomicOperation != null && atomicOperation.Operator != null && !operatorParents.ContainsKey(atomicOperation))
331        operatorParents[atomicOperation] = parent;
332    }
333
334    protected virtual void ExpandOperationCollection(OperationCollection operations) {
335      ExecutionStack.AddRange(operations.Reverse());
336      CurrentOperation = null;
337    }
338
339    protected virtual string Name(IAtomicOperation operation) {
340      return string.IsNullOrEmpty(operation.Operator.Name) ? operation.Operator.ItemName : operation.Operator.Name;
341    }
342
343    #endregion
344  }
345}
Note: See TracBrowser for help on using the repository browser.