Free cookie consent management tool by TermsFeed Policy Generator

source: branches/SimulationCore/HeuristicLab.SimulationCore/3.3/Simulation.cs @ 6623

Last change on this file since 6623 was 6623, checked in by svonolfe, 13 years ago

Added game of life simulation sample (#1610)

File size: 5.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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.Linq;
25using System.Text;
26using HeuristicLab.Core;
27using System.Drawing;
28using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
29using HeuristicLab.Common;
30using HeuristicLab.Collections;
31using HeuristicLab.Optimization;
32using System.Threading;
33using System.Threading.Tasks;
34
35namespace HeuristicLab.SimulationCore {
36  [Item("Simulation", "A base class for simulations.")]
37  [StorableClass]
38  public abstract class Simulation: Algorithm, ISimulation, IStorableContent {
39    public string Filename { get; set; }
40       
41    public override Type ProblemType {
42      get { return typeof(IScenario); }
43    }
44
45    [Storable]
46    private ResultCollection results;
47    public override ResultCollection Results {
48      get {
49        return results;
50      }
51    }
52
53    #region Variables for communication between threads
54    private CancellationTokenSource cancellationTokenSource;
55    private bool stopPending;
56    private DateTime lastUpdateTime;
57    #endregion
58
59    [StorableConstructor]
60    protected Simulation(bool deserializing) : base(deserializing) { }
61    protected Simulation()
62      : base() {
63        results = new ResultCollection();
64    }
65    protected Simulation(Simulation original, Cloner cloner)
66      : base(original, cloner) {
67        results = cloner.Clone(original.results) as ResultCollection;
68    }
69
70    public sealed override void Prepare() {
71      base.Prepare();
72      results.Clear();
73      OnPrepared();
74    }
75    protected override void OnPrepared() {
76      base.OnPrepared();
77    }
78
79    public override void Start() {
80      base.Start();
81      cancellationTokenSource = new CancellationTokenSource();
82      stopPending = false;
83      Task task = Task.Factory.StartNew(Run, cancellationTokenSource.Token, cancellationTokenSource.Token);
84      task.ContinueWith(t => {
85        try {
86          t.Wait();
87        }
88        catch (AggregateException ex) {
89          try {
90            ex.Flatten().Handle(x => x is OperationCanceledException);
91          }
92          catch (AggregateException remaining) {
93            if (remaining.InnerExceptions.Count == 1) OnExceptionOccurred(remaining.InnerExceptions[0]);
94            else OnExceptionOccurred(remaining);
95          }
96        }
97        cancellationTokenSource.Dispose();
98        cancellationTokenSource = null;
99        if (stopPending) OnStopped();
100        else OnPaused();
101      });
102    }
103    protected override void OnStarted() {
104      base.OnStarted();
105    }
106
107    public override void Pause() {
108      base.Pause();
109      cancellationTokenSource.Cancel();
110    }
111    protected override void OnPaused() {
112      base.OnPaused();
113    }
114
115    public override void Stop() {
116      base.Stop();
117      if (ExecutionState == ExecutionState.Paused) {
118        OnStopped();
119      } else {
120        stopPending = true;
121        cancellationTokenSource.Cancel();
122      }
123    }
124    protected override void OnStopped() {
125      base.OnStopped();
126    }
127
128    protected override void OnExceptionOccurred(Exception exception) {
129      base.OnExceptionOccurred(exception);
130    }
131
132    private void Run(object state) {
133      CancellationToken cancellationToken = (CancellationToken)state;
134
135      OnStarted();
136      lastUpdateTime = DateTime.Now;
137      System.Timers.Timer timer = new System.Timers.Timer(250);
138      timer.AutoReset = true;
139      timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
140      timer.Start();
141      try {
142        Run(cancellationToken);
143      }
144      finally {
145        timer.Elapsed -= new System.Timers.ElapsedEventHandler(timer_Elapsed);
146        timer.Stop();
147        ExecutionTime += DateTime.Now - lastUpdateTime;
148      }
149      Stop();
150
151      cancellationToken.ThrowIfCancellationRequested();
152    }
153    protected abstract void Run(CancellationToken cancellationToken);
154
155    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
156      System.Timers.Timer timer = (System.Timers.Timer)sender;
157      timer.Enabled = false;
158      DateTime now = DateTime.Now;
159      ExecutionTime += now - lastUpdateTime;
160      lastUpdateTime = now;
161      timer.Enabled = true;
162    }
163  }
164}
Note: See TracBrowser for help on using the repository browser.