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

Last change on this file since 3283 was 3283, checked in by swagner, 11 years ago

Continued work on algorithm batch processing (#947).

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