Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3555 was 3372, checked in by swagner, 15 years ago

Implemented reviewers' comments (#893).

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