Free cookie consent management tool by TermsFeed Policy Generator

source: branches/WebJobManager/HeuristicLab.Optimization/3.3/Algorithms/Algorithm.cs @ 17243

Last change on this file since 17243 was 13656, checked in by ascheibe, 9 years ago

#2582 created branch for Hive Web Job Manager

File size: 13.0 KB
RevLine 
[2851]1#region License Information
2/* HeuristicLab
[12012]3 * Copyright (C) 2002-2015 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;
[3716]26using HeuristicLab.Collections;
[2851]27using HeuristicLab.Common;
28using HeuristicLab.Core;
[3694]29using HeuristicLab.Data;
[2851]30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
32namespace HeuristicLab.Optimization {
33  /// <summary>
34  /// A base class for algorithms.
35  /// </summary>
36  [Item("Algorithm", "A base class for algorithms.")]
[3017]37  [StorableClass]
[4437]38  public abstract class Algorithm : ParameterizedNamedItem, IAlgorithm {
[13656]39    public static new Image StaticItemImage
40    {
41      get { return new Bitmap(25, 25); }
[7201]42    }
[13656]43    public override Image ItemImage
44    {
45      get
46      {
[5287]47        if (ExecutionState == ExecutionState.Prepared) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutablePrepared;
48        else if (ExecutionState == ExecutionState.Started) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutableStarted;
49        else if (ExecutionState == ExecutionState.Paused) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutablePaused;
50        else if (ExecutionState == ExecutionState.Stopped) return HeuristicLab.Common.Resources.VSImageLibrary.ExecutableStopped;
[7201]51        else return base.ItemImage;
[3351]52      }
[2851]53    }
54
[3262]55    [Storable]
56    private ExecutionState executionState;
[13656]57    public ExecutionState ExecutionState
58    {
[3262]59      get { return executionState; }
[13656]60      private set
61      {
[3262]62        if (executionState != value) {
63          executionState = value;
64          OnExecutionStateChanged();
[3351]65          OnItemImageChanged();
[3262]66        }
67      }
68    }
69
70    [Storable]
71    private TimeSpan executionTime;
[13656]72    public TimeSpan ExecutionTime
73    {
[3262]74      get { return executionTime; }
[13656]75      protected set
76      {
[3262]77        executionTime = value;
78        OnExecutionTimeChanged();
79      }
80    }
81
[13656]82    public virtual Type ProblemType
83    {
[2852]84      get { return typeof(IProblem); }
85    }
86
[3280]87    [Storable]
[2851]88    private IProblem problem;
[13656]89    public IProblem Problem
90    {
[2851]91      get { return problem; }
[13656]92      set
93      {
[2851]94        if (problem != value) {
[2852]95          if ((value != null) && !ProblemType.IsInstanceOfType(value)) throw new ArgumentException("Invalid problem type.");
96          if (problem != null) DeregisterProblemEvents();
[2851]97          problem = value;
[2852]98          if (problem != null) RegisterProblemEvents();
[2851]99          OnProblemChanged();
[2864]100          Prepare();
[2851]101        }
102      }
103    }
104
[3226]105    public abstract ResultCollection Results { get; }
[2882]106
[3275]107    [Storable]
[4102]108    private bool storeAlgorithmInEachRun;
[13656]109    public bool StoreAlgorithmInEachRun
110    {
[4102]111      get { return storeAlgorithmInEachRun; }
[13656]112      set
113      {
[4102]114        if (storeAlgorithmInEachRun != value) {
115          storeAlgorithmInEachRun = value;
116          OnStoreAlgorithmInEachRunChanged();
117        }
118      }
119    }
120
121    [Storable]
[3280]122    protected int runsCounter;
123
124    [Storable]
[3275]125    private RunCollection runs;
[13656]126    public RunCollection Runs
127    {
[3275]128      get { return runs; }
[13656]129      protected set
130      {
[3716]131        if (value == null) throw new ArgumentNullException();
132        if (runs != value) {
133          if (runs != null) DeregisterRunsEvents();
134          runs = value;
135          if (runs != null) RegisterRunsEvents();
136        }
137      }
[3275]138    }
139
[13656]140    public virtual IEnumerable<IOptimizer> NestedOptimizers
141    {
[5419]142      get { return Enumerable.Empty<IOptimizer>(); }
143    }
144
[3262]145    protected Algorithm()
146      : base() {
147      executionState = ExecutionState.Stopped;
148      executionTime = TimeSpan.Zero;
[5203]149      storeAlgorithmInEachRun = false;
[3280]150      runsCounter = 0;
[8962]151      Runs = new RunCollection { OptimizerName = Name };
[2851]152    }
[3262]153    protected Algorithm(string name)
154      : base(name) {
155      executionState = ExecutionState.Stopped;
156      executionTime = TimeSpan.Zero;
[5203]157      storeAlgorithmInEachRun = false;
[3280]158      runsCounter = 0;
[8962]159      Runs = new RunCollection { OptimizerName = Name };
[2851]160    }
[3262]161    protected Algorithm(string name, ParameterCollection parameters)
162      : base(name, parameters) {
163      executionState = ExecutionState.Stopped;
164      executionTime = TimeSpan.Zero;
[5203]165      storeAlgorithmInEachRun = false;
[3280]166      runsCounter = 0;
[8962]167      Runs = new RunCollection { OptimizerName = Name };
[3262]168    }
169    protected Algorithm(string name, string description)
170      : base(name, description) {
171      executionState = ExecutionState.Stopped;
172      executionTime = TimeSpan.Zero;
[5203]173      storeAlgorithmInEachRun = false;
[3280]174      runsCounter = 0;
[8962]175      Runs = new RunCollection { OptimizerName = Name };
[3262]176    }
177    protected Algorithm(string name, string description, ParameterCollection parameters)
178      : base(name, description, parameters) {
179      executionState = ExecutionState.Stopped;
180      executionTime = TimeSpan.Zero;
[5203]181      storeAlgorithmInEachRun = false;
[3280]182      runsCounter = 0;
[8962]183      Runs = new RunCollection { OptimizerName = Name };
[3262]184    }
[3280]185    [StorableConstructor]
[5203]186    protected Algorithm(bool deserializing) : base(deserializing) { }
[3280]187    [StorableHook(HookType.AfterDeserialization)]
[4722]188    private void AfterDeserialization() {
189      Initialize();
[3280]190    }
191
[4722]192    protected Algorithm(Algorithm original, Cloner cloner)
193      : base(original, cloner) {
[3280]194      if (ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
[4722]195      executionState = original.executionState;
196      executionTime = original.executionTime;
197      problem = cloner.Clone(original.problem);
198      storeAlgorithmInEachRun = original.storeAlgorithmInEachRun;
199      runsCounter = original.runsCounter;
200      runs = cloner.Clone(original.runs);
201      Initialize();
[2851]202    }
[4722]203
204    private void Initialize() {
205      if (problem != null) RegisterProblemEvents();
206      if (runs != null) RegisterRunsEvents();
[3286]207    }
[2851]208
[3275]209    public virtual void Prepare() {
210      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
211        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
[3274]212    }
[3275]213    public void Prepare(bool clearRuns) {
[3262]214      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
215        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
[3716]216      if (clearRuns) runs.Clear();
[3275]217      Prepare();
[2851]218    }
[3262]219    public virtual void Start() {
220      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
221        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
[2851]222    }
[3262]223    public virtual void Pause() {
224      if (ExecutionState != ExecutionState.Started)
225        throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
[2851]226    }
[3262]227    public virtual void Stop() {
228      if ((ExecutionState != ExecutionState.Started) && (ExecutionState != ExecutionState.Paused))
229        throw new InvalidOperationException(string.Format("Stop not allowed in execution state \"{0}\".", ExecutionState));
230    }
[2851]231
[3260]232    public override void CollectParameterValues(IDictionary<string, IItem> values) {
233      base.CollectParameterValues(values);
[3785]234      values.Add("Algorithm Name", new StringValue(Name));
235      values.Add("Algorithm Type", new StringValue(this.GetType().GetPrettyName()));
236      if (Problem != null) {
237        Problem.CollectParameterValues(values);
238        values.Add("Problem Name", new StringValue(Problem.Name));
239        values.Add("Problem Type", new StringValue(Problem.GetType().GetPrettyName()));
240      }
[3260]241    }
242    public virtual void CollectResultValues(IDictionary<string, IItem> values) {
[3694]243      values.Add("Execution Time", new TimeSpanValue(ExecutionTime));
[11762]244      Results.CollectResultValues(values);
[3260]245    }
246
[7706]247    protected override IEnumerable<KeyValuePair<string, IItem>> GetCollectedValues(IValueParameter param) {
248      var children = base.GetCollectedValues(param);
[7579]249      foreach (var child in children) {
250        if (child.Value is IOperator)
251          yield return new KeyValuePair<string, IItem>(child.Key, new StringValue(((IOperator)child.Value).Name));
252        else yield return child;
253      }
254    }
255
[2851]256    #region Events
[8738]257    protected override void OnNameChanged() {
258      base.OnNameChanged();
[8962]259      Runs.OptimizerName = Name;
[8738]260    }
261
[3262]262    public event EventHandler ExecutionStateChanged;
263    protected virtual void OnExecutionStateChanged() {
264      EventHandler handler = ExecutionStateChanged;
265      if (handler != null) handler(this, EventArgs.Empty);
[2851]266    }
267    public event EventHandler ExecutionTimeChanged;
268    protected virtual void OnExecutionTimeChanged() {
[3262]269      EventHandler handler = ExecutionTimeChanged;
270      if (handler != null) handler(this, EventArgs.Empty);
[2851]271    }
[3262]272    public event EventHandler ProblemChanged;
273    protected virtual void OnProblemChanged() {
274      EventHandler handler = ProblemChanged;
275      if (handler != null) handler(this, EventArgs.Empty);
[3226]276    }
[4102]277    public event EventHandler StoreAlgorithmInEachRunChanged;
278    protected virtual void OnStoreAlgorithmInEachRunChanged() {
279      EventHandler handler = StoreAlgorithmInEachRunChanged;
280      if (handler != null) handler(this, EventArgs.Empty);
281    }
[2851]282    public event EventHandler Prepared;
283    protected virtual void OnPrepared() {
[3275]284      ExecutionTime = TimeSpan.Zero;
[8212]285      foreach (IStatefulItem statefulObject in this.GetObjectGraphObjects(new HashSet<object>() { Runs }).OfType<IStatefulItem>()) {
[6103]286        statefulObject.InitializeState();
287      }
[8155]288      ExecutionState = ExecutionState.Prepared;
[3262]289      EventHandler handler = Prepared;
290      if (handler != null) handler(this, EventArgs.Empty);
[2851]291    }
292    public event EventHandler Started;
293    protected virtual void OnStarted() {
[3262]294      ExecutionState = ExecutionState.Started;
295      EventHandler handler = Started;
296      if (handler != null) handler(this, EventArgs.Empty);
[2851]297    }
[3262]298    public event EventHandler Paused;
299    protected virtual void OnPaused() {
300      ExecutionState = ExecutionState.Paused;
301      EventHandler handler = Paused;
302      if (handler != null) handler(this, EventArgs.Empty);
303    }
[2851]304    public event EventHandler Stopped;
305    protected virtual void OnStopped() {
[8212]306      foreach (IStatefulItem statefulObject in this.GetObjectGraphObjects(new HashSet<object>() { Runs }).OfType<IStatefulItem>()) {
[6103]307        statefulObject.ClearState();
308      }
[3280]309      runsCounter++;
[3694]310      runs.Add(new Run(string.Format("{0} Run {1}", Name, runsCounter), this));
[8155]311      ExecutionState = ExecutionState.Stopped;
[3262]312      EventHandler handler = Stopped;
313      if (handler != null) handler(this, EventArgs.Empty);
[2851]314    }
315    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
316    protected virtual void OnExceptionOccurred(Exception exception) {
[3262]317      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
318      if (handler != null) handler(this, new EventArgs<Exception>(exception));
[2851]319    }
[2975]320
[2852]321    protected virtual void DeregisterProblemEvents() {
[2975]322      problem.OperatorsChanged -= new EventHandler(Problem_OperatorsChanged);
[3739]323      problem.Reset -= new EventHandler(Problem_Reset);
[2852]324    }
325    protected virtual void RegisterProblemEvents() {
[2975]326      problem.OperatorsChanged += new EventHandler(Problem_OperatorsChanged);
[3739]327      problem.Reset += new EventHandler(Problem_Reset);
[2852]328    }
[2975]329    protected virtual void Problem_OperatorsChanged(object sender, EventArgs e) { }
[3739]330    protected virtual void Problem_Reset(object sender, EventArgs e) {
331      Prepare();
332    }
[3716]333
334    protected virtual void DeregisterRunsEvents() {
335      runs.CollectionReset -= new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
336    }
337    protected virtual void RegisterRunsEvents() {
338      runs.CollectionReset += new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
339    }
340    protected virtual void Runs_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
341      runsCounter = runs.Count;
342    }
[2851]343    #endregion
344  }
345}
Note: See TracBrowser for help on using the repository browser.