Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceReintegration/HeuristicLab.Optimization/3.3/Algorithms/BasicAlgorithm.cs @ 14927

Last change on this file since 14927 was 14927, checked in by gkronber, 7 years ago

#2520: changed all usages of StorableClass to use StorableType with an auto-generated GUID (did not add StorableType to other type definitions yet)

File size: 5.2 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 System.Threading.Tasks;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Persistence;
28
29namespace HeuristicLab.Optimization {
30  [StorableType("56321a10-4f23-4ef8-88ce-35775f002e9a")]
31  public abstract class BasicAlgorithm : Algorithm, IStorableContent {
32
33    private bool pausePending;
34    private DateTime lastUpdateTime;
35
36    public string Filename { get; set; }
37
38    public abstract bool SupportsPause { get; }
39
40    [Storable]
41    private bool initialized;
42    [Storable]
43    private readonly ResultCollection results;
44    public override ResultCollection Results {
45      get { return results; }
46    }
47
48    private CancellationTokenSource cancellationTokenSource;
49    protected CancellationTokenSource CancellationTokenSource {
50      get { return cancellationTokenSource; }
51      private set { cancellationTokenSource = value; }
52    }
53
54    [StorableConstructor]
55    protected BasicAlgorithm(bool deserializing) : base(deserializing) { }
56    protected BasicAlgorithm(BasicAlgorithm original, Cloner cloner)
57      : base(original, cloner) {
58      results = cloner.Clone(original.Results);
59    }
60    protected BasicAlgorithm()
61      : base() {
62      results = new ResultCollection();
63    }
64
65    public override void Prepare() {
66      if (Problem == null) return;
67      base.Prepare();
68      results.Clear();
69      initialized = false;
70      OnPrepared();
71    }
72
73    public override void Start() {
74      base.Start();
75      CancellationTokenSource = new CancellationTokenSource();
76      pausePending = false;
77      OnStarted();
78
79      Task task = Task.Factory.StartNew(Run, CancellationTokenSource.Token, CancellationTokenSource.Token);
80      task.ContinueWith(t => {
81        try {
82          t.Wait();
83        } catch (AggregateException ex) {
84          try {
85            ex.Flatten().Handle(x => x is OperationCanceledException);
86          } catch (AggregateException remaining) {
87            if (remaining.InnerExceptions.Count == 1) OnExceptionOccurred(remaining.InnerExceptions[0]);
88            else OnExceptionOccurred(remaining);
89          }
90        }
91        CancellationTokenSource.Dispose();
92        CancellationTokenSource = null;
93        if (pausePending) OnPaused();
94        else OnStopped();
95      });
96    }
97
98    public override void Pause() {
99      // CancellationToken.ThrowIfCancellationRequested() must be called from within the Run method, otherwise pause does nothing
100      // alternatively check the IsCancellationRequested property of the cancellation token
101      if (!SupportsPause)
102        throw new NotSupportedException("Pause is not supported by this algorithm.");
103
104      base.Pause();
105      pausePending = true;
106      CancellationTokenSource.Cancel();
107    }
108
109    public override void Stop() {
110      // CancellationToken.ThrowIfCancellationRequested() must be called from within the Run method, otherwise stop does nothing
111      // alternatively check the IsCancellationRequested property of the cancellation token
112      base.Stop();
113      if (ExecutionState == ExecutionState.Paused) OnStopped();
114      else CancellationTokenSource.Cancel();
115    }
116
117    private void Run(object state) {
118      CancellationToken cancellationToken = (CancellationToken)state;
119      lastUpdateTime = DateTime.UtcNow;
120      System.Timers.Timer timer = new System.Timers.Timer(250);
121      timer.AutoReset = true;
122      timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
123      timer.Start();
124      try {
125        if (!initialized)
126          Initialize(cancellationToken);
127        initialized = true;
128        Run(cancellationToken);
129      } finally {
130        timer.Elapsed -= new System.Timers.ElapsedEventHandler(timer_Elapsed);
131        timer.Stop();
132        ExecutionTime += DateTime.UtcNow - lastUpdateTime;
133      }
134    }
135
136    protected virtual void Initialize(CancellationToken cancellationToken) { }
137    protected abstract void Run(CancellationToken cancellationToken);
138
139    #region Events
140    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
141      System.Timers.Timer timer = (System.Timers.Timer)sender;
142      timer.Enabled = false;
143      DateTime now = DateTime.UtcNow;
144      ExecutionTime += now - lastUpdateTime;
145      lastUpdateTime = now;
146      timer.Enabled = true;
147    }
148    #endregion
149
150  }
151}
Note: See TracBrowser for help on using the repository browser.