1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 2002-2012 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 |
|
---|
22 | using System;
|
---|
23 | using System.Collections.Generic;
|
---|
24 | using System.ComponentModel;
|
---|
25 | using System.Drawing;
|
---|
26 | using System.Linq;
|
---|
27 | using HeuristicLab.Common;
|
---|
28 | using HeuristicLab.Common.Resources;
|
---|
29 | using HeuristicLab.Core;
|
---|
30 | using HeuristicLab.Data;
|
---|
31 | using HeuristicLab.Optimization;
|
---|
32 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
33 |
|
---|
34 | namespace HeuristicLab.Analysis {
|
---|
35 | public enum TerminationCriterium { OnlyByTime, OnlyByEvaluations, OnlyByTarget, ByTargetAndTime, ByTargetAndEvaluations, ByTimeAndEvaluations, WhicheverHitsFirst, WhicheverHitsLast }
|
---|
36 | /// <summary>
|
---|
37 | /// A run in which an algorithm is executed for a certain maximum time only.
|
---|
38 | /// </summary>
|
---|
39 | [Item("Independent Random Restarter", "An optimizer that repeats an algorithm until either a certain target value is reached or a maximum budget is exceeded.")]
|
---|
40 | [Creatable(CreatableAttribute.Categories.TestingAndAnalysis, Priority = 117)]
|
---|
41 | [StorableClass]
|
---|
42 | public sealed class IndepdentRandomRestarter : NamedItem, IOptimizer, IStorableContent, INotifyPropertyChanged {
|
---|
43 | private const string ExecutionTimeResultName = "Execution Time";
|
---|
44 | private const string BestQualityResultName = "BestQuality";
|
---|
45 | private const string RandomRestartsResultName = "RandomRestarts";
|
---|
46 | private const string EvaluatedSolutionsResultName = "EvaluatedSolutions";
|
---|
47 | private const string EvaluatedMovesResultName = "EvaluatedMoves";
|
---|
48 | private const string QualityPerClockResultName = "QualityPerClock";
|
---|
49 | private const string QualityPerEvaluationsResultName = "QualityPerEvaluations";
|
---|
50 |
|
---|
51 | public string Filename { get; set; }
|
---|
52 |
|
---|
53 | #region ItemImage
|
---|
54 | public static new Image StaticItemImage {
|
---|
55 | get { return VSImageLibrary.Event; }
|
---|
56 | }
|
---|
57 | public override Image ItemImage {
|
---|
58 | get { return (Algorithm != null) ? Algorithm.ItemImage : VSImageLibrary.ExecutableStopped; }
|
---|
59 | }
|
---|
60 | #endregion
|
---|
61 |
|
---|
62 | [Storable]
|
---|
63 | private TerminationCriterium terminationCriterium;
|
---|
64 | public TerminationCriterium TerminationCriterium {
|
---|
65 | get { return terminationCriterium; }
|
---|
66 | set {
|
---|
67 | if (terminationCriterium == value) return;
|
---|
68 | terminationCriterium = value;
|
---|
69 | OnPropertyChanged("TerminationCriterium");
|
---|
70 | }
|
---|
71 | }
|
---|
72 |
|
---|
73 | [Storable]
|
---|
74 | private TimeSpan maximumExecutionTime;
|
---|
75 | public TimeSpan MaximumExecutionTime {
|
---|
76 | get { return maximumExecutionTime; }
|
---|
77 | set {
|
---|
78 | if (maximumExecutionTime == value) return;
|
---|
79 | maximumExecutionTime = value;
|
---|
80 | OnPropertyChanged("MaximumExecutionTime");
|
---|
81 | }
|
---|
82 | }
|
---|
83 |
|
---|
84 | [Storable]
|
---|
85 | private int maximumEvaluations;
|
---|
86 | public int MaximumEvaluations {
|
---|
87 | get { return maximumEvaluations; }
|
---|
88 | set {
|
---|
89 | if (maximumEvaluations == value) return;
|
---|
90 | maximumEvaluations = value;
|
---|
91 | OnPropertyChanged("MaximumEvaluations");
|
---|
92 | }
|
---|
93 | }
|
---|
94 |
|
---|
95 | [Storable]
|
---|
96 | private double targetValue;
|
---|
97 | public double TargetValue {
|
---|
98 | get { return targetValue; }
|
---|
99 | set {
|
---|
100 | if (targetValue == value) return;
|
---|
101 | targetValue = value;
|
---|
102 | OnPropertyChanged("TargetValue");
|
---|
103 | }
|
---|
104 | }
|
---|
105 |
|
---|
106 | [Storable]
|
---|
107 | private bool maximization;
|
---|
108 | public bool Maximization {
|
---|
109 | get { return maximization; }
|
---|
110 | set {
|
---|
111 | if (maximization == value) return;
|
---|
112 | maximization = value;
|
---|
113 | OnPropertyChanged("Maximization");
|
---|
114 | }
|
---|
115 | }
|
---|
116 |
|
---|
117 | [Storable]
|
---|
118 | private double moveCostPerSolution;
|
---|
119 | public double MoveCostPerSolution {
|
---|
120 | get { return moveCostPerSolution; }
|
---|
121 | set {
|
---|
122 | if (moveCostPerSolution == value) return;
|
---|
123 | moveCostPerSolution = value;
|
---|
124 | perEvaluationsAnalyzer.MoveCostPerSolutionParameter.Value = new DoubleValue(moveCostPerSolution);
|
---|
125 | OnPropertyChanged("MoveCostPerSolution");
|
---|
126 | }
|
---|
127 | }
|
---|
128 |
|
---|
129 | [Storable]
|
---|
130 | private bool storeSolutionInRun;
|
---|
131 | public bool StoreSolutionInRun {
|
---|
132 | get { return storeSolutionInRun; }
|
---|
133 | set {
|
---|
134 | if (storeSolutionInRun == value) return;
|
---|
135 | storeSolutionInRun = value;
|
---|
136 | OnPropertyChanged("StoreSolutionInRun");
|
---|
137 | }
|
---|
138 | }
|
---|
139 |
|
---|
140 | [Storable]
|
---|
141 | private QualityPerClockAnalyzer perClockAnalyzer;
|
---|
142 | [Storable]
|
---|
143 | private QualityPerEvaluationsAnalyzer perEvaluationsAnalyzer;
|
---|
144 |
|
---|
145 | [Storable]
|
---|
146 | private ExecutionState executionState;
|
---|
147 | public ExecutionState ExecutionState {
|
---|
148 | get { return executionState; }
|
---|
149 | private set {
|
---|
150 | if (executionState != value) {
|
---|
151 | executionState = value;
|
---|
152 | OnExecutionStateChanged();
|
---|
153 | OnItemImageChanged();
|
---|
154 | }
|
---|
155 | }
|
---|
156 | }
|
---|
157 |
|
---|
158 | private TimeSpan lastAlgorithmExecutionTime;
|
---|
159 | [Storable]
|
---|
160 | private TimeSpan executionTime;
|
---|
161 | public TimeSpan ExecutionTime {
|
---|
162 | get { return executionTime; }
|
---|
163 | set {
|
---|
164 | if (executionTime == value) return;
|
---|
165 | executionTime = value;
|
---|
166 | OnPropertyChanged("ExecutionTime");
|
---|
167 | OnExecutionTimeChanged();
|
---|
168 | }
|
---|
169 | }
|
---|
170 |
|
---|
171 | [Storable]
|
---|
172 | private double evaluations;
|
---|
173 | public double Evaluations {
|
---|
174 | get { return evaluations; }
|
---|
175 | set {
|
---|
176 | if (evaluations == value) return;
|
---|
177 | evaluations = value;
|
---|
178 | OnPropertyChanged("Evaluations");
|
---|
179 | }
|
---|
180 | }
|
---|
181 |
|
---|
182 | [Storable]
|
---|
183 | private double bestSoFar;
|
---|
184 | public double BestSoFar {
|
---|
185 | get { return bestSoFar; }
|
---|
186 | set {
|
---|
187 | if (bestSoFar == value) return;
|
---|
188 | bestSoFar = value;
|
---|
189 | OnPropertyChanged("BestSoFar");
|
---|
190 | }
|
---|
191 | }
|
---|
192 |
|
---|
193 | [Storable]
|
---|
194 | private IRun currentRun;
|
---|
195 | public IRun CurrentRun {
|
---|
196 | get { return currentRun; }
|
---|
197 | private set {
|
---|
198 | if (currentRun == value) return;
|
---|
199 | currentRun = value;
|
---|
200 | OnPropertyChanged("CurrentRun");
|
---|
201 | }
|
---|
202 | }
|
---|
203 |
|
---|
204 | [Storable]
|
---|
205 | private IAlgorithm algorithm;
|
---|
206 | public IAlgorithm Algorithm {
|
---|
207 | get { return algorithm; }
|
---|
208 | set {
|
---|
209 | if (algorithm == value) return;
|
---|
210 | if (algorithm != null) {
|
---|
211 | DeregisterAlgorithmEvents();
|
---|
212 | RemoveAlgorithmAnalyzers();
|
---|
213 | }
|
---|
214 | algorithm = value;
|
---|
215 | if (algorithm != null) {
|
---|
216 | RegisterAlgorithmEvents();
|
---|
217 | AddAlgorithmAnalyzers();
|
---|
218 | }
|
---|
219 | OnPropertyChanged("Algorithm");
|
---|
220 | Prepare();
|
---|
221 | }
|
---|
222 | }
|
---|
223 |
|
---|
224 | [Storable]
|
---|
225 | private RunCollection runs;
|
---|
226 | public RunCollection Runs {
|
---|
227 | get { return runs; }
|
---|
228 | private set {
|
---|
229 | if (value == null) throw new ArgumentNullException();
|
---|
230 | if (runs == value) return;
|
---|
231 | runs = value;
|
---|
232 | OnPropertyChanged("Runs");
|
---|
233 | }
|
---|
234 | }
|
---|
235 |
|
---|
236 | public IEnumerable<IOptimizer> NestedOptimizers {
|
---|
237 | get {
|
---|
238 | if (Algorithm == null) yield break;
|
---|
239 | yield return Algorithm;
|
---|
240 | foreach (var opt in Algorithm.NestedOptimizers)
|
---|
241 | yield return opt;
|
---|
242 | }
|
---|
243 | }
|
---|
244 |
|
---|
245 | private bool IsFinished {
|
---|
246 | get {
|
---|
247 | var timeHit = ExecutionTime >= MaximumExecutionTime;
|
---|
248 | var evalHit = Evaluations >= MaximumEvaluations;
|
---|
249 | var targetHit = (Maximization && BestSoFar >= TargetValue || !Maximization && BestSoFar <= TargetValue);
|
---|
250 |
|
---|
251 | return timeHit && evalHit && targetHit
|
---|
252 | || timeHit && (TerminationCriterium == TerminationCriterium.OnlyByTime
|
---|
253 | || TerminationCriterium == TerminationCriterium.WhicheverHitsFirst
|
---|
254 | || TerminationCriterium == TerminationCriterium.ByTargetAndTime
|
---|
255 | || TerminationCriterium == TerminationCriterium.ByTimeAndEvaluations)
|
---|
256 | || evalHit && (TerminationCriterium == TerminationCriterium.OnlyByEvaluations
|
---|
257 | || TerminationCriterium == TerminationCriterium.WhicheverHitsFirst
|
---|
258 | || TerminationCriterium == TerminationCriterium.ByTargetAndEvaluations
|
---|
259 | || TerminationCriterium == TerminationCriterium.ByTimeAndEvaluations)
|
---|
260 | || targetHit && (TerminationCriterium == TerminationCriterium.OnlyByTarget
|
---|
261 | || TerminationCriterium == TerminationCriterium.WhicheverHitsFirst
|
---|
262 | || TerminationCriterium == TerminationCriterium.ByTargetAndTime
|
---|
263 | || TerminationCriterium == TerminationCriterium.ByTargetAndEvaluations);
|
---|
264 | }
|
---|
265 | }
|
---|
266 |
|
---|
267 | private ISingleObjectiveHeuristicOptimizationProblem problem;
|
---|
268 |
|
---|
269 | [StorableConstructor]
|
---|
270 | private IndepdentRandomRestarter(bool deserializing) : base(deserializing) { }
|
---|
271 | private IndepdentRandomRestarter(IndepdentRandomRestarter original, Cloner cloner)
|
---|
272 | : base(original, cloner) {
|
---|
273 | terminationCriterium = original.terminationCriterium;
|
---|
274 | maximumExecutionTime = original.maximumExecutionTime;
|
---|
275 | maximumEvaluations = original.maximumEvaluations;
|
---|
276 | moveCostPerSolution = original.moveCostPerSolution;
|
---|
277 | storeSolutionInRun = original.storeSolutionInRun;
|
---|
278 | targetValue = original.targetValue;
|
---|
279 | maximization = original.maximization;
|
---|
280 | executionTime = original.executionTime;
|
---|
281 | evaluations = original.evaluations;
|
---|
282 | bestSoFar = original.bestSoFar;
|
---|
283 | lastAlgorithmExecutionTime = original.lastAlgorithmExecutionTime;
|
---|
284 |
|
---|
285 | perClockAnalyzer = cloner.Clone(original.perClockAnalyzer);
|
---|
286 | perEvaluationsAnalyzer = cloner.Clone(original.perEvaluationsAnalyzer);
|
---|
287 |
|
---|
288 | algorithm = cloner.Clone(original.algorithm);
|
---|
289 | runs = cloner.Clone(original.runs);
|
---|
290 |
|
---|
291 | ExecutionState = original.ExecutionState;
|
---|
292 |
|
---|
293 | Initialize();
|
---|
294 | }
|
---|
295 | public IndepdentRandomRestarter()
|
---|
296 | : base() {
|
---|
297 | name = ItemName;
|
---|
298 | description = ItemDescription;
|
---|
299 | terminationCriterium = TerminationCriterium.ByTargetAndEvaluations;
|
---|
300 | maximumExecutionTime = TimeSpan.FromMinutes(1);
|
---|
301 | maximumEvaluations = 10000000; // 10 mio
|
---|
302 | moveCostPerSolution = 1;
|
---|
303 | storeSolutionInRun = false;
|
---|
304 | targetValue = 0;
|
---|
305 | maximization = false;
|
---|
306 | executionTime = TimeSpan.Zero;
|
---|
307 | evaluations = 0;
|
---|
308 | bestSoFar = double.NaN;
|
---|
309 | lastAlgorithmExecutionTime = TimeSpan.Zero;
|
---|
310 |
|
---|
311 | perClockAnalyzer = new QualityPerClockAnalyzer();
|
---|
312 | perEvaluationsAnalyzer = new QualityPerEvaluationsAnalyzer();
|
---|
313 |
|
---|
314 | Runs = new RunCollection { OptimizerName = Name };
|
---|
315 | Initialize();
|
---|
316 | }
|
---|
317 | public IndepdentRandomRestarter(string name)
|
---|
318 | : base(name) {
|
---|
319 | description = ItemDescription;
|
---|
320 | terminationCriterium = TerminationCriterium.ByTargetAndEvaluations;
|
---|
321 | maximumExecutionTime = TimeSpan.FromMinutes(1);
|
---|
322 | maximumEvaluations = 10000000; // 10 mio
|
---|
323 | moveCostPerSolution = 1;
|
---|
324 | storeSolutionInRun = false;
|
---|
325 | targetValue = 0;
|
---|
326 | maximization = false;
|
---|
327 | executionTime = TimeSpan.Zero;
|
---|
328 | evaluations = 0;
|
---|
329 | bestSoFar = double.NaN;
|
---|
330 | lastAlgorithmExecutionTime = TimeSpan.Zero;
|
---|
331 |
|
---|
332 | perClockAnalyzer = new QualityPerClockAnalyzer();
|
---|
333 | perEvaluationsAnalyzer = new QualityPerEvaluationsAnalyzer();
|
---|
334 |
|
---|
335 | Runs = new RunCollection { OptimizerName = Name };
|
---|
336 | Initialize();
|
---|
337 | }
|
---|
338 | public IndepdentRandomRestarter(string name, string description)
|
---|
339 | : base(name, description) {
|
---|
340 | terminationCriterium = TerminationCriterium.ByTargetAndEvaluations;
|
---|
341 | maximumExecutionTime = TimeSpan.FromMinutes(1);
|
---|
342 | maximumEvaluations = 10000000; // 10 mio
|
---|
343 | moveCostPerSolution = 1;
|
---|
344 | storeSolutionInRun = false;
|
---|
345 | targetValue = 0;
|
---|
346 | maximization = false;
|
---|
347 | executionTime = TimeSpan.Zero;
|
---|
348 | evaluations = 0;
|
---|
349 | bestSoFar = double.NaN;
|
---|
350 | lastAlgorithmExecutionTime = TimeSpan.Zero;
|
---|
351 |
|
---|
352 | perClockAnalyzer = new QualityPerClockAnalyzer();
|
---|
353 | perEvaluationsAnalyzer = new QualityPerEvaluationsAnalyzer();
|
---|
354 |
|
---|
355 | Runs = new RunCollection { OptimizerName = Name };
|
---|
356 | Initialize();
|
---|
357 | }
|
---|
358 |
|
---|
359 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
360 | if (ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
|
---|
361 | return new IndepdentRandomRestarter(this, cloner);
|
---|
362 | }
|
---|
363 |
|
---|
364 | [StorableHook(HookType.AfterDeserialization)]
|
---|
365 | private void AfterDeserialization() {
|
---|
366 | Initialize();
|
---|
367 | }
|
---|
368 |
|
---|
369 | private void Initialize() {
|
---|
370 | if (algorithm != null) RegisterAlgorithmEvents();
|
---|
371 | }
|
---|
372 |
|
---|
373 | private void Reset() {
|
---|
374 | ExecutionTime = TimeSpan.Zero;
|
---|
375 | Evaluations = 0;
|
---|
376 | BestSoFar = double.NaN;
|
---|
377 | lastAlgorithmExecutionTime = TimeSpan.Zero;
|
---|
378 |
|
---|
379 | CurrentRun = null;
|
---|
380 | }
|
---|
381 |
|
---|
382 | public void Prepare() {
|
---|
383 | Prepare(false);
|
---|
384 | }
|
---|
385 | public void Prepare(bool clearRuns) {
|
---|
386 | if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused) && (ExecutionState != ExecutionState.Stopped))
|
---|
387 | throw new InvalidOperationException(string.Format("Prepare not allowed in execution state \"{0}\".", ExecutionState));
|
---|
388 | Reset();
|
---|
389 |
|
---|
390 | if (Algorithm != null) {
|
---|
391 | Algorithm.Prepare(clearRuns);
|
---|
392 | ExecutionState = ExecutionState.Prepared;
|
---|
393 | OnPrepared();
|
---|
394 | }
|
---|
395 | }
|
---|
396 | public void Start() {
|
---|
397 | if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
|
---|
398 | throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
|
---|
399 |
|
---|
400 | if (ExecutionState == ExecutionState.Prepared) {
|
---|
401 | CurrentRun = new Run(Algorithm) {
|
---|
402 | Name = Algorithm.Name + " IRRRun" + Runs.Count
|
---|
403 | };
|
---|
404 | if (!CurrentRun.Results.ContainsKey(ExecutionTimeResultName))
|
---|
405 | CurrentRun.Results.Add(ExecutionTimeResultName, new TimeSpanValue(TimeSpan.Zero));
|
---|
406 | // use double instead of int, otherwise one might run into int.MaxValue (at least with moves)
|
---|
407 | CurrentRun.Results.Add(EvaluatedSolutionsResultName, new DoubleValue(0));
|
---|
408 | CurrentRun.Results.Add(EvaluatedMovesResultName, new DoubleValue(0));
|
---|
409 | CurrentRun.Results.Add(BestQualityResultName, new DoubleValue(Maximization ? double.MinValue : double.MaxValue));
|
---|
410 | CurrentRun.Results.Add(RandomRestartsResultName, new IntValue(0));
|
---|
411 | }
|
---|
412 | if (Algorithm.ExecutionState == ExecutionState.Stopped)
|
---|
413 | Algorithm.Prepare(true);
|
---|
414 | Algorithm.Start();
|
---|
415 | ExecutionState = ExecutionState.Started;
|
---|
416 | OnStarted();
|
---|
417 | }
|
---|
418 | public void Pause() {
|
---|
419 | if (ExecutionState != ExecutionState.Started)
|
---|
420 | throw new InvalidOperationException(string.Format("Pause not allowed in execution state \"{0}\".", ExecutionState));
|
---|
421 | Algorithm.Pause();
|
---|
422 | ExecutionState = ExecutionState.Paused;
|
---|
423 | OnPaused();
|
---|
424 | }
|
---|
425 |
|
---|
426 | private bool forceStop = false;
|
---|
427 | public void Stop() {
|
---|
428 | if ((ExecutionState != ExecutionState.Started) && (ExecutionState != ExecutionState.Paused))
|
---|
429 | throw new InvalidOperationException(string.Format("Stop not allowed in execution state \"{0}\".", ExecutionState));
|
---|
430 | forceStop = true;
|
---|
431 | try {
|
---|
432 | Algorithm.Stop();
|
---|
433 | } catch (InvalidOperationException) {
|
---|
434 | // sometimes we hit the algorithm in an invalid state
|
---|
435 | }
|
---|
436 | }
|
---|
437 |
|
---|
438 | private void AddAlgorithmAnalyzers() {
|
---|
439 | if (!Algorithm.Parameters.ContainsKey("Analyzer")) return;
|
---|
440 | var analyzerParam = Algorithm.Parameters["Analyzer"] as IValueParameter<MultiAnalyzer>;
|
---|
441 | if (analyzerParam == null) return;
|
---|
442 | if (!analyzerParam.Value.Operators.Contains(perClockAnalyzer))
|
---|
443 | analyzerParam.Value.Operators.Add(perClockAnalyzer);
|
---|
444 | if (!analyzerParam.Value.Operators.Contains(perEvaluationsAnalyzer))
|
---|
445 | analyzerParam.Value.Operators.Add(perEvaluationsAnalyzer);
|
---|
446 | }
|
---|
447 |
|
---|
448 | private void RemoveAlgorithmAnalyzers() {
|
---|
449 | if (!Algorithm.Parameters.ContainsKey("Analyzer")) return;
|
---|
450 | var analyzerParam = Algorithm.Parameters["Analyzer"] as IValueParameter<MultiAnalyzer>;
|
---|
451 | if (analyzerParam == null) return;
|
---|
452 | analyzerParam.Value.Operators.Remove(perClockAnalyzer);
|
---|
453 | analyzerParam.Value.Operators.Remove(perEvaluationsAnalyzer);
|
---|
454 | }
|
---|
455 |
|
---|
456 | #region Events
|
---|
457 | protected override void OnNameChanged() {
|
---|
458 | base.OnNameChanged();
|
---|
459 | runs.OptimizerName = Name;
|
---|
460 | }
|
---|
461 |
|
---|
462 | public event PropertyChangedEventHandler PropertyChanged;
|
---|
463 | private void OnPropertyChanged(string property) {
|
---|
464 | var handler = PropertyChanged;
|
---|
465 | if (handler != null) handler(this, new PropertyChangedEventArgs(property));
|
---|
466 | }
|
---|
467 |
|
---|
468 | #region IExecutable Events
|
---|
469 | public event EventHandler ExecutionStateChanged;
|
---|
470 | private void OnExecutionStateChanged() {
|
---|
471 | var handler = ExecutionStateChanged;
|
---|
472 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
473 | }
|
---|
474 | public event EventHandler ExecutionTimeChanged;
|
---|
475 | private void OnExecutionTimeChanged() {
|
---|
476 | var handler = ExecutionTimeChanged;
|
---|
477 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
478 | }
|
---|
479 | public event EventHandler Prepared;
|
---|
480 | private void OnPrepared() {
|
---|
481 | var handler = Prepared;
|
---|
482 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
483 | }
|
---|
484 | public event EventHandler Started;
|
---|
485 | private void OnStarted() {
|
---|
486 | var handler = Started;
|
---|
487 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
488 | }
|
---|
489 | public event EventHandler Paused;
|
---|
490 | private void OnPaused() {
|
---|
491 | var handler = Paused;
|
---|
492 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
493 | }
|
---|
494 | public event EventHandler Stopped;
|
---|
495 | private void OnStopped() {
|
---|
496 | var handler = Stopped;
|
---|
497 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
498 | }
|
---|
499 | public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
|
---|
500 | private void OnExceptionOccurred(Exception exception) {
|
---|
501 | var handler = ExceptionOccurred;
|
---|
502 | if (handler != null) handler(this, new EventArgs<Exception>(exception));
|
---|
503 | }
|
---|
504 | #endregion
|
---|
505 |
|
---|
506 | #region Algorithm Events
|
---|
507 | private void RegisterAlgorithmEvents() {
|
---|
508 | algorithm.ExceptionOccurred += Algorithm_ExceptionOccurred;
|
---|
509 | algorithm.ExecutionTimeChanged += Algorithm_ExecutionTimeChanged;
|
---|
510 | algorithm.Paused += Algorithm_Paused;
|
---|
511 | algorithm.Prepared += Algorithm_Prepared;
|
---|
512 | algorithm.Stopped += Algorithm_Stopped;
|
---|
513 | algorithm.ProblemChanged += Algorithm_ProblemChanged;
|
---|
514 | Algorithm_ProblemChanged(algorithm, EventArgs.Empty);
|
---|
515 | }
|
---|
516 | private void DeregisterAlgorithmEvents() {
|
---|
517 | algorithm.ExceptionOccurred -= Algorithm_ExceptionOccurred;
|
---|
518 | algorithm.ExecutionTimeChanged -= Algorithm_ExecutionTimeChanged;
|
---|
519 | algorithm.Paused -= Algorithm_Paused;
|
---|
520 | algorithm.Prepared -= Algorithm_Prepared;
|
---|
521 | algorithm.Stopped -= Algorithm_Stopped;
|
---|
522 | algorithm.ProblemChanged -= Algorithm_ProblemChanged;
|
---|
523 | }
|
---|
524 | private void Algorithm_ExceptionOccurred(object sender, EventArgs<Exception> e) {
|
---|
525 | OnExceptionOccurred(e.Value);
|
---|
526 | }
|
---|
527 | private void Algorithm_ExecutionTimeChanged(object sender, EventArgs e) {
|
---|
528 | ExecutionTime += Algorithm.ExecutionTime - lastAlgorithmExecutionTime;
|
---|
529 | lastAlgorithmExecutionTime = Algorithm.ExecutionTime;
|
---|
530 | }
|
---|
531 | private void Algorithm_Paused(object sender, EventArgs e) {
|
---|
532 | ExecutionTime += Algorithm.ExecutionTime - lastAlgorithmExecutionTime;
|
---|
533 | lastAlgorithmExecutionTime = Algorithm.ExecutionTime;
|
---|
534 | OnPaused();
|
---|
535 | }
|
---|
536 | private void Algorithm_Prepared(object sender, EventArgs e) {
|
---|
537 | lastAlgorithmExecutionTime = TimeSpan.Zero;
|
---|
538 | }
|
---|
539 | private void Algorithm_Stopped(object sender, EventArgs e) {
|
---|
540 | ExecutionTime += Algorithm.ExecutionTime - lastAlgorithmExecutionTime;
|
---|
541 | lastAlgorithmExecutionTime = Algorithm.ExecutionTime;
|
---|
542 |
|
---|
543 | var execTime = ((TimeSpanValue)CurrentRun.Results[ExecutionTimeResultName]).Value;
|
---|
544 | var solEvals = ((DoubleValue)CurrentRun.Results[EvaluatedSolutionsResultName]).Value;
|
---|
545 | var movEvals = ((DoubleValue)CurrentRun.Results[EvaluatedMovesResultName]).Value;
|
---|
546 | var restarts = ((IntValue)CurrentRun.Results[RandomRestartsResultName]).Value;
|
---|
547 | var improvement = false;
|
---|
548 |
|
---|
549 | IResult result;
|
---|
550 | if (Algorithm.Results.TryGetValue(perEvaluationsAnalyzer.EvaluatedSolutionsParameter.ActualName, out result)) {
|
---|
551 | var evals = ((IntValue)result.Value).Value;
|
---|
552 | Evaluations += evals;
|
---|
553 | CurrentRun.Results[EvaluatedSolutionsResultName] = new DoubleValue(solEvals + evals);
|
---|
554 | }
|
---|
555 | if (Algorithm.Results.TryGetValue(perEvaluationsAnalyzer.EvaluatedMovesParameter.ActualName, out result)) {
|
---|
556 | var evals = ((IntValue)result.Value).Value;
|
---|
557 | Evaluations += moveCostPerSolution * evals;
|
---|
558 | CurrentRun.Results[EvaluatedMovesResultName] = new DoubleValue(movEvals + evals);
|
---|
559 | }
|
---|
560 | if (Algorithm.Results.TryGetValue(perEvaluationsAnalyzer.BestQualityParameter.ActualName, out result)) {
|
---|
561 | var bestQuality = ((DoubleValue)result.Value).Value;
|
---|
562 | if (double.IsNaN(BestSoFar)
|
---|
563 | || Maximization && bestQuality > BestSoFar
|
---|
564 | || !Maximization && bestQuality < BestSoFar) {
|
---|
565 | BestSoFar = bestQuality;
|
---|
566 | CurrentRun.Results[BestQualityResultName] = new DoubleValue(bestQuality);
|
---|
567 | improvement = true;
|
---|
568 | }
|
---|
569 | }
|
---|
570 | if (Algorithm.Results.TryGetValue(perClockAnalyzer.QualityPerClockParameter.ResultName, out result)) {
|
---|
571 | UpdateQualityPerClockResult((IndexedDataTable<double>)result.Value, execTime, restarts);
|
---|
572 | }
|
---|
573 | if (Algorithm.Results.TryGetValue(perEvaluationsAnalyzer.QualityPerEvaluationsParameter.ResultName, out result)) {
|
---|
574 | UpdateQualityPerEvaluationsResult((IndexedDataTable<double>)result.Value, solEvals, movEvals, restarts);
|
---|
575 | }
|
---|
576 | if (StoreSolutionInRun) {
|
---|
577 | foreach (var r in Algorithm.Results) {
|
---|
578 | if (r.Name.ToLower().EndsWith("solution") && improvement) {
|
---|
579 | CurrentRun.Results[r.Name] = (IItem)r.Value.Clone();
|
---|
580 | }
|
---|
581 | }
|
---|
582 | }
|
---|
583 |
|
---|
584 | CurrentRun.Results[ExecutionTimeResultName] = new TimeSpanValue(execTime + Algorithm.ExecutionTime);
|
---|
585 |
|
---|
586 | // Algorithm sets ExecutionTime to zero before firing Prepared
|
---|
587 | // We will thus see ExecutionTimeChanged before Prepared
|
---|
588 | lastAlgorithmExecutionTime = TimeSpan.Zero;
|
---|
589 |
|
---|
590 | if (!forceStop && !IsFinished) {
|
---|
591 | CurrentRun.Results[RandomRestartsResultName] = new IntValue(restarts + 1);
|
---|
592 | Algorithm.Prepare(true);
|
---|
593 | Algorithm.Start();
|
---|
594 | } else {
|
---|
595 | forceStop = false;
|
---|
596 | Runs.Add(CurrentRun);
|
---|
597 | Algorithm.Prepare(true);
|
---|
598 | ExecutionState = ExecutionState.Stopped;
|
---|
599 | OnStopped();
|
---|
600 | }
|
---|
601 | }
|
---|
602 |
|
---|
603 | private void UpdateQualityPerClockResult(IndexedDataTable<double> perClock, TimeSpan execTime, int restarts) {
|
---|
604 | IndexedDataTable<double> dt;
|
---|
605 | if (!CurrentRun.Results.ContainsKey(QualityPerClockResultName)) {
|
---|
606 | dt = (IndexedDataTable<double>)perClock.Clone();
|
---|
607 | if (!dt.Rows.ContainsKey("Restarts"))
|
---|
608 | dt.Rows.Add(new IndexedDataRow<double>("Restarts") {
|
---|
609 | VisualProperties = {
|
---|
610 | ChartType = DataRowVisualProperties.DataRowChartType.StepLine,
|
---|
611 | SecondYAxis = true
|
---|
612 | }
|
---|
613 | });
|
---|
614 | foreach (var v in dt.Rows.First().Values)
|
---|
615 | dt.Rows["Restarts"].Values.Add(Tuple.Create(v.Item1, 0.0));
|
---|
616 | CurrentRun.Results.Add(QualityPerClockResultName, dt);
|
---|
617 | } else {
|
---|
618 | dt = (IndexedDataTable<double>)CurrentRun.Results[QualityPerClockResultName];
|
---|
619 | var best = dt.Rows.First().Values.Last().Item2;
|
---|
620 | foreach (var tupl in perClock.Rows.First().Values) {
|
---|
621 | if (Maximization && tupl.Item2 > best || !Maximization && tupl.Item2 < best) {
|
---|
622 | dt.Rows.First().Values.Add(Tuple.Create(execTime.TotalSeconds + tupl.Item1, tupl.Item2));
|
---|
623 | dt.Rows["Restarts"].Values.Add(Tuple.Create(execTime.TotalSeconds + tupl.Item1, (double)restarts));
|
---|
624 | best = tupl.Item2;
|
---|
625 | }
|
---|
626 | }
|
---|
627 | }
|
---|
628 | if (IsFinished) {
|
---|
629 | dt.Rows.First().Values.Add(Tuple.Create(ExecutionTime.TotalSeconds, BestSoFar));
|
---|
630 | dt.Rows["Restarts"].Values.Add(Tuple.Create(ExecutionTime.TotalSeconds, (double)restarts));
|
---|
631 | }
|
---|
632 | }
|
---|
633 |
|
---|
634 | private void UpdateQualityPerEvaluationsResult(IndexedDataTable<double> perEvaluations, double solEvals, double movEvals, int restarts) {
|
---|
635 | IndexedDataTable<double> dt;
|
---|
636 | if (!CurrentRun.Results.ContainsKey(QualityPerEvaluationsResultName)) {
|
---|
637 | dt = (IndexedDataTable<double>)perEvaluations.Clone();
|
---|
638 | if (!dt.Rows.ContainsKey("Restarts"))
|
---|
639 | dt.Rows.Add(new IndexedDataRow<double>("Restarts") {
|
---|
640 | VisualProperties = {
|
---|
641 | ChartType = DataRowVisualProperties.DataRowChartType.StepLine,
|
---|
642 | SecondYAxis = true
|
---|
643 | }
|
---|
644 | });
|
---|
645 | foreach (var v in dt.Rows.First().Values)
|
---|
646 | dt.Rows["Restarts"].Values.Add(Tuple.Create(v.Item1, 0.0));
|
---|
647 | CurrentRun.Results.Add(QualityPerEvaluationsResultName, dt);
|
---|
648 | } else {
|
---|
649 | dt = (IndexedDataTable<double>)CurrentRun.Results[QualityPerEvaluationsResultName];
|
---|
650 | var best = dt.Rows.First().Values.Last().Item2;
|
---|
651 | foreach (var tupl in perEvaluations.Rows.First().Values) {
|
---|
652 | if (Maximization && tupl.Item2 > best || !Maximization && tupl.Item2 < best) {
|
---|
653 | dt.Rows.First().Values.Add(Tuple.Create(solEvals + moveCostPerSolution * movEvals + tupl.Item1, tupl.Item2));
|
---|
654 | dt.Rows["Restarts"].Values.Add(Tuple.Create(solEvals + moveCostPerSolution * movEvals + tupl.Item1, (double)restarts));
|
---|
655 | best = tupl.Item2;
|
---|
656 | }
|
---|
657 | }
|
---|
658 | }
|
---|
659 | if (IsFinished) {
|
---|
660 | dt.Rows.First().Values.Add(Tuple.Create(Evaluations, BestSoFar));
|
---|
661 | dt.Rows["Restarts"].Values.Add(Tuple.Create(Evaluations, (double)restarts));
|
---|
662 | }
|
---|
663 | }
|
---|
664 |
|
---|
665 | private void Algorithm_ProblemChanged(object sender, EventArgs e) {
|
---|
666 | if (problem != null) DeregisterProblemEvents();
|
---|
667 |
|
---|
668 | problem = Algorithm.Problem as ISingleObjectiveHeuristicOptimizationProblem;
|
---|
669 | if (problem == null) return;
|
---|
670 | RegisterProblemEvents();
|
---|
671 |
|
---|
672 | AddAlgorithmAnalyzers();
|
---|
673 |
|
---|
674 | var maxParam = problem.MaximizationParameter as IValueParameter<BoolValue>;
|
---|
675 | if (maxParam != null)
|
---|
676 | Maximization = maxParam.Value.Value;
|
---|
677 | var bkParam = problem.BestKnownQualityParameter as IValueParameter<DoubleValue>;
|
---|
678 | if (bkParam != null && bkParam.Value != null)
|
---|
679 | TargetValue = bkParam.Value.Value;
|
---|
680 |
|
---|
681 | Reset();
|
---|
682 | }
|
---|
683 |
|
---|
684 | private void RegisterProblemEvents() {
|
---|
685 | problem.Reset += ProblemOnReset;
|
---|
686 | problem.OperatorsChanged += ProblemOnOperatorsChanged;
|
---|
687 | }
|
---|
688 |
|
---|
689 | private void DeregisterProblemEvents() {
|
---|
690 | problem.Reset -= ProblemOnReset;
|
---|
691 | problem.OperatorsChanged -= ProblemOnOperatorsChanged;
|
---|
692 | }
|
---|
693 |
|
---|
694 | private void ProblemOnReset(object sender, EventArgs eventArgs) {
|
---|
695 | AddAlgorithmAnalyzers();
|
---|
696 | }
|
---|
697 |
|
---|
698 | private void ProblemOnOperatorsChanged(object sender, EventArgs eventArgs) {
|
---|
699 | AddAlgorithmAnalyzers();
|
---|
700 | }
|
---|
701 | #endregion
|
---|
702 | #endregion
|
---|
703 | }
|
---|
704 | }
|
---|