Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3286 was 3286, checked in by swagner, 13 years ago

Continued work on algorithm batch processing (#947).

File size: 10.4 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    [StorableConstructor]
129    protected Algorithm(bool deserializing) : base(deserializing) { }
130
131    [StorableHook(HookType.AfterDeserialization)]
132    private void Initialize() {
133      if (problem != null) RegisterProblemEvents();
134    }
135
136    public override IDeepCloneable Clone(Cloner cloner) {
137      if (ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
138      Algorithm clone = (Algorithm)base.Clone(cloner);
139      clone.executionState = executionState;
140      clone.executionTime = executionTime;
141      clone.problem = (IProblem)cloner.Clone(problem);
142      clone.runsCounter = runsCounter;
143      clone.runs = (RunCollection)cloner.Clone(runs);
144      clone.Initialize();
145      return clone;
146    }
147    protected virtual void Clone(IDeepCloneable clone, Cloner cloner) {
148      Algorithm algorithm = clone as Algorithm;
149      if (algorithm != null) {
150        algorithm.name = name;
151        algorithm.description = description;
152        foreach (IParameter param in Parameters)
153          algorithm.Parameters.Add((IParameter)cloner.Clone(param));
154        algorithm.executionState = executionState;
155        algorithm.executionTime = executionTime;
156        algorithm.problem = (IProblem)cloner.Clone(problem);
157        algorithm.runsCounter = runsCounter;
158        algorithm.runs = (RunCollection)cloner.Clone(runs);
159        algorithm.Initialize();
160      }
161    }
162
163    public virtual void Prepare() {
164      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
165        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
166    }
167    public void Prepare(bool clearRuns) {
168      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
169        throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
170      if (clearRuns) {
171        runsCounter = 0;
172        runs.Clear();
173      }
174      Prepare();
175    }
176    public virtual void Start() {
177      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
178        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
179    }
180    public virtual void Pause() {
181      if (ExecutionState != ExecutionState.Started)
182        throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
183    }
184    public virtual void Stop() {
185      if ((ExecutionState != ExecutionState.Started) && (ExecutionState != ExecutionState.Paused))
186        throw new InvalidOperationException(string.Format("Stop not allowed in execution state \"{0}\".", ExecutionState));
187    }
188
189    public override void CollectParameterValues(IDictionary<string, IItem> values) {
190      base.CollectParameterValues(values);
191      if (Problem != null) Problem.CollectParameterValues(values);
192    }
193    public virtual void CollectResultValues(IDictionary<string, IItem> values) {
194      foreach (IResult result in Results)
195        values.Add(result.Name, result.Value);
196    }
197
198    #region Events
199    public event EventHandler ExecutionStateChanged;
200    protected virtual void OnExecutionStateChanged() {
201      EventHandler handler = ExecutionStateChanged;
202      if (handler != null) handler(this, EventArgs.Empty);
203    }
204    public event EventHandler ExecutionTimeChanged;
205    protected virtual void OnExecutionTimeChanged() {
206      EventHandler handler = ExecutionTimeChanged;
207      if (handler != null) handler(this, EventArgs.Empty);
208    }
209    public event EventHandler ProblemChanged;
210    protected virtual void OnProblemChanged() {
211      EventHandler handler = ProblemChanged;
212      if (handler != null) handler(this, EventArgs.Empty);
213    }
214    public event EventHandler Prepared;
215    protected virtual void OnPrepared() {
216      ExecutionTime = TimeSpan.Zero;
217      ExecutionState = ExecutionState.Prepared;
218      EventHandler handler = Prepared;
219      if (handler != null) handler(this, EventArgs.Empty);
220    }
221    public event EventHandler Started;
222    protected virtual void OnStarted() {
223      ExecutionState = ExecutionState.Started;
224      EventHandler handler = Started;
225      if (handler != null) handler(this, EventArgs.Empty);
226    }
227    public event EventHandler Paused;
228    protected virtual void OnPaused() {
229      ExecutionState = ExecutionState.Paused;
230      EventHandler handler = Paused;
231      if (handler != null) handler(this, EventArgs.Empty);
232    }
233    public event EventHandler Stopped;
234    protected virtual void OnStopped() {
235      ExecutionState = ExecutionState.Stopped;
236      runsCounter++;
237      runs.Add(new Run(string.Format("{0} Run {1} ({2})", Name, runsCounter, ExecutionTime), this));
238      EventHandler handler = Stopped;
239      if (handler != null) handler(this, EventArgs.Empty);
240    }
241    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
242    protected virtual void OnExceptionOccurred(Exception exception) {
243      EventHandler<EventArgs<Exception>> handler = ExceptionOccurred;
244      if (handler != null) handler(this, new EventArgs<Exception>(exception));
245    }
246
247    protected virtual void DeregisterProblemEvents() {
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    protected virtual void RegisterProblemEvents() {
254      problem.SolutionCreatorChanged += new EventHandler(Problem_SolutionCreatorChanged);
255      problem.EvaluatorChanged += new EventHandler(Problem_EvaluatorChanged);
256      problem.VisualizerChanged += new EventHandler(Problem_VisualizerChanged);
257      problem.OperatorsChanged += new EventHandler(Problem_OperatorsChanged);
258    }
259
260    protected virtual void Problem_SolutionCreatorChanged(object sender, EventArgs e) { }
261    protected virtual void Problem_EvaluatorChanged(object sender, EventArgs e) { }
262    protected virtual void Problem_VisualizerChanged(object sender, EventArgs e) { }
263    protected virtual void Problem_OperatorsChanged(object sender, EventArgs e) { }
264    #endregion
265  }
266}
Note: See TracBrowser for help on using the repository browser.