Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GeneralizedQAP/HeuristicLab.Optimization/3.3/Algorithms/Algorithm.cs @ 15603

Last change on this file since 15603 was 15603, checked in by abeham, 6 years ago

#1614: Implemented changed behavior to measure execution time (cf. #2869)

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