Free cookie consent management tool by TermsFeed Policy Generator

source: branches/SimulationCore/HeuristicLab.SimulationCore.Samples/3.3/GameOfLifeSimulation.cs @ 6739

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

Added game of life simulation sample (#1610)

File size: 6.8 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.Persistence.Default.CompositeSerializers.Storable;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Parameters;
30using HeuristicLab.Data;
31using HeuristicLab.Optimization;
32using System.Threading;
33using HeuristicLab.SimulationCore.AgentBased;
34using HeuristicLab.Analysis;
35
36namespace HeuristicLab.SimulationCore.Samples {
37  [Item("GameOfLifeSimulation", "A game of life simulation.")]
38  [Creatable("Simulations")]
39  [StorableClass]
40  public sealed class GameOfLifeSimulation: AgentBasedSimulation {
41    public override Type ProblemType {
42      get { return typeof(GameOfLifeScenario); }
43    }
44
45    private GameOfLifeScenario Scenario {
46      get {
47        return Problem as GameOfLifeScenario;
48      }
49    }
50   
51    public ValueParameter<IntValue> IterationsParameter {
52      get { return (ValueParameter<IntValue>)Parameters["Iterations"]; }
53    }
54   
55    public GameOfLifeSimulation() : base() {
56      Parameters.Add(new ValueParameter<IntValue>("Iterations", "The number of iterations.", new IntValue(100)));
57
58      Initialize();
59    }
60    [StorableConstructor]
61    private GameOfLifeSimulation(bool deserializing) : base(deserializing) { }
62    [StorableHook(HookType.AfterDeserialization)]
63    private void AfterDeserialization() {
64      Initialize();
65    }
66    private GameOfLifeSimulation(GameOfLifeSimulation original, Cloner cloner)
67      : base(original, cloner) {
68      Initialize();
69    }
70    public override IDeepCloneable Clone(Cloner cloner) {
71      return new GameOfLifeSimulation(this, cloner);
72    }
73
74    private GameOfLifeAgent GetAgent(int x, int y) {     
75      int width = Scenario.WidthParameter.Value.Value;
76      int height = Scenario.HeightParameter.Value.Value;
77
78      if (x >= width || y >= height)
79        throw new Exception("invalid index");
80
81      int index = x + y * width; 
82
83      return Agents[index] as GameOfLifeAgent;
84    }
85
86    private void Initialize() {
87      if (Scenario != null) {
88        Scenario.WidthParameter.ValueChanged += new EventHandler(WidthParameter_ValueChanged);
89        if(Scenario.WidthParameter.Value != null)
90          Scenario.WidthParameter.Value.ValueChanged += new EventHandler(Width_ValueChanged);
91        Scenario.HeightParameter.ValueChanged += new EventHandler(HeightParameter_ValueChanged);
92        if (Scenario.HeightParameter.Value != null)
93          Scenario.HeightParameter.Value.ValueChanged += new EventHandler(Height_ValueChanged);
94      }
95    }
96
97    void Width_ValueChanged(object sender, EventArgs e) {
98      CreateAgents();
99    }
100
101    void Height_ValueChanged(object sender, EventArgs e) {
102      CreateAgents();
103    }
104
105    void HeightParameter_ValueChanged(object sender, EventArgs e) {
106      CreateAgents();
107    }
108
109    void WidthParameter_ValueChanged(object sender, EventArgs e) {
110      CreateAgents();
111    }
112
113    public IEnumerable<GameOfLifeAgent> GetNeighbors(GameOfLifeAgent agent) {
114      int width = Scenario.WidthParameter.Value.Value;
115      int height = Scenario.HeightParameter.Value.Value;
116      int index = Agents.IndexOf(agent);
117     
118      List<GameOfLifeAgent> result = new List<GameOfLifeAgent>();
119
120      int y = index / width;
121      int x = index - (y * width);
122
123      for (int x1 = x - 1; x1 <= x + 1; x1++) {
124        for (int y1 = y - 1; y1 <= y + 1; y1++) {
125          if (x1 >= 0 && y1 >= 0 && x1 < width && y1 < height &&
126            (x1 != x || y1 != y)) {
127            GameOfLifeAgent neighbor = GetAgent(x1, y1);
128            result.Add(neighbor);
129          }
130        }
131      }
132
133      return result;
134    }
135
136    private void CreateAgents() {
137      Agents.Clear();
138      int width = Scenario.WidthParameter.Value.Value;
139      int height = Scenario.HeightParameter.Value.Value;
140
141      for (int i = 0; i < width * height; i++) {
142        Agents.Add(new GameOfLifeAgent(this));
143      }
144
145      InitAgents();
146    }
147
148    protected override void OnProblemChanged() {
149      base.OnProblemChanged();
150
151      Initialize();
152
153      CreateAgents();
154    }
155
156    private void InitAgents() {
157      double rate = Scenario.AliveRateParameter.Value.Value;
158      int width = Scenario.WidthParameter.Value.Value;
159      int height = Scenario.HeightParameter.Value.Value;
160
161      Random rand = new Random();
162
163      for (int i = 0; i < width * height; i++) {
164        GameOfLifeAgent agent = Agents[i] as GameOfLifeAgent;
165        agent.Alive = rand.NextDouble() < rate;
166      }
167    }
168
169    protected override void OnPrepared() {
170      base.OnPrepared();
171
172      InitAgents();
173    }
174
175    private void UpdateResults() {
176      int width = Scenario.WidthParameter.Value.Value;
177      int height = Scenario.HeightParameter.Value.Value;
178
179      HeatMap cells = new HeatMap(width, height);
180
181      for (int i = 0; i < width * height; i++) {
182        int y = i / width;
183        int x = i - (y * width);
184
185        if (GetAgent(x, y).Alive)
186          cells[x, y] = 1;
187        else
188          cells[x, y] = 0;
189      }
190
191      Results["Cells"].Value = cells;
192     
193      IntValue currentIterations = (Results["CurrentIterations"].Value as IntValue);
194      currentIterations.Value++;
195    }
196
197    protected override void Run(CancellationToken cancellationToken) {
198      int iterations = IterationsParameter.Value.Value;
199      int width = Scenario.WidthParameter.Value.Value;
200      int height = Scenario.HeightParameter.Value.Value;
201
202      int start = 0;
203      if (Results.ContainsKey("CurrentIterations")) {
204        start = (Results["CurrentIterations"].Value as IntValue).Value;
205      } else {
206        Results.Add(new Result("CurrentIterations", new IntValue(0)));
207        Results.Add(new Result("Cells", new HeatMap(width, height)));
208      }     
209
210      for (int i = start; i < iterations; i++) {
211        cancellationToken.ThrowIfCancellationRequested();
212       
213        base.Step();
214        UpdateResults();       
215
216        Thread.Sleep(250);
217      }
218    }
219  }
220}
Note: See TracBrowser for help on using the repository browser.