Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Optimization/3.3/Algorithms/Algorithm.cs @ 16804

Last change on this file since 16804 was 16565, checked in by gkronber, 6 years ago

#2520: merged changes from PersistenceOverhaul branch (r16451:16564) into trunk

File size: 13.5 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      values.Add("Execution Time", new TimeSpanValue(ExecutionTime));
238      Results.CollectResultValues(values);
239    }
240
241    protected override IEnumerable<KeyValuePair<string, IItem>> GetCollectedValues(IValueParameter param) {
242      var children = base.GetCollectedValues(param);
243      foreach (var child in children) {
244        if (child.Value is IOperator)
245          yield return new KeyValuePair<string, IItem>(child.Key, new StringValue(((IOperator)child.Value).Name));
246        else yield return child;
247      }
248    }
249
250    #region Events
251    protected override void OnNameChanged() {
252      base.OnNameChanged();
253      Runs.OptimizerName = Name;
254    }
255
256    public event EventHandler ExecutionStateChanged;
257    protected virtual void OnExecutionStateChanged() {
258      EventHandler handler = ExecutionStateChanged;
259      if (handler != null) handler(this, EventArgs.Empty);
260    }
261    public event EventHandler ExecutionTimeChanged;
262    protected virtual void OnExecutionTimeChanged() {
263      EventHandler handler = ExecutionTimeChanged;
264      if (handler != null) handler(this, EventArgs.Empty);
265    }
266    public event EventHandler ProblemChanged;
267    protected virtual void OnProblemChanged() {
268      EventHandler handler = ProblemChanged;
269      if (handler != null) handler(this, EventArgs.Empty);
270    }
271    public event EventHandler StoreAlgorithmInEachRunChanged;
272    protected virtual void OnStoreAlgorithmInEachRunChanged() {
273      EventHandler handler = StoreAlgorithmInEachRunChanged;
274      if (handler != null) handler(this, EventArgs.Empty);
275    }
276    public event EventHandler Prepared;
277    protected virtual void OnPrepared() {
278      ExecutionTime = TimeSpan.Zero;
279      foreach (IStatefulItem statefulObject in this.GetObjectGraphObjects(new HashSet<object>() { Runs }).OfType<IStatefulItem>()) {
280        statefulObject.InitializeState();
281      }
282      ExecutionState = ExecutionState.Prepared;
283      EventHandler handler = Prepared;
284      if (handler != null) handler(this, EventArgs.Empty);
285    }
286    public event EventHandler Started;
287    protected virtual void OnStarted() {
288      ExecutionState = ExecutionState.Started;
289      EventHandler handler = Started;
290      if (handler != null) handler(this, EventArgs.Empty);
291    }
292    public event EventHandler Paused;
293    protected virtual void OnPaused() {
294      ExecutionState = ExecutionState.Paused;
295      EventHandler handler = Paused;
296      if (handler != null) handler(this, EventArgs.Empty);
297    }
298    public event EventHandler Stopped;
299    protected virtual void OnStopped() {
300      try {
301        foreach (
302          IStatefulItem statefulObject in
303          this.GetObjectGraphObjects(new HashSet<object>() {Runs}).OfType<IStatefulItem>()) {
304          statefulObject.ClearState();
305        }
306        runsCounter++;
307        try {
308          runs.Add(new Run(string.Format("{0} Run {1}", Name, runsCounter), this));
309        }
310        catch (ArgumentException e) {
311          OnExceptionOccurred(new InvalidOperationException("Run creation failed.", e));
312        }
313      }   
314      finally {
315        ExecutionState = ExecutionState.Stopped;
316        EventHandler handler = Stopped;
317        if (handler != null) handler(this, EventArgs.Empty);
318      }
319    }
320    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
321    protected virtual void OnExceptionOccurred(Exception exception) {
322      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
323      if (handler != null) handler(this, new EventArgs<Exception>(exception));
324    }
325
326    protected virtual void DeregisterProblemEvents() {
327      problem.OperatorsChanged -= new EventHandler(Problem_OperatorsChanged);
328      problem.Reset -= new EventHandler(Problem_Reset);
329    }
330    protected virtual void RegisterProblemEvents() {
331      problem.OperatorsChanged += new EventHandler(Problem_OperatorsChanged);
332      problem.Reset += new EventHandler(Problem_Reset);
333    }
334    protected virtual void Problem_OperatorsChanged(object sender, EventArgs e) { }
335    protected virtual void Problem_Reset(object sender, EventArgs e) {
336      Prepare();
337    }
338
339    protected virtual void DeregisterRunsEvents() {
340      runs.CollectionReset -= new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
341    }
342    protected virtual void RegisterRunsEvents() {
343      runs.CollectionReset += new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
344    }
345    protected virtual void Runs_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
346      runsCounter = runs.Count;
347    }
348    #endregion
349  }
350}
Note: See TracBrowser for help on using the repository browser.