Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Analysis.AlgorithmBehavior/HeuristicLab.Analysis.SolutionCaching/3.3/RunCollectionModifiers/RunCollectionModifierExecutable.cs @ 10114

Last change on this file since 10114 was 10114, checked in by ascheibe, 10 years ago

#1886 added tasks and hive tasks for RunCollectionModifiers

File size: 7.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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 System.Threading.Tasks;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32
33namespace HeuristicLab.Analysis.SolutionCaching {
34  [Item("RunCollectionModifierExecutable", "An executable that runs RunCollectionModifiers on RunCollections.")]
35  [StorableClass]
36  public class RunCollectionModifierExecutable : ParameterizedNamedItem, IExecutable {
37    [Storable]
38    protected ExecutionState executionState;
39    public ExecutionState ExecutionState {
40      get { return executionState; }
41      set {
42        if (value != executionState) {
43          executionState = value;
44          OnExecutionStateChanged();
45        }
46      }
47    }
48
49    [Storable]
50    protected TimeSpan executionTime;
51    public TimeSpan ExecutionTime {
52      get { return executionTime; }
53      set {
54        if (value != executionTime) {
55          executionTime = value;
56          OnExecutionTimeChanged();
57        }
58      }
59    }
60
61    public ValueParameter<ItemList<IRunCollectionModifier>> RunCollectionModifiersParameter {
62      get { return (ValueParameter<ItemList<IRunCollectionModifier>>)Parameters["RunCollectionModifiers"]; }
63    }
64    public ItemList<IRunCollectionModifier> RunCollectionModifiers {
65      get { return RunCollectionModifiersParameter.Value; }
66    }
67
68    [Storable]
69    protected RunCollection runCollection;
70    public RunCollection RunCollection {
71      get { return runCollection; }
72    }
73
74    [Storable]
75    protected Stack<IRunCollectionModifier> executionStack;
76    protected Stack<IRunCollectionModifier> ExecutionStack {
77      get { return executionStack; }
78    }
79
80    [Storable]
81    protected ILog log;
82    public ILog Log {
83      get { return log; }
84    }
85
86    protected CancellationTokenSource cancellationTokenSource;
87    protected bool stopPending;
88
89    #region Constructors and Cloning
90    public RunCollectionModifierExecutable() {
91      Parameters.Add(new ValueParameter<ItemList<IRunCollectionModifier>>("RunCollectionModifiers", "List of RunCollectionModifiers that are executed. ", new ItemList<IRunCollectionModifier>()));
92      executionStack = new Stack<IRunCollectionModifier>();
93      runCollection = new RunCollection();
94      log = new Log();
95    }
96    [StorableConstructor]
97    protected RunCollectionModifierExecutable(bool deserializing) : base(deserializing) { }
98    protected RunCollectionModifierExecutable(RunCollectionModifierExecutable original, Cloner cloner)
99      : base(original, cloner) {
100      executionTime = original.executionTime;
101      executionState = original.executionState;
102      runCollection = (RunCollection)original.runCollection.Clone(cloner);
103      executionStack = new Stack<IRunCollectionModifier>();
104      foreach (var runCollectionModifier in original.executionStack) {
105        executionStack.Push(runCollectionModifier);
106      }
107      log = (ILog)original.log.Clone(cloner);
108    }
109    public override IDeepCloneable Clone(Cloner cloner) {
110      return new RunCollectionModifierExecutable(this, cloner);
111    }
112    #endregion
113
114    public void Pause() {
115      cancellationTokenSource.Cancel();
116    }
117
118    public void Prepare() {
119      executionStack.Clear();
120      foreach (var runCollectionModifier in RunCollectionModifiers) {
121        executionStack.Push(runCollectionModifier);
122      }
123    }
124
125    public void Start() {
126      cancellationTokenSource = new CancellationTokenSource();
127
128      Task task = Task.Factory.StartNew(RunModifiers, cancellationTokenSource.Token, cancellationTokenSource.Token);
129      task.ContinueWith(t => {
130        try {
131          t.Wait();
132        }
133        catch (AggregateException ex) {
134          try {
135            ex.Flatten().Handle(x => x is OperationCanceledException);
136          }
137          catch (AggregateException remaining) {
138            if (remaining.InnerExceptions.Count == 1) OnExceptionOccuted(remaining.InnerExceptions[0]);
139            else OnExceptionOccuted(remaining);
140          }
141        }
142        cancellationTokenSource.Dispose();
143        cancellationTokenSource = null;
144        if (stopPending) executionStack.Clear();
145        if (executionStack.Count == 0) OnStopped();
146        else OnPaused();
147      });
148    }
149
150    public void Stop() {
151      if (ExecutionState == ExecutionState.Paused) {
152        executionStack.Clear();
153        OnStopped();
154      } else {
155        stopPending = true;
156        cancellationTokenSource.Cancel();
157      }
158    }
159
160    public virtual void AddRunCollectionModifiers(IRunCollectionModifier modifier) {
161      RunCollectionModifiers.Add(modifier);
162    }
163
164    protected virtual void RunModifiers(object state) {
165      CancellationToken ct = (CancellationToken)state;
166      OnStarted();
167
168      IRunCollectionModifier next;
169      while (executionStack.Count > 0) {
170        next = executionStack.Pop();
171        try {
172          ct.ThrowIfCancellationRequested();
173          next.Modify(runCollection.ToList());
174        }
175        catch (Exception ex) {
176          executionStack.Push(next);
177          if (ex is OperationCanceledException) throw ex;
178          else throw new Exception("IRunCollectionModifier " + next + "threw an exception.", ex);
179        }
180      }
181    }
182
183    #region Events
184    public event EventHandler Prepared;
185    protected virtual void OnPrepared() {
186      ExecutionState = ExecutionState.Prepared;
187      EventHandler handler = Prepared;
188      if (handler != null) handler(this, EventArgs.Empty);
189    }
190    public event EventHandler Started;
191    protected virtual void OnStarted() {
192      executionState = ExecutionState.Started;
193      EventHandler handler = Started;
194      if (handler != null) handler(this, EventArgs.Empty);
195    }
196    public event EventHandler Stopped;
197    protected virtual void OnStopped() {
198      executionState = ExecutionState.Stopped;
199      EventHandler handler = Stopped;
200      if (handler != null) handler(this, EventArgs.Empty);
201    }
202    public event EventHandler Paused;
203    protected virtual void OnPaused() {
204      executionState = ExecutionState.Paused;
205      EventHandler handler = Paused;
206      if (handler != null) handler(this, EventArgs.Empty);
207    }
208    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
209    protected virtual void OnExceptionOccuted(Exception e) {
210      var eventArgs = new EventArgs<Exception>(e);
211      Log.LogException(e);
212      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
213      if (handler != null) handler(this, eventArgs);
214    }
215    public event EventHandler ExecutionTimeChanged;
216    protected virtual void OnExecutionTimeChanged() {
217      EventHandler handler = ExecutionTimeChanged;
218      if (handler != null) handler(this, EventArgs.Empty);
219    }
220    public event EventHandler ExecutionStateChanged;
221    protected virtual void OnExecutionStateChanged() {
222      EventHandler handler = ExecutionStateChanged;
223      if (handler != null) handler(this, EventArgs.Empty);
224    }
225    #endregion
226  }
227}
Note: See TracBrowser for help on using the repository browser.