Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2258: improved cancellation support

File size: 13.2 KB
RevLine 
[2851]1#region License Information
2/* HeuristicLab
[12012]3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[2851]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;
[3260]23using System.Collections.Generic;
[2851]24using System.Drawing;
[5419]25using System.Linq;
[13349]26using System.Threading;
27using System.Threading.Tasks;
[3716]28using HeuristicLab.Collections;
[2851]29using HeuristicLab.Common;
30using HeuristicLab.Core;
[3694]31using HeuristicLab.Data;
[2851]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.")]
[3017]39  [StorableClass]
[4437]40  public abstract class Algorithm : ParameterizedNamedItem, IAlgorithm {
[7201]41    public static new Image StaticItemImage {
42      get { return HeuristicLab.Common.Resources.VSImageLibrary.Event; }
43    }
[2851]44    public override Image ItemImage {
[3351]45      get {
[5287]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;
[7201]50        else return base.ItemImage;
[3351]51      }
[2851]52    }
53
[3262]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();
[3351]62          OnItemImageChanged();
[3262]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
[2852]77    public virtual Type ProblemType {
78      get { return typeof(IProblem); }
79    }
80
[3280]81    [Storable]
[2851]82    private IProblem problem;
83    public IProblem Problem {
84      get { return problem; }
85      set {
86        if (problem != value) {
[2852]87          if ((value != null) && !ProblemType.IsInstanceOfType(value)) throw new ArgumentException("Invalid problem type.");
88          if (problem != null) DeregisterProblemEvents();
[2851]89          problem = value;
[2852]90          if (problem != null) RegisterProblemEvents();
[2851]91          OnProblemChanged();
[2864]92          Prepare();
[2851]93        }
94      }
95    }
96
[3226]97    public abstract ResultCollection Results { get; }
[2882]98
[3275]99    [Storable]
[4102]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]
[3280]112    protected int runsCounter;
113
114    [Storable]
[3275]115    private RunCollection runs;
116    public RunCollection Runs {
117      get { return runs; }
[3716]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      }
[3275]126    }
127
[5419]128    public virtual IEnumerable<IOptimizer> NestedOptimizers {
129      get { return Enumerable.Empty<IOptimizer>(); }
130    }
131
[3262]132    protected Algorithm()
133      : base() {
134      executionState = ExecutionState.Stopped;
135      executionTime = TimeSpan.Zero;
[5203]136      storeAlgorithmInEachRun = false;
[3280]137      runsCounter = 0;
[8962]138      Runs = new RunCollection { OptimizerName = Name };
[2851]139    }
[3262]140    protected Algorithm(string name)
141      : base(name) {
142      executionState = ExecutionState.Stopped;
143      executionTime = TimeSpan.Zero;
[5203]144      storeAlgorithmInEachRun = false;
[3280]145      runsCounter = 0;
[8962]146      Runs = new RunCollection { OptimizerName = Name };
[2851]147    }
[3262]148    protected Algorithm(string name, ParameterCollection parameters)
149      : base(name, parameters) {
150      executionState = ExecutionState.Stopped;
151      executionTime = TimeSpan.Zero;
[5203]152      storeAlgorithmInEachRun = false;
[3280]153      runsCounter = 0;
[8962]154      Runs = new RunCollection { OptimizerName = Name };
[3262]155    }
156    protected Algorithm(string name, string description)
157      : base(name, description) {
158      executionState = ExecutionState.Stopped;
159      executionTime = TimeSpan.Zero;
[5203]160      storeAlgorithmInEachRun = false;
[3280]161      runsCounter = 0;
[8962]162      Runs = new RunCollection { OptimizerName = Name };
[3262]163    }
164    protected Algorithm(string name, string description, ParameterCollection parameters)
165      : base(name, description, parameters) {
166      executionState = ExecutionState.Stopped;
167      executionTime = TimeSpan.Zero;
[5203]168      storeAlgorithmInEachRun = false;
[3280]169      runsCounter = 0;
[8962]170      Runs = new RunCollection { OptimizerName = Name };
[3262]171    }
[3280]172    [StorableConstructor]
[5203]173    protected Algorithm(bool deserializing) : base(deserializing) { }
[3280]174    [StorableHook(HookType.AfterDeserialization)]
[4722]175    private void AfterDeserialization() {
176      Initialize();
[3280]177    }
178
[4722]179    protected Algorithm(Algorithm original, Cloner cloner)
180      : base(original, cloner) {
[3280]181      if (ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
[4722]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();
[2851]189    }
[4722]190
191    private void Initialize() {
192      if (problem != null) RegisterProblemEvents();
193      if (runs != null) RegisterRunsEvents();
[3286]194    }
[2851]195
[3275]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));
[3274]199    }
[3275]200    public void Prepare(bool clearRuns) {
[3262]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));
[3716]203      if (clearRuns) runs.Clear();
[3275]204      Prepare();
[2851]205    }
[13349]206    public void Start() {
207      StartAsync().Wait();
208    }
209    public async Task StartAsync() {
[13354]210      await StartAsync(CancellationToken.None);
[13349]211    }
212    public virtual async Task StartAsync(CancellationToken cancellationToken) {
[3262]213      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
214        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
[2851]215    }
[3262]216    public virtual void Pause() {
217      if (ExecutionState != ExecutionState.Started)
218        throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
[2851]219    }
[3262]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    }
[2851]224
[3260]225    public override void CollectParameterValues(IDictionary<string, IItem> values) {
226      base.CollectParameterValues(values);
[3785]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      }
[3260]234    }
235    public virtual void CollectResultValues(IDictionary<string, IItem> values) {
[3694]236      values.Add("Execution Time", new TimeSpanValue(ExecutionTime));
[11762]237      Results.CollectResultValues(values);
[3260]238    }
239
[7706]240    protected override IEnumerable<KeyValuePair<string, IItem>> GetCollectedValues(IValueParameter param) {
241      var children = base.GetCollectedValues(param);
[7579]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
[2851]249    #region Events
[8738]250    protected override void OnNameChanged() {
251      base.OnNameChanged();
[8962]252      Runs.OptimizerName = Name;
[8738]253    }
254
[3262]255    public event EventHandler ExecutionStateChanged;
256    protected virtual void OnExecutionStateChanged() {
257      EventHandler handler = ExecutionStateChanged;
258      if (handler != null) handler(this, EventArgs.Empty);
[2851]259    }
260    public event EventHandler ExecutionTimeChanged;
261    protected virtual void OnExecutionTimeChanged() {
[3262]262      EventHandler handler = ExecutionTimeChanged;
263      if (handler != null) handler(this, EventArgs.Empty);
[2851]264    }
[3262]265    public event EventHandler ProblemChanged;
266    protected virtual void OnProblemChanged() {
267      EventHandler handler = ProblemChanged;
268      if (handler != null) handler(this, EventArgs.Empty);
[3226]269    }
[4102]270    public event EventHandler StoreAlgorithmInEachRunChanged;
271    protected virtual void OnStoreAlgorithmInEachRunChanged() {
272      EventHandler handler = StoreAlgorithmInEachRunChanged;
273      if (handler != null) handler(this, EventArgs.Empty);
274    }
[2851]275    public event EventHandler Prepared;
276    protected virtual void OnPrepared() {
[3275]277      ExecutionTime = TimeSpan.Zero;
[8212]278      foreach (IStatefulItem statefulObject in this.GetObjectGraphObjects(new HashSet<object>() { Runs }).OfType<IStatefulItem>()) {
[6103]279        statefulObject.InitializeState();
280      }
[8155]281      ExecutionState = ExecutionState.Prepared;
[3262]282      EventHandler handler = Prepared;
283      if (handler != null) handler(this, EventArgs.Empty);
[2851]284    }
285    public event EventHandler Started;
286    protected virtual void OnStarted() {
[3262]287      ExecutionState = ExecutionState.Started;
288      EventHandler handler = Started;
289      if (handler != null) handler(this, EventArgs.Empty);
[2851]290    }
[3262]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    }
[2851]297    public event EventHandler Stopped;
298    protected virtual void OnStopped() {
[8212]299      foreach (IStatefulItem statefulObject in this.GetObjectGraphObjects(new HashSet<object>() { Runs }).OfType<IStatefulItem>()) {
[6103]300        statefulObject.ClearState();
301      }
[3280]302      runsCounter++;
[3694]303      runs.Add(new Run(string.Format("{0} Run {1}", Name, runsCounter), this));
[8155]304      ExecutionState = ExecutionState.Stopped;
[3262]305      EventHandler handler = Stopped;
306      if (handler != null) handler(this, EventArgs.Empty);
[2851]307    }
308    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
309    protected virtual void OnExceptionOccurred(Exception exception) {
[3262]310      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
311      if (handler != null) handler(this, new EventArgs<Exception>(exception));
[2851]312    }
[2975]313
[2852]314    protected virtual void DeregisterProblemEvents() {
[2975]315      problem.OperatorsChanged -= new EventHandler(Problem_OperatorsChanged);
[3739]316      problem.Reset -= new EventHandler(Problem_Reset);
[2852]317    }
318    protected virtual void RegisterProblemEvents() {
[2975]319      problem.OperatorsChanged += new EventHandler(Problem_OperatorsChanged);
[3739]320      problem.Reset += new EventHandler(Problem_Reset);
[2852]321    }
[2975]322    protected virtual void Problem_OperatorsChanged(object sender, EventArgs e) { }
[3739]323    protected virtual void Problem_Reset(object sender, EventArgs e) {
324      Prepare();
325    }
[3716]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    }
[2851]336    #endregion
337  }
338}
Note: See TracBrowser for help on using the repository browser.