Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Async/HeuristicLab.Optimization/3.3/Algorithms/Algorithm.cs @ 13349

Last change on this file since 13349 was 13349, checked in by jkarder, 9 years ago

#2258: added StartAsync to IExecutable

File size: 13.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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.Drawing;
25using System.Linq;
26using System.Threading;
27using System.Threading.Tasks;
28using HeuristicLab.Collections;
29using HeuristicLab.Common;
30using HeuristicLab.Core;
31using HeuristicLab.Data;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33
34namespace HeuristicLab.Optimization {
35  /// <summary>
36  /// A base class for algorithms.
37  /// </summary>
38  [Item("Algorithm", "A base class for algorithms.")]
39  [StorableClass]
40  public abstract class Algorithm : ParameterizedNamedItem, IAlgorithm {
41    public static new Image StaticItemImage {
42      get { return HeuristicLab.Common.Resources.VSImageLibrary.Event; }
43    }
44    public override Image ItemImage {
45      get {
46        if (ExecutionState == ExecutionState.Prepared) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutablePrepared;
47        else if (ExecutionState == ExecutionState.Started) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutableStarted;
48        else if (ExecutionState == ExecutionState.Paused) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutablePaused;
49        else if (ExecutionState == ExecutionState.Stopped) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutableStopped;
50        else return base.ItemImage;
51      }
52    }
53
54    [Storable]
55    private ExecutionState executionState;
56    public ExecutionState ExecutionState {
57      get { return executionState; }
58      private set {
59        if (executionState != value) {
60          executionState = value;
61          OnExecutionStateChanged();
62          OnItemImageChanged();
63        }
64      }
65    }
66
67    [Storable]
68    private TimeSpan executionTime;
69    public TimeSpan ExecutionTime {
70      get { return executionTime; }
71      protected set {
72        executionTime = value;
73        OnExecutionTimeChanged();
74      }
75    }
76
77    public virtual Type ProblemType {
78      get { return typeof(IProblem); }
79    }
80
81    [Storable]
82    private IProblem problem;
83    public IProblem Problem {
84      get { return problem; }
85      set {
86        if (problem != value) {
87          if ((value != null) && !ProblemType.IsInstanceOfType(value)) throw new ArgumentException("Invalid problem type.");
88          if (problem != null) DeregisterProblemEvents();
89          problem = value;
90          if (problem != null) RegisterProblemEvents();
91          OnProblemChanged();
92          Prepare();
93        }
94      }
95    }
96
97    public abstract ResultCollection Results { get; }
98
99    [Storable]
100    private bool storeAlgorithmInEachRun;
101    public bool StoreAlgorithmInEachRun {
102      get { return storeAlgorithmInEachRun; }
103      set {
104        if (storeAlgorithmInEachRun != value) {
105          storeAlgorithmInEachRun = value;
106          OnStoreAlgorithmInEachRunChanged();
107        }
108      }
109    }
110
111    [Storable]
112    protected int runsCounter;
113
114    [Storable]
115    private RunCollection runs;
116    public RunCollection Runs {
117      get { return runs; }
118      protected set {
119        if (value == null) throw new ArgumentNullException();
120        if (runs != value) {
121          if (runs != null) DeregisterRunsEvents();
122          runs = value;
123          if (runs != null) RegisterRunsEvents();
124        }
125      }
126    }
127
128    public virtual IEnumerable<IOptimizer> NestedOptimizers {
129      get { return Enumerable.Empty<IOptimizer>(); }
130    }
131
132    protected Algorithm()
133      : base() {
134      executionState = ExecutionState.Stopped;
135      executionTime = TimeSpan.Zero;
136      storeAlgorithmInEachRun = false;
137      runsCounter = 0;
138      Runs = new RunCollection { OptimizerName = Name };
139    }
140    protected Algorithm(string name)
141      : base(name) {
142      executionState = ExecutionState.Stopped;
143      executionTime = TimeSpan.Zero;
144      storeAlgorithmInEachRun = false;
145      runsCounter = 0;
146      Runs = new RunCollection { OptimizerName = Name };
147    }
148    protected Algorithm(string name, ParameterCollection parameters)
149      : base(name, parameters) {
150      executionState = ExecutionState.Stopped;
151      executionTime = TimeSpan.Zero;
152      storeAlgorithmInEachRun = false;
153      runsCounter = 0;
154      Runs = new RunCollection { OptimizerName = Name };
155    }
156    protected Algorithm(string name, string description)
157      : base(name, description) {
158      executionState = ExecutionState.Stopped;
159      executionTime = TimeSpan.Zero;
160      storeAlgorithmInEachRun = false;
161      runsCounter = 0;
162      Runs = new RunCollection { OptimizerName = Name };
163    }
164    protected Algorithm(string name, string description, ParameterCollection parameters)
165      : base(name, description, parameters) {
166      executionState = ExecutionState.Stopped;
167      executionTime = TimeSpan.Zero;
168      storeAlgorithmInEachRun = false;
169      runsCounter = 0;
170      Runs = new RunCollection { OptimizerName = Name };
171    }
172    [StorableConstructor]
173    protected Algorithm(bool deserializing) : base(deserializing) { }
174    [StorableHook(HookType.AfterDeserialization)]
175    private void AfterDeserialization() {
176      Initialize();
177    }
178
179    protected Algorithm(Algorithm original, Cloner cloner)
180      : base(original, cloner) {
181      if (ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
182      executionState = original.executionState;
183      executionTime = original.executionTime;
184      problem = cloner.Clone(original.problem);
185      storeAlgorithmInEachRun = original.storeAlgorithmInEachRun;
186      runsCounter = original.runsCounter;
187      runs = cloner.Clone(original.runs);
188      Initialize();
189    }
190
191    private void Initialize() {
192      if (problem != null) RegisterProblemEvents();
193      if (runs != null) RegisterRunsEvents();
194    }
195
196    public virtual void Prepare() {
197      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
198        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
199    }
200    public void Prepare(bool clearRuns) {
201      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
202        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
203      if (clearRuns) runs.Clear();
204      Prepare();
205    }
206    public void Start() {
207      StartAsync().Wait();
208    }
209    public async Task StartAsync() {
210      await StartAsync(new CancellationToken());
211    }
212    public virtual async Task StartAsync(CancellationToken cancellationToken) {
213      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
214        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
215    }
216    public virtual void Pause() {
217      if (ExecutionState != ExecutionState.Started)
218        throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
219    }
220    public virtual void Stop() {
221      if ((ExecutionState != ExecutionState.Started) && (ExecutionState != ExecutionState.Paused))
222        throw new InvalidOperationException(string.Format("Stop not allowed in execution state \"{0}\".", ExecutionState));
223    }
224
225    public override void CollectParameterValues(IDictionary<string, IItem> values) {
226      base.CollectParameterValues(values);
227      values.Add("Algorithm Name", new StringValue(Name));
228      values.Add("Algorithm Type", new StringValue(this.GetType().GetPrettyName()));
229      if (Problem != null) {
230        Problem.CollectParameterValues(values);
231        values.Add("Problem Name", new StringValue(Problem.Name));
232        values.Add("Problem Type", new StringValue(Problem.GetType().GetPrettyName()));
233      }
234    }
235    public virtual void CollectResultValues(IDictionary<string, IItem> values) {
236      values.Add("Execution Time", new TimeSpanValue(ExecutionTime));
237      Results.CollectResultValues(values);
238    }
239
240    protected override IEnumerable<KeyValuePair<string, IItem>> GetCollectedValues(IValueParameter param) {
241      var children = base.GetCollectedValues(param);
242      foreach (var child in children) {
243        if (child.Value is IOperator)
244          yield return new KeyValuePair<string, IItem>(child.Key, new StringValue(((IOperator)child.Value).Name));
245        else yield return child;
246      }
247    }
248
249    #region Events
250    protected override void OnNameChanged() {
251      base.OnNameChanged();
252      Runs.OptimizerName = Name;
253    }
254
255    public event EventHandler ExecutionStateChanged;
256    protected virtual void OnExecutionStateChanged() {
257      EventHandler handler = ExecutionStateChanged;
258      if (handler != null) handler(this, EventArgs.Empty);
259    }
260    public event EventHandler ExecutionTimeChanged;
261    protected virtual void OnExecutionTimeChanged() {
262      EventHandler handler = ExecutionTimeChanged;
263      if (handler != null) handler(this, EventArgs.Empty);
264    }
265    public event EventHandler ProblemChanged;
266    protected virtual void OnProblemChanged() {
267      EventHandler handler = ProblemChanged;
268      if (handler != null) handler(this, EventArgs.Empty);
269    }
270    public event EventHandler StoreAlgorithmInEachRunChanged;
271    protected virtual void OnStoreAlgorithmInEachRunChanged() {
272      EventHandler handler = StoreAlgorithmInEachRunChanged;
273      if (handler != null) handler(this, EventArgs.Empty);
274    }
275    public event EventHandler Prepared;
276    protected virtual void OnPrepared() {
277      ExecutionTime = TimeSpan.Zero;
278      foreach (IStatefulItem statefulObject in this.GetObjectGraphObjects(new HashSet<object>() { Runs }).OfType<IStatefulItem>()) {
279        statefulObject.InitializeState();
280      }
281      ExecutionState = ExecutionState.Prepared;
282      EventHandler handler = Prepared;
283      if (handler != null) handler(this, EventArgs.Empty);
284    }
285    public event EventHandler Started;
286    protected virtual void OnStarted() {
287      ExecutionState = ExecutionState.Started;
288      EventHandler handler = Started;
289      if (handler != null) handler(this, EventArgs.Empty);
290    }
291    public event EventHandler Paused;
292    protected virtual void OnPaused() {
293      ExecutionState = ExecutionState.Paused;
294      EventHandler handler = Paused;
295      if (handler != null) handler(this, EventArgs.Empty);
296    }
297    public event EventHandler Stopped;
298    protected virtual void OnStopped() {
299      foreach (IStatefulItem statefulObject in this.GetObjectGraphObjects(new HashSet<object>() { Runs }).OfType<IStatefulItem>()) {
300        statefulObject.ClearState();
301      }
302      runsCounter++;
303      runs.Add(new Run(string.Format("{0} Run {1}", Name, runsCounter), this));
304      ExecutionState = ExecutionState.Stopped;
305      EventHandler handler = Stopped;
306      if (handler != null) handler(this, EventArgs.Empty);
307    }
308    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
309    protected virtual void OnExceptionOccurred(Exception exception) {
310      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
311      if (handler != null) handler(this, new EventArgs<Exception>(exception));
312    }
313
314    protected virtual void DeregisterProblemEvents() {
315      problem.OperatorsChanged -= new EventHandler(Problem_OperatorsChanged);
316      problem.Reset -= new EventHandler(Problem_Reset);
317    }
318    protected virtual void RegisterProblemEvents() {
319      problem.OperatorsChanged += new EventHandler(Problem_OperatorsChanged);
320      problem.Reset += new EventHandler(Problem_Reset);
321    }
322    protected virtual void Problem_OperatorsChanged(object sender, EventArgs e) { }
323    protected virtual void Problem_Reset(object sender, EventArgs e) {
324      Prepare();
325    }
326
327    protected virtual void DeregisterRunsEvents() {
328      runs.CollectionReset -= new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
329    }
330    protected virtual void RegisterRunsEvents() {
331      runs.CollectionReset += new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
332    }
333    protected virtual void Runs_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
334      runsCounter = runs.Count;
335    }
336    #endregion
337  }
338}
Note: See TracBrowser for help on using the repository browser.