Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Optimization/3.3/Algorithm.cs @ 4475

Last change on this file since 4475 was 4437, checked in by swagner, 15 years ago

Implemented !IStorableContent separately for each algorithm (#1193)

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