Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2521_ProblemRefactoring/HeuristicLab.Optimization/3.3/Algorithms/Algorithm.cs @ 17612

Last change on this file since 17612 was 17612, checked in by mkommend, 4 years ago

#2521: Added first version of problem results.

File size: 14.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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 HEAL.Attic;
29using HeuristicLab.Collections;
30using HeuristicLab.Common;
31using HeuristicLab.Core;
32using HeuristicLab.Data;
33
34namespace HeuristicLab.Optimization {
35  /// <summary>
36  /// A base class for algorithms.
37  /// </summary>
38  [Item("Algorithm", "A base class for algorithms.")]
39  [StorableType("7879C550-E8C2-4121-84C3-DADB06BD5C96")]
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) {
89            Results.RemoveRange(problem.Results);
90            DeregisterProblemEvents();
91          }
92          problem = value;
93          if (problem != null) {
94            Results.AddRange(problem.Results);
95            RegisterProblemEvents();
96          }
97          OnProblemChanged();
98          Prepare();
99        }
100      }
101    }
102
103    [Storable]
104    private readonly ResultCollection results = new ResultCollection();
105    public ResultCollection Results {
106      get { return results; }
107    }
108
109    [Storable]
110    private bool storeAlgorithmInEachRun;
111    public bool StoreAlgorithmInEachRun {
112      get { return storeAlgorithmInEachRun; }
113      set {
114        if (storeAlgorithmInEachRun != value) {
115          storeAlgorithmInEachRun = value;
116          OnStoreAlgorithmInEachRunChanged();
117        }
118      }
119    }
120
121    [Storable]
122    protected int runsCounter;
123
124    [Storable]
125    private RunCollection runs;
126    public RunCollection Runs {
127      get { return runs; }
128      protected set {
129        if (value == null) throw new ArgumentNullException();
130        if (runs != value) {
131          if (runs != null) DeregisterRunsEvents();
132          runs = value;
133          if (runs != null) RegisterRunsEvents();
134        }
135      }
136    }
137
138    public virtual IEnumerable<IOptimizer> NestedOptimizers {
139      get { return Enumerable.Empty<IOptimizer>(); }
140    }
141
142    protected Algorithm()
143      : base() {
144      executionState = ExecutionState.Stopped;
145      executionTime = TimeSpan.Zero;
146      storeAlgorithmInEachRun = false;
147      runsCounter = 0;
148      Runs = new RunCollection { OptimizerName = Name };
149    }
150    protected Algorithm(string name)
151      : base(name) {
152      executionState = ExecutionState.Stopped;
153      executionTime = TimeSpan.Zero;
154      storeAlgorithmInEachRun = false;
155      runsCounter = 0;
156      Runs = new RunCollection { OptimizerName = Name };
157    }
158    protected Algorithm(string name, ParameterCollection parameters)
159      : base(name, parameters) {
160      executionState = ExecutionState.Stopped;
161      executionTime = TimeSpan.Zero;
162      storeAlgorithmInEachRun = false;
163      runsCounter = 0;
164      Runs = new RunCollection { OptimizerName = Name };
165    }
166    protected Algorithm(string name, string description)
167      : base(name, description) {
168      executionState = ExecutionState.Stopped;
169      executionTime = TimeSpan.Zero;
170      storeAlgorithmInEachRun = false;
171      runsCounter = 0;
172      Runs = new RunCollection { OptimizerName = Name };
173    }
174    protected Algorithm(string name, string description, ParameterCollection parameters)
175      : base(name, description, parameters) {
176      executionState = ExecutionState.Stopped;
177      executionTime = TimeSpan.Zero;
178      storeAlgorithmInEachRun = false;
179      runsCounter = 0;
180      Runs = new RunCollection { OptimizerName = Name };
181    }
182    [StorableConstructor]
183    protected Algorithm(StorableConstructorFlag _) : base(_) { }
184    [StorableHook(HookType.AfterDeserialization)]
185    private void AfterDeserialization() {
186      Initialize();
187    }
188
189    protected Algorithm(Algorithm original, Cloner cloner)
190      : base(original, cloner) {
191      if (ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
192      executionState = original.executionState;
193      executionTime = original.executionTime;
194      problem = cloner.Clone(original.problem);
195      storeAlgorithmInEachRun = original.storeAlgorithmInEachRun;
196      runsCounter = original.runsCounter;
197      results = cloner.Clone(original.Results);
198      runs = cloner.Clone(original.runs);
199      Initialize();
200    }
201
202    private void Initialize() {
203      if (problem != null) RegisterProblemEvents();
204      if (runs != null) RegisterRunsEvents();
205    }
206
207    public virtual void Prepare() {
208      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
209        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
210
211      //TODO Reset all results
212      Results.Reset();
213    }
214    public void Prepare(bool clearRuns) {
215      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
216        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
217      if (clearRuns) runs.Clear();
218      Prepare();
219    }
220    public virtual void Start() {
221      Start(CancellationToken.None);
222    }
223    public virtual void Start(CancellationToken cancellationToken) {
224      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
225        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
226    }
227    public virtual async Task StartAsync() { await StartAsync(CancellationToken.None); }
228    public virtual async Task StartAsync(CancellationToken cancellationToken) {
229      await AsyncHelper.DoAsync(Start, cancellationToken);
230    }
231    public virtual void Pause() {
232      if (ExecutionState != ExecutionState.Started)
233        throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
234    }
235    public virtual void Stop() {
236      if ((ExecutionState != ExecutionState.Started) && (ExecutionState != ExecutionState.Paused))
237        throw new InvalidOperationException(string.Format("Stop not allowed in execution state \"{0}\".", ExecutionState));
238    }
239
240    public override void CollectParameterValues(IDictionary<string, IItem> values) {
241      base.CollectParameterValues(values);
242      values.Add("Algorithm Name", new StringValue(Name));
243      values.Add("Algorithm Type", new StringValue(this.GetType().GetPrettyName()));
244      if (Problem != null) {
245        Problem.CollectParameterValues(values);
246        values.Add("Problem Name", new StringValue(Problem.Name));
247        values.Add("Problem Type", new StringValue(Problem.GetType().GetPrettyName()));
248      }
249    }
250    public virtual void CollectResultValues(IDictionary<string, IItem> values) {
251      values.Add("Execution Time", new TimeSpanValue(ExecutionTime));
252      Results.CollectResultValues(values);
253    }
254
255    protected override IEnumerable<KeyValuePair<string, IItem>> GetCollectedValues(IValueParameter param) {
256      var children = base.GetCollectedValues(param);
257      foreach (var child in children) {
258        if (child.Value is IOperator)
259          yield return new KeyValuePair<string, IItem>(child.Key, new StringValue(((IOperator)child.Value).Name));
260        else yield return child;
261      }
262    }
263
264    #region Events
265    protected override void OnNameChanged() {
266      base.OnNameChanged();
267      Runs.OptimizerName = Name;
268    }
269
270    public event EventHandler ExecutionStateChanged;
271    protected virtual void OnExecutionStateChanged() {
272      EventHandler handler = ExecutionStateChanged;
273      if (handler != null) handler(this, EventArgs.Empty);
274    }
275    public event EventHandler ExecutionTimeChanged;
276    protected virtual void OnExecutionTimeChanged() {
277      EventHandler handler = ExecutionTimeChanged;
278      if (handler != null) handler(this, EventArgs.Empty);
279    }
280    public event EventHandler ProblemChanged;
281    protected virtual void OnProblemChanged() {
282      EventHandler handler = ProblemChanged;
283      if (handler != null) handler(this, EventArgs.Empty);
284    }
285    public event EventHandler StoreAlgorithmInEachRunChanged;
286    protected virtual void OnStoreAlgorithmInEachRunChanged() {
287      EventHandler handler = StoreAlgorithmInEachRunChanged;
288      if (handler != null) handler(this, EventArgs.Empty);
289    }
290    public event EventHandler Prepared;
291    protected virtual void OnPrepared() {
292      ExecutionTime = TimeSpan.Zero;
293      foreach (IStatefulItem statefulObject in this.GetObjectGraphObjects(new HashSet<object>() { Runs }).OfType<IStatefulItem>()) {
294        statefulObject.InitializeState();
295      }
296      ExecutionState = ExecutionState.Prepared;
297      EventHandler handler = Prepared;
298      if (handler != null) handler(this, EventArgs.Empty);
299    }
300    public event EventHandler Started;
301    protected virtual void OnStarted() {
302      foreach (var param in Parameters.Concat(Problem.Parameters).OfType<IResultParameter>())
303        param.ResultCollection = results;
304      ExecutionState = ExecutionState.Started;
305      EventHandler handler = Started;
306      if (handler != null) handler(this, EventArgs.Empty);
307    }
308    public event EventHandler Paused;
309    protected virtual void OnPaused() {
310      foreach (var param in Parameters.Concat(Problem.Parameters).OfType<IResultParameter>())
311        param.ResultCollection = null;
312      ExecutionState = ExecutionState.Paused;
313      EventHandler handler = Paused;
314      if (handler != null) handler(this, EventArgs.Empty);
315    }
316    public event EventHandler Stopped;
317    protected virtual void OnStopped() {
318      try {
319        foreach (
320          IStatefulItem statefulObject in
321          this.GetObjectGraphObjects(new HashSet<object>() { Runs }).OfType<IStatefulItem>()) {
322          statefulObject.ClearState();
323        }
324        runsCounter++;
325        try {
326          runs.Add(new Run(string.Format("{0} Run {1}", Name, runsCounter), this));
327        } catch (ArgumentException e) {
328          OnExceptionOccurred(new InvalidOperationException("Run creation failed.", e));
329        }
330      } finally {
331        foreach (var param in Parameters.Concat(Problem.Parameters).OfType<IResultParameter>())
332          param.ResultCollection = null;
333        ExecutionState = ExecutionState.Stopped;
334        EventHandler handler = Stopped;
335        if (handler != null) handler(this, EventArgs.Empty);
336      }
337    }
338    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
339    protected virtual void OnExceptionOccurred(Exception exception) {
340      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
341      if (handler != null) handler(this, new EventArgs<Exception>(exception));
342    }
343
344    protected virtual void DeregisterProblemEvents() {
345      problem.Reset -= new EventHandler(Problem_Reset);
346    }
347    protected virtual void RegisterProblemEvents() {
348      problem.Reset += new EventHandler(Problem_Reset);
349    }
350    protected virtual void Problem_Reset(object sender, EventArgs e) {
351      Prepare();
352    }
353
354    protected virtual void DeregisterRunsEvents() {
355      runs.CollectionReset -= new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
356    }
357    protected virtual void RegisterRunsEvents() {
358      runs.CollectionReset += new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
359    }
360    protected virtual void Runs_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
361      runsCounter = runs.Count;
362    }
363    #endregion
364  }
365}
Note: See TracBrowser for help on using the repository browser.