Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ParameterBinding/HeuristicLab.Optimization/3.3/Algorithm.cs @ 12974

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

Merged cloning refactoring branch back into trunk (#922)

File size: 12.3 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.Collections;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
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.")]
36  [StorableClass]
37  public abstract class Algorithm : ParameterizedNamedItem, IAlgorithm {
38    public override Image ItemImage {
39      get {
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;
44        else return HeuristicLab.Common.Resources.VS2008ImageLibrary.Event;
45      }
46    }
47
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();
56          OnItemImageChanged();
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
71    public virtual Type ProblemType {
72      get { return typeof(IProblem); }
73    }
74
75    [Storable]
76    private IProblem problem;
77    public IProblem Problem {
78      get { return problem; }
79      set {
80        if (problem != value) {
81          if ((value != null) && !ProblemType.IsInstanceOfType(value)) throw new ArgumentException("Invalid problem type.");
82          if (problem != null) DeregisterProblemEvents();
83          problem = value;
84          if (problem != null) RegisterProblemEvents();
85          OnProblemChanged();
86          Prepare();
87        }
88      }
89    }
90
91    public abstract ResultCollection Results { get; }
92
93    [Storable]
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]
106    protected int runsCounter;
107
108    [Storable]
109    private RunCollection runs;
110    public RunCollection Runs {
111      get { return runs; }
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      }
120    }
121
122    protected Algorithm()
123      : base() {
124      executionState = ExecutionState.Stopped;
125      executionTime = TimeSpan.Zero;
126      storeAlgorithmInEachRun = true;
127      runsCounter = 0;
128      Runs = new RunCollection();
129    }
130    protected Algorithm(string name)
131      : base(name) {
132      executionState = ExecutionState.Stopped;
133      executionTime = TimeSpan.Zero;
134      storeAlgorithmInEachRun = true;
135      runsCounter = 0;
136      Runs = new RunCollection();
137    }
138    protected Algorithm(string name, ParameterCollection parameters)
139      : base(name, parameters) {
140      executionState = ExecutionState.Stopped;
141      executionTime = TimeSpan.Zero;
142      storeAlgorithmInEachRun = true;
143      runsCounter = 0;
144      Runs = new RunCollection();
145    }
146    protected Algorithm(string name, string description)
147      : base(name, description) {
148      executionState = ExecutionState.Stopped;
149      executionTime = TimeSpan.Zero;
150      storeAlgorithmInEachRun = true;
151      runsCounter = 0;
152      Runs = new RunCollection();
153    }
154    protected Algorithm(string name, string description, ParameterCollection parameters)
155      : base(name, description, parameters) {
156      executionState = ExecutionState.Stopped;
157      executionTime = TimeSpan.Zero;
158      storeAlgorithmInEachRun = true;
159      runsCounter = 0;
160      Runs = new RunCollection();
161    }
162    [StorableConstructor]
163    protected Algorithm(bool deserializing)
164      : base(deserializing) {
165      storeAlgorithmInEachRun = true;
166    }
167    [StorableHook(HookType.AfterDeserialization)]
168    private void AfterDeserialization() {
169      Initialize();
170    }
171
172    protected Algorithm(Algorithm original, Cloner cloner)
173      : base(original, cloner) {
174      if (ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
175      executionState = original.executionState;
176      executionTime = original.executionTime;
177      problem = cloner.Clone(original.problem);
178      storeAlgorithmInEachRun = original.storeAlgorithmInEachRun;
179      runsCounter = original.runsCounter;
180      runs = cloner.Clone(original.runs);
181      Initialize();
182    }
183
184    private void Initialize() {
185      if (problem != null) RegisterProblemEvents();
186      if (runs != null) RegisterRunsEvents();
187    }
188
189    public virtual void Prepare() {
190      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
191        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
192    }
193    public void Prepare(bool clearRuns) {
194      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
195        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
196      if (clearRuns) runs.Clear();
197      Prepare();
198    }
199    public virtual void Start() {
200      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
201        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
202    }
203    public virtual void Pause() {
204      if (ExecutionState != ExecutionState.Started)
205        throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
206    }
207    public virtual void Stop() {
208      if ((ExecutionState != ExecutionState.Started) && (ExecutionState != ExecutionState.Paused))
209        throw new InvalidOperationException(string.Format("Stop not allowed in execution state \"{0}\".", ExecutionState));
210    }
211
212    public override void CollectParameterValues(IDictionary<string, IItem> values) {
213      base.CollectParameterValues(values);
214      values.Add("Algorithm Name", new StringValue(Name));
215      values.Add("Algorithm Type", new StringValue(this.GetType().GetPrettyName()));
216      if (Problem != null) {
217        Problem.CollectParameterValues(values);
218        values.Add("Problem Name", new StringValue(Problem.Name));
219        values.Add("Problem Type", new StringValue(Problem.GetType().GetPrettyName()));
220      }
221    }
222    public virtual void CollectResultValues(IDictionary<string, IItem> values) {
223      values.Add("Execution Time", new TimeSpanValue(ExecutionTime));
224      foreach (IResult result in Results)
225        values.Add(result.Name, result.Value);
226    }
227
228    #region Events
229    public event EventHandler ExecutionStateChanged;
230    protected virtual void OnExecutionStateChanged() {
231      EventHandler handler = ExecutionStateChanged;
232      if (handler != null) handler(this, EventArgs.Empty);
233    }
234    public event EventHandler ExecutionTimeChanged;
235    protected virtual void OnExecutionTimeChanged() {
236      EventHandler handler = ExecutionTimeChanged;
237      if (handler != null) handler(this, EventArgs.Empty);
238    }
239    public event EventHandler ProblemChanged;
240    protected virtual void OnProblemChanged() {
241      EventHandler handler = ProblemChanged;
242      if (handler != null) handler(this, EventArgs.Empty);
243    }
244    public event EventHandler StoreAlgorithmInEachRunChanged;
245    protected virtual void OnStoreAlgorithmInEachRunChanged() {
246      EventHandler handler = StoreAlgorithmInEachRunChanged;
247      if (handler != null) handler(this, EventArgs.Empty);
248    }
249    public event EventHandler Prepared;
250    protected virtual void OnPrepared() {
251      ExecutionTime = TimeSpan.Zero;
252      ExecutionState = ExecutionState.Prepared;
253      EventHandler handler = Prepared;
254      if (handler != null) handler(this, EventArgs.Empty);
255    }
256    public event EventHandler Started;
257    protected virtual void OnStarted() {
258      ExecutionState = ExecutionState.Started;
259      EventHandler handler = Started;
260      if (handler != null) handler(this, EventArgs.Empty);
261    }
262    public event EventHandler Paused;
263    protected virtual void OnPaused() {
264      ExecutionState = ExecutionState.Paused;
265      EventHandler handler = Paused;
266      if (handler != null) handler(this, EventArgs.Empty);
267    }
268    public event EventHandler Stopped;
269    protected virtual void OnStopped() {
270      ExecutionState = ExecutionState.Stopped;
271      runsCounter++;
272      runs.Add(new Run(string.Format("{0} Run {1}", Name, runsCounter), this));
273      EventHandler handler = Stopped;
274      if (handler != null) handler(this, EventArgs.Empty);
275    }
276    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
277    protected virtual void OnExceptionOccurred(Exception exception) {
278      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
279      if (handler != null) handler(this, new EventArgs<Exception>(exception));
280    }
281
282    protected virtual void DeregisterProblemEvents() {
283      problem.SolutionCreatorChanged -= new EventHandler(Problem_SolutionCreatorChanged);
284      problem.EvaluatorChanged -= new EventHandler(Problem_EvaluatorChanged);
285      problem.OperatorsChanged -= new EventHandler(Problem_OperatorsChanged);
286      problem.Reset -= new EventHandler(Problem_Reset);
287    }
288    protected virtual void RegisterProblemEvents() {
289      problem.SolutionCreatorChanged += new EventHandler(Problem_SolutionCreatorChanged);
290      problem.EvaluatorChanged += new EventHandler(Problem_EvaluatorChanged);
291      problem.OperatorsChanged += new EventHandler(Problem_OperatorsChanged);
292      problem.Reset += new EventHandler(Problem_Reset);
293    }
294    protected virtual void Problem_SolutionCreatorChanged(object sender, EventArgs e) { }
295    protected virtual void Problem_EvaluatorChanged(object sender, EventArgs e) { }
296    protected virtual void Problem_OperatorsChanged(object sender, EventArgs e) { }
297    protected virtual void Problem_Reset(object sender, EventArgs e) {
298      Prepare();
299    }
300
301    protected virtual void DeregisterRunsEvents() {
302      runs.CollectionReset -= new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
303    }
304    protected virtual void RegisterRunsEvents() {
305      runs.CollectionReset += new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
306    }
307    protected virtual void Runs_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
308      runsCounter = runs.Count;
309    }
310    #endregion
311  }
312}
Note: See TracBrowser for help on using the repository browser.