Free cookie consent management tool by TermsFeed Policy Generator

source: branches/1614_GeneralizedQAP/HeuristicLab.Optimization/3.3/Algorithms/BasicAlgorithm.cs @ 15683

Last change on this file since 15683 was 15605, checked in by abeham, 7 years ago

#1614: merged trunk into branch

File size: 5.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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      } catch (OperationCanceledException) {
94      } catch (AggregateException ae) {
95        ae.FlattenAndHandle(new[] { typeof(OperationCanceledException) }, e => OnExceptionOccurred(e));
96      } catch (Exception e) {
97        OnExceptionOccurred(e);
98      }
99
100      CancellationTokenSource.Dispose();
101      CancellationTokenSource = null;
102      if (pausePending) OnPaused();
103      else OnStopped();
104    }
105
106    public override void Pause() {
107      // CancellationToken.ThrowIfCancellationRequested() must be called from within the Run method, otherwise pause does nothing
108      // alternatively check the IsCancellationRequested property of the cancellation token
109      if (!SupportsPause)
110        throw new NotSupportedException("Pause is not supported by this algorithm.");
111
112      base.Pause();
113      pausePending = true;
114      if (CancellationTokenSource != null) CancellationTokenSource.Cancel();
115    }
116
117    public override void Stop() {
118      // CancellationToken.ThrowIfCancellationRequested() must be called from within the Run method, otherwise stop does nothing
119      // alternatively check the IsCancellationRequested property of the cancellation token
120      base.Stop();
121      if (ExecutionState == ExecutionState.Paused) OnStopped();
122      else if (CancellationTokenSource != null) CancellationTokenSource.Cancel();
123    }
124
125    private void Run(object state) {
126      CancellationToken cancellationToken = (CancellationToken)state;
127      if (!initialized)
128        Initialize(cancellationToken);
129      initialized = true;
130      Run(cancellationToken);
131    }
132
133    protected virtual void Initialize(CancellationToken cancellationToken) { }
134    protected abstract void Run(CancellationToken cancellationToken);
135
136    protected override void OnPaused() {
137      executionTime += DateTime.UtcNow - startDate;
138      executionTimeActive = false;
139      base.OnPaused();
140    }
141
142    protected override void OnStopped() {
143      if (executionTimeActive) { // don't do if going from pause to stop
144        executionTime += DateTime.UtcNow - startDate;
145        executionTimeActive = false;
146      }
147      base.OnStopped();
148    }
149  }
150}
Note: See TracBrowser for help on using the repository browser.