Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Analysis.AlgorithmBehavior/HeuristicLab.Analysis.SolutionCaching/3.3/RunCollectionModifiers/RunCollectionModifierTask.cs @ 10113

Last change on this file since 10113 was 10113, checked in by ascheibe, 11 years ago

#1886 added basic dialog for configuring a RunCollectionModifierTask

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