Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3694 was 3694, checked in by swagner, 14 years ago

Implemented reviewers' comments (#893)

File size: 10.8 KB
Line 
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;
23using System.Collections.Generic;
24using System.Drawing;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
29
30namespace HeuristicLab.Optimization {
31  /// <summary>
32  /// A base class for algorithms.
33  /// </summary>
34  [Item("Algorithm", "A base class for algorithms.")]
35  [StorableClass]
36  public abstract class Algorithm : ParameterizedNamedItem, IAlgorithm {
37    public override Image ItemImage {
38      get {
39        if (ExecutionState == ExecutionState.Prepared) return HeuristicLab.Common.Resources.VS2008ImageLibrary.ExecutablePrepared;
40        else if (ExecutionState == ExecutionState.Started) return HeuristicLab.Common.Resources.VS2008ImageLibrary.ExecutableStarted;
41        else if (ExecutionState == ExecutionState.Paused) return HeuristicLab.Common.Resources.VS2008ImageLibrary.ExecutablePaused;
42        else if (ExecutionState == ExecutionState.Stopped) return HeuristicLab.Common.Resources.VS2008ImageLibrary.ExecutableStopped;
43        else return HeuristicLab.Common.Resources.VS2008ImageLibrary.Event;
44      }
45    }
46
47    [Storable]
48    private ExecutionState executionState;
49    public ExecutionState ExecutionState {
50      get { return executionState; }
51      private set {
52        if (executionState != value) {
53          executionState = value;
54          OnExecutionStateChanged();
55          OnItemImageChanged();
56        }
57      }
58    }
59
60    [Storable]
61    private TimeSpan executionTime;
62    public TimeSpan ExecutionTime {
63      get { return executionTime; }
64      protected set {
65        executionTime = value;
66        OnExecutionTimeChanged();
67      }
68    }
69
70    public virtual Type ProblemType {
71      get { return typeof(IProblem); }
72    }
73
74    [Storable]
75    private IProblem problem;
76    public IProblem Problem {
77      get { return problem; }
78      set {
79        if (problem != value) {
80          if ((value != null) && !ProblemType.IsInstanceOfType(value)) throw new ArgumentException("Invalid problem type.");
81          if (problem != null) DeregisterProblemEvents();
82          problem = value;
83          if (problem != null) RegisterProblemEvents();
84          OnProblemChanged();
85          Prepare();
86        }
87      }
88    }
89
90    public abstract ResultCollection Results { get; }
91
92    [Storable]
93    protected int runsCounter;
94
95    [Storable]
96    private RunCollection runs;
97    public RunCollection Runs {
98      get { return runs; }
99    }
100
101    protected Algorithm()
102      : base() {
103      executionState = ExecutionState.Stopped;
104      executionTime = TimeSpan.Zero;
105      runsCounter = 0;
106      runs = new RunCollection();
107    }
108    protected Algorithm(string name)
109      : base(name) {
110      executionState = ExecutionState.Stopped;
111      executionTime = TimeSpan.Zero;
112      runsCounter = 0;
113      runs = new RunCollection();
114    }
115    protected Algorithm(string name, ParameterCollection parameters)
116      : base(name, parameters) {
117      executionState = ExecutionState.Stopped;
118      executionTime = TimeSpan.Zero;
119      runsCounter = 0;
120      runs = new RunCollection();
121    }
122    protected Algorithm(string name, string description)
123      : base(name, description) {
124      executionState = ExecutionState.Stopped;
125      executionTime = TimeSpan.Zero;
126      runsCounter = 0;
127      runs = new RunCollection();
128    }
129    protected Algorithm(string name, string description, ParameterCollection parameters)
130      : base(name, description, parameters) {
131      executionState = ExecutionState.Stopped;
132      executionTime = TimeSpan.Zero;
133      runsCounter = 0;
134      runs = new RunCollection();
135    }
136    [StorableConstructor]
137    protected Algorithm(bool deserializing) : base(deserializing) { }
138
139    [StorableHook(HookType.AfterDeserialization)]
140    private void Initialize() {
141      if (problem != null) RegisterProblemEvents();
142    }
143
144    public override IDeepCloneable Clone(Cloner cloner) {
145      if (ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
146      Algorithm clone = (Algorithm)base.Clone(cloner);
147      clone.executionState = executionState;
148      clone.executionTime = executionTime;
149      clone.problem = (IProblem)cloner.Clone(problem);
150      clone.runsCounter = runsCounter;
151      clone.runs = (RunCollection)cloner.Clone(runs);
152      clone.Initialize();
153      return clone;
154    }
155    protected virtual void Clone(IDeepCloneable clone, Cloner cloner) {
156      Algorithm algorithm = clone as Algorithm;
157      if (algorithm != null) {
158        algorithm.name = name;
159        algorithm.description = description;
160        foreach (IParameter param in Parameters)
161          algorithm.Parameters.Add((IParameter)cloner.Clone(param));
162        algorithm.executionState = executionState;
163        algorithm.executionTime = executionTime;
164        algorithm.problem = (IProblem)cloner.Clone(problem);
165        algorithm.runsCounter = runsCounter;
166        algorithm.runs = (RunCollection)cloner.Clone(runs);
167        algorithm.Initialize();
168      }
169    }
170
171    public virtual void Prepare() {
172      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
173        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
174    }
175    public void Prepare(bool clearRuns) {
176      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
177        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
178      if (clearRuns) {
179        runsCounter = 0;
180        runs.Clear();
181      }
182      Prepare();
183    }
184    public virtual void Start() {
185      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
186        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
187    }
188    public virtual void Pause() {
189      if (ExecutionState != ExecutionState.Started)
190        throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
191    }
192    public virtual void Stop() {
193      if ((ExecutionState != ExecutionState.Started) && (ExecutionState != ExecutionState.Paused))
194        throw new InvalidOperationException(string.Format("Stop not allowed in execution state \"{0}\".", ExecutionState));
195    }
196
197    public override void CollectParameterValues(IDictionary<string, IItem> values) {
198      base.CollectParameterValues(values);
199      if (Problem != null) Problem.CollectParameterValues(values);
200    }
201    public virtual void CollectResultValues(IDictionary<string, IItem> values) {
202      values.Add("Execution Time", new TimeSpanValue(ExecutionTime));
203      foreach (IResult result in Results)
204        values.Add(result.Name, result.Value);
205    }
206
207    #region Events
208    public event EventHandler ExecutionStateChanged;
209    protected virtual void OnExecutionStateChanged() {
210      EventHandler handler = ExecutionStateChanged;
211      if (handler != null) handler(this, EventArgs.Empty);
212    }
213    public event EventHandler ExecutionTimeChanged;
214    protected virtual void OnExecutionTimeChanged() {
215      EventHandler handler = ExecutionTimeChanged;
216      if (handler != null) handler(this, EventArgs.Empty);
217    }
218    public event EventHandler ProblemChanged;
219    protected virtual void OnProblemChanged() {
220      EventHandler handler = ProblemChanged;
221      if (handler != null) handler(this, EventArgs.Empty);
222    }
223    public event EventHandler Prepared;
224    protected virtual void OnPrepared() {
225      ExecutionTime = TimeSpan.Zero;
226      ExecutionState = ExecutionState.Prepared;
227      EventHandler handler = Prepared;
228      if (handler != null) handler(this, EventArgs.Empty);
229    }
230    public event EventHandler Started;
231    protected virtual void OnStarted() {
232      ExecutionState = ExecutionState.Started;
233      EventHandler handler = Started;
234      if (handler != null) handler(this, EventArgs.Empty);
235    }
236    public event EventHandler Paused;
237    protected virtual void OnPaused() {
238      ExecutionState = ExecutionState.Paused;
239      EventHandler handler = Paused;
240      if (handler != null) handler(this, EventArgs.Empty);
241    }
242    public event EventHandler Stopped;
243    protected virtual void OnStopped() {
244      ExecutionState = ExecutionState.Stopped;
245      runsCounter++;
246      runs.Add(new Run(string.Format("{0} Run {1}", Name, runsCounter), this));
247      EventHandler handler = Stopped;
248      if (handler != null) handler(this, EventArgs.Empty);
249    }
250    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
251    protected virtual void OnExceptionOccurred(Exception exception) {
252      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
253      if (handler != null) handler(this, new EventArgs<Exception>(exception));
254    }
255
256    protected virtual void DeregisterProblemEvents() {
257      problem.SolutionCreatorChanged -= new EventHandler(Problem_SolutionCreatorChanged);
258      problem.EvaluatorChanged -= new EventHandler(Problem_EvaluatorChanged);
259      problem.OperatorsChanged -= new EventHandler(Problem_OperatorsChanged);
260    }
261    protected virtual void RegisterProblemEvents() {
262      problem.SolutionCreatorChanged += new EventHandler(Problem_SolutionCreatorChanged);
263      problem.EvaluatorChanged += new EventHandler(Problem_EvaluatorChanged);
264      problem.OperatorsChanged += new EventHandler(Problem_OperatorsChanged);
265    }
266
267    protected virtual void Problem_SolutionCreatorChanged(object sender, EventArgs e) { }
268    protected virtual void Problem_EvaluatorChanged(object sender, EventArgs e) { }
269    protected virtual void Problem_OperatorsChanged(object sender, EventArgs e) { }
270    #endregion
271  }
272}
Note: See TracBrowser for help on using the repository browser.