Free cookie consent management tool by TermsFeed Policy Generator

source: branches/1614_GeneralizedQAP/HeuristicLab.Optimization/3.3/Algorithms/Algorithm.cs

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

#1614: updated to new persistence and .NET 4.6.1

File size: 13.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2019 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 HEAL.Attic;
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) 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(StorableConstructorFlag _) : base(_) { }
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 virtual void Start() {
207      Start(CancellationToken.None);
208    }
209    public virtual void Start(CancellationToken cancellationToken) {
210      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
211        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
212    }
213    public virtual async Task StartAsync() { await StartAsync(CancellationToken.None); }
214    public virtual async Task StartAsync(CancellationToken cancellationToken) {
215      await AsyncHelper.DoAsync(Start, cancellationToken);
216    }
217    public virtual void Pause() {
218      if (ExecutionState != ExecutionState.Started)
219        throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
220    }
221    public virtual void Stop() {
222      if ((ExecutionState != ExecutionState.Started) && (ExecutionState != ExecutionState.Paused))
223        throw new InvalidOperationException(string.Format("Stop not allowed in execution state \"{0}\".", ExecutionState));
224    }
225
226    public override void CollectParameterValues(IDictionary<string, IItem> values) {
227      base.CollectParameterValues(values);
228      values.Add("Algorithm Name", new StringValue(Name));
229      values.Add("Algorithm Type", new StringValue(this.GetType().GetPrettyName()));
230      if (Problem != null) {
231        Problem.CollectParameterValues(values);
232        values.Add("Problem Name", new StringValue(Problem.Name));
233        values.Add("Problem Type", new StringValue(Problem.GetType().GetPrettyName()));
234      }
235    }
236    public virtual void CollectResultValues(IDictionary<string, IItem> values) {
237      if (!Results.ContainsKey("Execution Time"))
238        values.Add("Execution Time", new TimeSpanValue(ExecutionTime));
239      Results.CollectResultValues(values);
240    }
241
242    protected override IEnumerable<KeyValuePair<string, IItem>> GetCollectedValues(IValueParameter param) {
243      var children = base.GetCollectedValues(param);
244      foreach (var child in children) {
245        if (child.Value is IOperator)
246          yield return new KeyValuePair<string, IItem>(child.Key, new StringValue(((IOperator)child.Value).Name));
247        else yield return child;
248      }
249    }
250
251    #region Events
252    protected override void OnNameChanged() {
253      base.OnNameChanged();
254      Runs.OptimizerName = Name;
255    }
256
257    public event EventHandler ExecutionStateChanged;
258    protected virtual void OnExecutionStateChanged() {
259      EventHandler handler = ExecutionStateChanged;
260      if (handler != null) handler(this, EventArgs.Empty);
261    }
262    public event EventHandler ExecutionTimeChanged;
263    protected virtual void OnExecutionTimeChanged() {
264      EventHandler handler = ExecutionTimeChanged;
265      if (handler != null) handler(this, EventArgs.Empty);
266    }
267    public event EventHandler ProblemChanged;
268    protected virtual void OnProblemChanged() {
269      EventHandler handler = ProblemChanged;
270      if (handler != null) handler(this, EventArgs.Empty);
271    }
272    public event EventHandler StoreAlgorithmInEachRunChanged;
273    protected virtual void OnStoreAlgorithmInEachRunChanged() {
274      EventHandler handler = StoreAlgorithmInEachRunChanged;
275      if (handler != null) handler(this, EventArgs.Empty);
276    }
277    public event EventHandler Prepared;
278    protected virtual void OnPrepared() {
279      ExecutionTime = TimeSpan.Zero;
280      foreach (IStatefulItem statefulObject in this.GetObjectGraphObjects(new HashSet<object>() { Runs }).OfType<IStatefulItem>()) {
281        statefulObject.InitializeState();
282      }
283      ExecutionState = ExecutionState.Prepared;
284      EventHandler handler = Prepared;
285      if (handler != null) handler(this, EventArgs.Empty);
286    }
287    public event EventHandler Started;
288    protected virtual void OnStarted() {
289      ExecutionState = ExecutionState.Started;
290      EventHandler handler = Started;
291      if (handler != null) handler(this, EventArgs.Empty);
292    }
293    public event EventHandler Paused;
294    protected virtual void OnPaused() {
295      ExecutionState = ExecutionState.Paused;
296      EventHandler handler = Paused;
297      if (handler != null) handler(this, EventArgs.Empty);
298    }
299    public event EventHandler Stopped;
300    protected virtual void OnStopped() {
301      try {
302        foreach (
303          IStatefulItem statefulObject in
304          this.GetObjectGraphObjects(new HashSet<object>() {Runs}).OfType<IStatefulItem>()) {
305          statefulObject.ClearState();
306        }
307        runsCounter++;
308        try {
309          runs.Add(new Run(string.Format("{0} Run {1}", Name, runsCounter), this));
310        }
311        catch (ArgumentException e) {
312          OnExceptionOccurred(new InvalidOperationException("Run creation failed.", e));
313        }
314      }   
315      finally {
316        ExecutionState = ExecutionState.Stopped;
317        EventHandler handler = Stopped;
318        if (handler != null) handler(this, EventArgs.Empty);
319      }
320    }
321    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
322    protected virtual void OnExceptionOccurred(Exception exception) {
323      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
324      if (handler != null) handler(this, new EventArgs<Exception>(exception));
325    }
326
327    protected virtual void DeregisterProblemEvents() {
328      problem.OperatorsChanged -= new EventHandler(Problem_OperatorsChanged);
329      problem.Reset -= new EventHandler(Problem_Reset);
330    }
331    protected virtual void RegisterProblemEvents() {
332      problem.OperatorsChanged += new EventHandler(Problem_OperatorsChanged);
333      problem.Reset += new EventHandler(Problem_Reset);
334    }
335    protected virtual void Problem_OperatorsChanged(object sender, EventArgs e) { }
336    protected virtual void Problem_Reset(object sender, EventArgs e) {
337      Prepare();
338    }
339
340    protected virtual void DeregisterRunsEvents() {
341      runs.CollectionReset -= new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
342    }
343    protected virtual void RegisterRunsEvents() {
344      runs.CollectionReset += new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
345    }
346    protected virtual void Runs_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
347      runsCounter = runs.Count;
348    }
349    #endregion
350  }
351}
Note: See TracBrowser for help on using the repository browser.