Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GeneralizedQAP/HeuristicLab.Optimization/3.3/Algorithms/BasicAlgorithm.cs @ 15603

Last change on this file since 15603 was 15603, checked in by abeham, 6 years ago

#1614: Implemented changed behavior to measure execution time (cf. #2869)

File size: 5.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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.Threading;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
27
28namespace HeuristicLab.Optimization {
29  [StorableClass]
30  public abstract class BasicAlgorithm : Algorithm, IStorableContent {
31
32    private bool pausePending;
33    private bool executionTimeActive;
34
35    public string Filename { get; set; }
36
37    public abstract bool SupportsPause { get; }
38
39    [Storable]
40    private bool initialized;
41    [Storable]
42    private readonly ResultCollection results;
43    public override ResultCollection Results {
44      get { return results; }
45    }
46
47    private CancellationTokenSource cancellationTokenSource;
48    protected CancellationTokenSource CancellationTokenSource {
49      get { return cancellationTokenSource; }
50      private set { cancellationTokenSource = value; }
51    }
52
53    [Storable]
54    private TimeSpan executionTime;
55    private DateTime startDate;
56    public override TimeSpan ExecutionTime {
57      get { return executionTime + (executionTimeActive ? DateTime.UtcNow - startDate : TimeSpan.Zero); }
58    }
59
60    [StorableConstructor]
61    protected BasicAlgorithm(bool deserializing) : base(deserializing) { }
62    protected BasicAlgorithm(BasicAlgorithm original, Cloner cloner)
63      : base(original, cloner) {
64      results = cloner.Clone(original.Results);
65      initialized = original.initialized;
66      executionTime = original.executionTime;
67    }
68    protected BasicAlgorithm()
69      : base() {
70      results = new ResultCollection();
71      executionTime = TimeSpan.Zero;
72    }
73
74    public override void Prepare() {
75      executionTime = TimeSpan.Zero;
76      if (Problem == null) return;
77      base.Prepare();
78      results.Clear();
79      initialized = false;
80      OnPrepared();
81    }
82
83    public override void Start(CancellationToken cancellationToken) {
84      startDate = DateTime.UtcNow;
85      executionTimeActive = true;
86      base.Start(cancellationToken);
87      CancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
88      pausePending = false;
89      OnStarted();
90
91      try {
92        Run((object)cancellationTokenSource.Token);
93      }
94      catch (OperationCanceledException) {
95      }
96      catch (AggregateException ae) {
97        ae.FlattenAndHandle(new[] { typeof(OperationCanceledException) }, e => OnExceptionOccurred(e));
98      }
99      catch (Exception e) {
100        OnExceptionOccurred(e);
101      }
102
103      CancellationTokenSource.Dispose();
104      CancellationTokenSource = null;
105      if (pausePending) OnPaused();
106      else OnStopped();
107    }
108
109    public override void Pause() {
110      // CancellationToken.ThrowIfCancellationRequested() must be called from within the Run method, otherwise pause does nothing
111      // alternatively check the IsCancellationRequested property of the cancellation token
112      if (!SupportsPause)
113        throw new NotSupportedException("Pause is not supported by this algorithm.");
114
115      base.Pause();
116      pausePending = true;
117      CancellationTokenSource.Cancel();
118    }
119
120    public override void Stop() {
121      // CancellationToken.ThrowIfCancellationRequested() must be called from within the Run method, otherwise stop does nothing
122      // alternatively check the IsCancellationRequested property of the cancellation token
123      base.Stop();
124      if (ExecutionState == ExecutionState.Paused) OnStopped();
125      else CancellationTokenSource.Cancel();
126    }
127
128    private void Run(object state) {
129      CancellationToken cancellationToken = (CancellationToken)state;
130      if (!initialized)
131        Initialize(cancellationToken);
132      initialized = true;
133      Run(cancellationToken);
134    }
135
136    protected virtual void Initialize(CancellationToken cancellationToken) { }
137    protected abstract void Run(CancellationToken cancellationToken);
138
139    protected override void OnPaused() {
140      executionTime += DateTime.UtcNow - startDate;
141      executionTimeActive = false;
142      base.OnPaused();
143    }
144
145    protected override void OnStopped() {
146      if (executionTimeActive) { // don't do if going from pause to stop
147        executionTime += DateTime.UtcNow - startDate;
148        executionTimeActive = false;
149      }
150      base.OnStopped();
151    }
152  }
153}
Note: See TracBrowser for help on using the repository browser.