Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3932 was 3785, checked in by swagner, 15 years ago

Added algorithm and problem name and type to the parameters collection when collecting the parameter values of a run (#947)

File size: 12.1 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    protected int runsCounter;
95
96    [Storable]
97    private RunCollection runs;
98    public RunCollection Runs {
99      get { return runs; }
100      protected set {
101        if (value == null) throw new ArgumentNullException();
102        if (runs != value) {
103          if (runs != null) DeregisterRunsEvents();
104          runs = value;
105          if (runs != null) RegisterRunsEvents();
106        }
107      }
108    }
109
110    protected Algorithm()
111      : base() {
112      executionState = ExecutionState.Stopped;
113      executionTime = TimeSpan.Zero;
114      runsCounter = 0;
115      Runs = new RunCollection();
116    }
117    protected Algorithm(string name)
118      : base(name) {
119      executionState = ExecutionState.Stopped;
120      executionTime = TimeSpan.Zero;
121      runsCounter = 0;
122      Runs = new RunCollection();
123    }
124    protected Algorithm(string name, ParameterCollection parameters)
125      : base(name, parameters) {
126      executionState = ExecutionState.Stopped;
127      executionTime = TimeSpan.Zero;
128      runsCounter = 0;
129      Runs = new RunCollection();
130    }
131    protected Algorithm(string name, string description)
132      : base(name, description) {
133      executionState = ExecutionState.Stopped;
134      executionTime = TimeSpan.Zero;
135      runsCounter = 0;
136      Runs = new RunCollection();
137    }
138    protected Algorithm(string name, string description, ParameterCollection parameters)
139      : base(name, description, parameters) {
140      executionState = ExecutionState.Stopped;
141      executionTime = TimeSpan.Zero;
142      runsCounter = 0;
143      Runs = new RunCollection();
144    }
145    [StorableConstructor]
146    protected Algorithm(bool deserializing) : base(deserializing) { }
147
148    [StorableHook(HookType.AfterDeserialization)]
149    private void Initialize() {
150      if (problem != null) RegisterProblemEvents();
151      if (runs != null) RegisterRunsEvents();
152    }
153
154    public override IDeepCloneable Clone(Cloner cloner) {
155      if (ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
156      Algorithm clone = (Algorithm)base.Clone(cloner);
157      clone.executionState = executionState;
158      clone.executionTime = executionTime;
159      clone.problem = (IProblem)cloner.Clone(problem);
160      clone.runsCounter = runsCounter;
161      clone.runs = (RunCollection)cloner.Clone(runs);
162      clone.Initialize();
163      return clone;
164    }
165    protected virtual void Clone(IDeepCloneable clone, Cloner cloner) {
166      Algorithm algorithm = clone as Algorithm;
167      if (algorithm != null) {
168        algorithm.name = name;
169        algorithm.description = description;
170        foreach (IParameter param in Parameters)
171          algorithm.Parameters.Add((IParameter)cloner.Clone(param));
172        algorithm.executionState = executionState;
173        algorithm.executionTime = executionTime;
174        algorithm.problem = (IProblem)cloner.Clone(problem);
175        algorithm.runsCounter = runsCounter;
176        algorithm.runs = (RunCollection)cloner.Clone(runs);
177        algorithm.Initialize();
178      }
179    }
180
181    public virtual void Prepare() {
182      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
183        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
184    }
185    public void Prepare(bool clearRuns) {
186      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
187        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
188      if (clearRuns) runs.Clear();
189      Prepare();
190    }
191    public virtual void Start() {
192      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
193        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
194    }
195    public virtual void Pause() {
196      if (ExecutionState != ExecutionState.Started)
197        throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
198    }
199    public virtual void Stop() {
200      if ((ExecutionState != ExecutionState.Started) && (ExecutionState != ExecutionState.Paused))
201        throw new InvalidOperationException(string.Format("Stop not allowed in execution state \"{0}\".", ExecutionState));
202    }
203
204    public override void CollectParameterValues(IDictionary<string, IItem> values) {
205      base.CollectParameterValues(values);
206      values.Add("Algorithm Name", new StringValue(Name));
207      values.Add("Algorithm Type", new StringValue(this.GetType().GetPrettyName()));
208      if (Problem != null) {
209        Problem.CollectParameterValues(values);
210        values.Add("Problem Name", new StringValue(Problem.Name));
211        values.Add("Problem Type", new StringValue(Problem.GetType().GetPrettyName()));
212      }
213    }
214    public virtual void CollectResultValues(IDictionary<string, IItem> values) {
215      values.Add("Execution Time", new TimeSpanValue(ExecutionTime));
216      foreach (IResult result in Results)
217        values.Add(result.Name, result.Value);
218    }
219
220    #region Events
221    public event EventHandler ExecutionStateChanged;
222    protected virtual void OnExecutionStateChanged() {
223      EventHandler handler = ExecutionStateChanged;
224      if (handler != null) handler(this, EventArgs.Empty);
225    }
226    public event EventHandler ExecutionTimeChanged;
227    protected virtual void OnExecutionTimeChanged() {
228      EventHandler handler = ExecutionTimeChanged;
229      if (handler != null) handler(this, EventArgs.Empty);
230    }
231    public event EventHandler ProblemChanged;
232    protected virtual void OnProblemChanged() {
233      EventHandler handler = ProblemChanged;
234      if (handler != null) handler(this, EventArgs.Empty);
235    }
236    public event EventHandler Prepared;
237    protected virtual void OnPrepared() {
238      ExecutionTime = TimeSpan.Zero;
239      ExecutionState = ExecutionState.Prepared;
240      EventHandler handler = Prepared;
241      if (handler != null) handler(this, EventArgs.Empty);
242    }
243    public event EventHandler Started;
244    protected virtual void OnStarted() {
245      ExecutionState = ExecutionState.Started;
246      EventHandler handler = Started;
247      if (handler != null) handler(this, EventArgs.Empty);
248    }
249    public event EventHandler Paused;
250    protected virtual void OnPaused() {
251      ExecutionState = ExecutionState.Paused;
252      EventHandler handler = Paused;
253      if (handler != null) handler(this, EventArgs.Empty);
254    }
255    public event EventHandler Stopped;
256    protected virtual void OnStopped() {
257      ExecutionState = ExecutionState.Stopped;
258      runsCounter++;
259      runs.Add(new Run(string.Format("{0} Run {1}", Name, runsCounter), this));
260      EventHandler handler = Stopped;
261      if (handler != null) handler(this, EventArgs.Empty);
262    }
263    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
264    protected virtual void OnExceptionOccurred(Exception exception) {
265      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
266      if (handler != null) handler(this, new EventArgs<Exception>(exception));
267    }
268
269    protected virtual void DeregisterProblemEvents() {
270      problem.SolutionCreatorChanged -= new EventHandler(Problem_SolutionCreatorChanged);
271      problem.EvaluatorChanged -= new EventHandler(Problem_EvaluatorChanged);
272      problem.OperatorsChanged -= new EventHandler(Problem_OperatorsChanged);
273      problem.Reset -= new EventHandler(Problem_Reset);
274    }
275    protected virtual void RegisterProblemEvents() {
276      problem.SolutionCreatorChanged += new EventHandler(Problem_SolutionCreatorChanged);
277      problem.EvaluatorChanged += new EventHandler(Problem_EvaluatorChanged);
278      problem.OperatorsChanged += new EventHandler(Problem_OperatorsChanged);
279      problem.Reset += new EventHandler(Problem_Reset);
280    }
281    protected virtual void Problem_SolutionCreatorChanged(object sender, EventArgs e) { }
282    protected virtual void Problem_EvaluatorChanged(object sender, EventArgs e) { }
283    protected virtual void Problem_OperatorsChanged(object sender, EventArgs e) { }
284    protected virtual void Problem_Reset(object sender, EventArgs e) {
285      Prepare();
286    }
287
288    protected virtual void DeregisterRunsEvents() {
289      runs.CollectionReset -= new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
290    }
291    protected virtual void RegisterRunsEvents() {
292      runs.CollectionReset += new CollectionItemsChangedEventHandler<IRun>(Runs_CollectionReset);
293    }
294    protected virtual void Runs_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
295      runsCounter = runs.Count;
296    }
297    #endregion
298  }
299}
Note: See TracBrowser for help on using the repository browser.