Free cookie consent management tool by TermsFeed Policy Generator

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

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

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

File size: 13.5 KB
RevLine 
[2851]1#region License Information
2/* HeuristicLab
[16565]3 * Copyright (C) 2002-2019 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;
[15287]26using System.Threading;
27using System.Threading.Tasks;
[3716]28using HeuristicLab.Collections;
[2851]29using HeuristicLab.Common;
30using HeuristicLab.Core;
[3694]31using HeuristicLab.Data;
[16565]32using HEAL.Attic;
[2851]33
34namespace HeuristicLab.Optimization {
35  /// <summary>
36  /// A base class for algorithms.
37  /// </summary>
38  [Item("Algorithm", "A base class for algorithms.")]
[16565]39  [StorableType("7879C550-E8C2-4121-84C3-DADB06BD5C96")]
[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]
[16565]173    protected Algorithm(StorableConstructorFlag _) : base(_) { }
[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    }
[3262]206    public virtual void Start() {
[15287]207      Start(CancellationToken.None);
208    }
209    public virtual void Start(CancellationToken cancellationToken) {
[3262]210      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
211        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
[2851]212    }
[15287]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    }
[3262]217    public virtual void Pause() {
218      if (ExecutionState != ExecutionState.Started)
219        throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
[2851]220    }
[3262]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    }
[2851]225
[3260]226    public override void CollectParameterValues(IDictionary<string, IItem> values) {
227      base.CollectParameterValues(values);
[3785]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      }
[3260]235    }
236    public virtual void CollectResultValues(IDictionary<string, IItem> values) {
[3694]237      values.Add("Execution Time", new TimeSpanValue(ExecutionTime));
[11762]238      Results.CollectResultValues(values);
[3260]239    }
240
[7706]241    protected override IEnumerable<KeyValuePair<string, IItem>> GetCollectedValues(IValueParameter param) {
242      var children = base.GetCollectedValues(param);
[7579]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
[2851]250    #region Events
[8738]251    protected override void OnNameChanged() {
252      base.OnNameChanged();
[8962]253      Runs.OptimizerName = Name;
[8738]254    }
255
[3262]256    public event EventHandler ExecutionStateChanged;
257    protected virtual void OnExecutionStateChanged() {
258      EventHandler handler = ExecutionStateChanged;
259      if (handler != null) handler(this, EventArgs.Empty);
[2851]260    }
261    public event EventHandler ExecutionTimeChanged;
262    protected virtual void OnExecutionTimeChanged() {
[3262]263      EventHandler handler = ExecutionTimeChanged;
264      if (handler != null) handler(this, EventArgs.Empty);
[2851]265    }
[3262]266    public event EventHandler ProblemChanged;
267    protected virtual void OnProblemChanged() {
268      EventHandler handler = ProblemChanged;
269      if (handler != null) handler(this, EventArgs.Empty);
[3226]270    }
[4102]271    public event EventHandler StoreAlgorithmInEachRunChanged;
272    protected virtual void OnStoreAlgorithmInEachRunChanged() {
273      EventHandler handler = StoreAlgorithmInEachRunChanged;
274      if (handler != null) handler(this, EventArgs.Empty);
275    }
[2851]276    public event EventHandler Prepared;
277    protected virtual void OnPrepared() {
[3275]278      ExecutionTime = TimeSpan.Zero;
[8212]279      foreach (IStatefulItem statefulObject in this.GetObjectGraphObjects(new HashSet<object>() { Runs }).OfType<IStatefulItem>()) {
[6103]280        statefulObject.InitializeState();
281      }
[8155]282      ExecutionState = ExecutionState.Prepared;
[3262]283      EventHandler handler = Prepared;
284      if (handler != null) handler(this, EventArgs.Empty);
[2851]285    }
286    public event EventHandler Started;
287    protected virtual void OnStarted() {
[3262]288      ExecutionState = ExecutionState.Started;
289      EventHandler handler = Started;
290      if (handler != null) handler(this, EventArgs.Empty);
[2851]291    }
[3262]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    }
[2851]298    public event EventHandler Stopped;
299    protected virtual void OnStopped() {
[14433]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);
[6103]318      }
[2851]319    }
320    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
321    protected virtual void OnExceptionOccurred(Exception exception) {
[3262]322      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
323      if (handler != null) handler(this, new EventArgs<Exception>(exception));
[2851]324    }
[2975]325
[2852]326    protected virtual void DeregisterProblemEvents() {
[2975]327      problem.OperatorsChanged -= new EventHandler(Problem_OperatorsChanged);
[3739]328      problem.Reset -= new EventHandler(Problem_Reset);
[2852]329    }
330    protected virtual void RegisterProblemEvents() {
[2975]331      problem.OperatorsChanged += new EventHandler(Problem_OperatorsChanged);
[3739]332      problem.Reset += new EventHandler(Problem_Reset);
[2852]333    }
[2975]334    protected virtual void Problem_OperatorsChanged(object sender, EventArgs e) { }
[3739]335    protected virtual void Problem_Reset(object sender, EventArgs e) {
336      Prepare();
337    }
[3716]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    }
[2851]348    #endregion
349  }
350}
Note: See TracBrowser for help on using the repository browser.