├── LICENSE ├── README.md ├── assets ├── cellvolution4.gif └── readme.md ├── make-video.py └── simulation.py /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cellvolution 2 | 3 | Evolutionary simulation of competing cell races (colored cells) on a grid of resources (visualized black to white). 4 | 5 | Cells move, consume resources, replicate, and evolve. Visualized in real-time. 6 | 7 | Can also save frames from the simulation. 8 | 9 | ![Alt text](https://github.com/Sentdex/cellvolution/blob/main/assets/cellvolution4.gif) 10 | 11 | 12 | -------------------------------------------------------------------------------- /assets/cellvolution4.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Sentdex/cellvolution/cf6fcb042abb48b4a26177960bbfe9b4ea10e0d7/assets/cellvolution4.gif -------------------------------------------------------------------------------- /assets/readme.md: -------------------------------------------------------------------------------- 1 | . 2 | -------------------------------------------------------------------------------- /make-video.py: -------------------------------------------------------------------------------- 1 | import os 2 | import subprocess 3 | 4 | def create_video_ffmpeg(input_folder, output_file, fps=30, crf=23): 5 | # Ensure the input folder exists 6 | if not os.path.exists(input_folder): 7 | raise ValueError(f"Input folder does not exist: {input_folder}") 8 | 9 | # Construct the FFmpeg command 10 | ffmpeg_cmd = [ 11 | 'ffmpeg', 12 | '-framerate', str(fps), 13 | '-pattern_type', 'glob', 14 | '-i', f'{input_folder}/*.png', 15 | '-c:v', 'libx264', 16 | '-preset', 'slow', 17 | '-crf', str(crf), 18 | '-pix_fmt', 'yuv420p', 19 | output_file 20 | ] 21 | 22 | # Run the FFmpeg command 23 | try: 24 | subprocess.run(ffmpeg_cmd, check=True) 25 | print(f"Video created successfully: {output_file}") 26 | except subprocess.CalledProcessError as e: 27 | print(f"Error creating video: {e}") 28 | 29 | 30 | simulation = "1719264027" 31 | 32 | simulation_dir = f"simulations/{simulation}" 33 | output_video_dir = "simvids" 34 | os.makedirs(output_video_dir, exist_ok=True) 35 | 36 | output_video = f"{output_video_dir}/{simulation}.mp4" 37 | create_video_ffmpeg(simulation_dir, output_video, fps=60, crf=23) 38 | -------------------------------------------------------------------------------- /simulation.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | import torch.nn as nn 4 | import random 5 | import matplotlib.pyplot as plt 6 | from matplotlib.colors import ListedColormap, LinearSegmentedColormap 7 | from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas 8 | import os 9 | import time 10 | 11 | 12 | 13 | SAVE_FRAMES = False # Will save frames at the expense of considerable simulation speed. 14 | 15 | class Cell(nn.Module): 16 | def __init__(self, input_size, hidden_size, output_size): 17 | super(Cell, self).__init__() 18 | self.network = nn.Sequential( 19 | nn.Linear(input_size, hidden_size), 20 | nn.ReLU(), 21 | nn.Linear(hidden_size, output_size) 22 | ) 23 | self.energy = 100 24 | 25 | def forward(self, x): 26 | return self.network(x) 27 | 28 | class Simulation: 29 | def __init__(self, width, height, n_races, initial_density=0.3): 30 | self.width = width 31 | self.height = height 32 | self.n_races = n_races 33 | self.grid = np.full((height, width), -1, dtype=int) # Initialize all cells as empty (-1) 34 | self.cells = [[None for _ in range(width)] for _ in range(height)] 35 | self.resources = self.initialize_resources() 36 | self.step_count = 0 37 | self.replication_threshold = 150 38 | self.mutation_rate = 0.1 39 | self.collision_stats = {i: {'wins': 0, 'losses': 0} for i in range(n_races)} 40 | self.collision_stats[-1] = {'wins': 0, 'losses': 0} # Add stats for empty/dead cells 41 | self.all_cells_dead = False 42 | 43 | # Initialize cells based on initial_density 44 | total_cells = int(width * height * initial_density) 45 | cells_per_race = total_cells // n_races 46 | remaining_cells = total_cells % n_races 47 | 48 | for race in range(n_races): 49 | for _ in range(cells_per_race + (1 if race < remaining_cells else 0)): 50 | while True: 51 | x, y = random.randint(0, width-1), random.randint(0, height-1) 52 | if self.grid[y][x] == -1: # If the spot is empty 53 | self.grid[y][x] = race 54 | self.cells[y][x] = Cell(75, 30, 5) 55 | break 56 | 57 | initial_counts = [np.sum(self.grid == i) for i in range(self.n_races)] 58 | print("Initial cell counts for each race:", initial_counts) 59 | 60 | 61 | 62 | def initialize_resources(self): 63 | resources = np.zeros((self.height, self.width)) 64 | num_patches = (self.height * self.width) // 100 # Create resource patches in about 1% of the grid 65 | for _ in range(num_patches): 66 | x, y = random.randint(0, self.width-1), random.randint(0, self.height-1) 67 | resources[y, x] = random.randint(50, 100) # Resource-rich patches 68 | return resources 69 | 70 | def step(self): 71 | new_grid = self.grid.copy() 72 | for y in range(self.height): 73 | for x in range(self.width): 74 | if self.grid[y, x] == -1: # Skip dead cells 75 | continue 76 | 77 | cell = self.cells[y][x] 78 | if cell is None or cell.energy <= 0: 79 | new_grid[y, x] = -1 # Dead cell 80 | self.cells[y][x] = None 81 | continue 82 | 83 | neighborhood = self.get_neighborhood(x, y) 84 | action_probs = torch.softmax(cell(torch.FloatTensor(neighborhood).unsqueeze(0)).squeeze(0), dim=0) 85 | action = torch.multinomial(action_probs, 1).item() 86 | 87 | cell.energy -= 1 # Energy cost for existing 88 | 89 | new_x, new_y = x, y 90 | if action == 0: # Move up 91 | new_y = (y - 1) % self.height 92 | elif action == 1: # Move right 93 | new_x = (x + 1) % self.width 94 | elif action == 2: # Move down 95 | new_y = (y + 1) % self.height 96 | elif action == 3: # Move left 97 | new_x = (x - 1) % self.width 98 | elif action == 4: # Stay and consume 99 | consumed = min(self.resources[y, x], 10) 100 | cell.energy += consumed 101 | self.resources[y, x] -= consumed 102 | 103 | if cell.energy >= self.replication_threshold: 104 | self.replicate(cell, new_grid, x, y) 105 | 106 | if new_grid[new_y, new_x] == -1: # Empty space 107 | new_grid[new_y, new_x] = self.grid[y, x] 108 | self.cells[new_y][new_x] = cell 109 | new_grid[y, x] = -1 110 | self.cells[y][x] = None 111 | self.collision_stats[self.grid[y, x]]['wins'] += 1 112 | self.collision_stats[-1]['losses'] += 1 113 | elif new_grid[new_y, new_x] != self.grid[y, x]: # Different race collision 114 | other_cell = self.cells[new_y][new_x] 115 | if other_cell is None or cell.energy > other_cell.energy: 116 | # Current cell wins 117 | cell.energy -= other_cell.energy if other_cell else 0 118 | new_grid[new_y, new_x] = self.grid[y, x] 119 | self.cells[new_y][new_x] = cell 120 | new_grid[y, x] = -1 121 | self.cells[y][x] = None 122 | self.collision_stats[self.grid[y, x]]['wins'] += 1 123 | self.collision_stats[new_grid[new_y, new_x]]['losses'] += 1 124 | else: 125 | other_cell.energy -= cell.energy 126 | new_grid[y, x] = -1 127 | self.cells[y][x] = None 128 | self.collision_stats[self.grid[y, x]]['losses'] += 1 129 | self.collision_stats[new_grid[new_y, new_x]]['wins'] += 1 130 | self.grid = new_grid 131 | 132 | # Slow resource regeneration 133 | self.resources += np.random.random(self.resources.shape) < 0.05 # 0.1% chance of adding 1 resource 134 | 135 | self.step_count += 1 136 | if self.step_count % 100 == 0: 137 | print(f"Step {self.step_count}: Active cells: {np.sum(self.grid != -1)}") 138 | print("Collision stats:", self.collision_stats) 139 | 140 | def get_neighborhood(self, x, y): 141 | neighborhood = [] 142 | for i in range(-2, 3): 143 | for j in range(-2, 3): 144 | nx, ny = (x + i) % self.width, (y + j) % self.height 145 | cell_type = self.grid[ny, nx] 146 | cell_energy = self.cells[ny][nx].energy if self.cells[ny][nx] is not None else 0 147 | resource = self.resources[ny, nx] 148 | neighborhood.extend([cell_type, cell_energy, resource]) 149 | return neighborhood 150 | 151 | def replicate(self, parent_cell, new_grid, x, y): 152 | neighbors = [(x, (y-1) % self.height), ((x+1) % self.width, y), 153 | (x, (y+1) % self.height), ((x-1) % self.width, y)] 154 | empty_neighbors = [pos for pos in neighbors if new_grid[pos[1]][pos[0]] == -1] 155 | 156 | if empty_neighbors: 157 | new_x, new_y = random.choice(empty_neighbors) 158 | 159 | new_cell = Cell(75, 30, 5) # Match the new input size 160 | new_cell.load_state_dict(parent_cell.state_dict()) 161 | 162 | if random.random() < self.mutation_rate: 163 | with torch.no_grad(): 164 | for param in new_cell.parameters(): 165 | param.add_(torch.randn(param.size()) * 0.1) 166 | 167 | new_cell.energy = parent_cell.energy // 2 168 | parent_cell.energy = parent_cell.energy // 2 169 | 170 | new_grid[new_y][new_x] = new_grid[y][x] # Same race as parent 171 | self.cells[new_y][new_x] = new_cell 172 | 173 | def evolve(self): 174 | performances = np.zeros((self.height, self.width)) 175 | for y in range(self.height): 176 | for x in range(self.width): 177 | if self.grid[y, x] != -1 and self.cells[y][x] is not None: 178 | performances[y, x] = self.cells[y][x].energy 179 | 180 | worst_indices = np.argsort(performances.flatten())[:100] 181 | best_indices = np.argsort(performances.flatten())[-100:] 182 | 183 | for worst, best in zip(worst_indices, best_indices): 184 | wy, wx = np.unravel_index(worst, performances.shape) 185 | by, bx = np.unravel_index(best, performances.shape) 186 | 187 | if self.grid[wy][wx] != -1 and self.grid[by][bx] != -1 and self.cells[wy][wx] is not None and self.cells[by][bx] is not None: 188 | self.cells[wy][wx].load_state_dict(self.cells[by][bx].state_dict()) 189 | with torch.no_grad(): 190 | for param in self.cells[wy][wx].parameters(): 191 | param.add_(torch.randn(param.size()) * 0.1) 192 | self.cells[wy][wx].energy = 100 # Reset energy for new cell 193 | 194 | print(f"Evolution performed at step {self.step_count}") 195 | 196 | 197 | class Visualization: 198 | def __init__(self, simulation): 199 | self.simulation = simulation 200 | plt.ion() # Turn on interactive mode 201 | plt.style.use('dark_background') 202 | self.fig = plt.figure(figsize=(14, 14)) # Square figure 203 | 204 | # Modify the gridspec to allocate 80% height to the top graph 205 | self.gs = self.fig.add_gridspec(5, 1) # 5 rows, 1 column 206 | self.ax1 = self.fig.add_subplot(self.gs[:4, 0]) # Top 4 rows (80%) 207 | self.ax2 = self.fig.add_subplot(self.gs[4, 0]) # Bottom row (20%) 208 | 209 | self.population_history = [[] for _ in range(simulation.n_races)] 210 | self.steps = [] 211 | 212 | if SAVE_FRAMES: 213 | # Create directory for saving frames 214 | self.sim_dir = os.path.join("simulations", str(int(time.time()))) 215 | os.makedirs(self.sim_dir, exist_ok=True) 216 | 217 | self.frame_count = 0 218 | 219 | self.setup_plot() 220 | 221 | def setup_plot(self): 222 | self.ax1.set_title("Cells and Resources") 223 | self.ax2.set_title("Population by Race Over Time") 224 | 225 | # Define less bright colors for races 226 | self.race_colors = ['#8B0000', '#006400', '#00008B', '#8B8B00', '#8B008B'] # Dark Red, Dark Green, Dark Blue, Dark Yellow, Dark Magenta 227 | if self.simulation.n_races > len(self.race_colors): 228 | self.race_colors.extend(['#' + ''.join([random.choice('456789ABCD') for _ in range(6)]) 229 | for _ in range(self.simulation.n_races - len(self.race_colors))]) 230 | 231 | # Create custom colormap for races 232 | race_cmap = ListedColormap(['#1A1A1A'] + self.race_colors) # Dark gray for empty/dead cells 233 | 234 | # Create custom colormap for resources (black to white) 235 | resource_cmap = LinearSegmentedColormap.from_list("resource_cmap", ['#000000', '#FFFFFF']) 236 | 237 | # Create the main plot 238 | self.im1 = self.ax1.imshow(self.simulation.grid, cmap=race_cmap, vmin=-1, vmax=self.simulation.n_races-1, interpolation='nearest') 239 | 240 | # Create a semi-transparent overlay for resources 241 | self.resource_overlay = self.ax1.imshow(self.simulation.resources, cmap=resource_cmap, alpha=0.5, vmin=0, vmax=100, interpolation='nearest') 242 | 243 | # Setup line graph for population over time 244 | self.lines = [self.ax2.plot([], [], color=color, label=f'Race {i}')[0] 245 | for i, color in enumerate(self.race_colors)] 246 | self.ax2.set_xlabel('Steps') 247 | self.ax2.set_ylabel('Population') 248 | self.legend = self.ax2.legend(loc='upper left', fontsize='small') 249 | 250 | # Set background color for both subplots 251 | self.ax1.set_facecolor('#1A1A1A') 252 | self.ax2.set_facecolor('#1A1A1A') 253 | 254 | # Remove x-axis labels from the top plot to save space 255 | self.ax1.set_xticks([]) 256 | self.ax1.set_yticks([]) 257 | 258 | self.fig.tight_layout() 259 | 260 | def update(self): 261 | self.im1.set_data(self.simulation.grid) 262 | self.resource_overlay.set_data(self.simulation.resources) 263 | 264 | # Update population line graph 265 | populations = [np.sum(self.simulation.grid == i) for i in range(self.simulation.n_races)] 266 | self.steps.append(self.simulation.step_count) 267 | for i, pop in enumerate(populations): 268 | self.population_history[i].append(pop) 269 | 270 | for line, pop_history, pop in zip(self.lines, self.population_history, populations): 271 | line.set_data(self.steps, pop_history) 272 | line.set_label(f'Race {line.get_label().split()[1]} ({pop} alive)') 273 | 274 | self.ax2.relim() 275 | self.ax2.autoscale_view() 276 | 277 | # Update the legend with current population counts 278 | self.legend.remove() 279 | self.legend = self.ax2.legend(loc='upper left') 280 | 281 | self.fig.canvas.draw() 282 | self.fig.canvas.flush_events() # Refresh the plot 283 | 284 | if SAVE_FRAMES: 285 | self.save_frame() 286 | 287 | def save_frame(self): 288 | self.frame_count += 1 289 | filename = os.path.join(self.sim_dir, f"{self.frame_count:06d}.png") 290 | self.fig.savefig(filename) 291 | 292 | def run(self): 293 | while True: 294 | try: 295 | self.simulation.step() 296 | if random.random() < 0.3: # Evolve occasionally 297 | self.simulation.evolve() 298 | self.update() 299 | 300 | # Check if all cells are dead 301 | if np.all(self.simulation.grid == -1): 302 | print("All cells have died. Simulation ending.") 303 | break 304 | 305 | except KeyboardInterrupt: 306 | print("Simulation stopped by user.") 307 | break 308 | 309 | # Keep the plot window open after simulation ends 310 | plt.ioff() 311 | plt.show() 312 | 313 | 314 | #sim = Simulation(800, 600, 10, initial_density=0.05) # for the very patient among us. 315 | sim = Simulation(40, 30, 5, initial_density=0.1) # for the rest of you 316 | vis = Visualization(sim) 317 | vis.run() 318 | --------------------------------------------------------------------------------