neuropercolation/src/cellular_automaton/cellular_automaton.py

62 lines
1.9 KiB
Python
Raw Normal View History

2018-12-01 19:37:18 +00:00
from cellular_automaton.ca_grid import Grid
from cellular_automaton.ca_rule import Rule
2018-12-02 16:45:08 +00:00
from cellular_automaton.ca_neighborhood import Neighborhood
2018-12-01 14:14:22 +00:00
class CellularAutomaton:
2018-12-08 21:33:13 +00:00
def __init__(self, dimension: list, neighborhood: Neighborhood, evolution_rule: Rule=None):
2018-12-02 16:45:08 +00:00
self.grid = Grid(dimension, neighborhood)
2018-12-08 21:33:13 +00:00
self.evolution_rule = evolution_rule
self.iteration = 0
self.test_number = 0
2018-12-01 14:14:22 +00:00
2018-12-01 19:37:18 +00:00
def set_rule(self, rule: Rule):
2018-12-08 21:33:13 +00:00
""" Set new evolution rule.
:param rule:
:return:
"""
self.evolution_rule = rule
2018-12-01 19:37:18 +00:00
2018-12-02 16:45:08 +00:00
def get_iteration_index(self):
2018-12-08 21:33:13 +00:00
""" Get the count of evolution cycles done.
:return: Evolution steps done.
"""
return self.iteration
2018-12-02 16:45:08 +00:00
2018-12-08 21:33:13 +00:00
def evolve_x_times(self, evolutions: int):
""" Evolve all cells for x time steps.
:param evolutions: the count of evolutions done.
:return: True if all cells are inactive
"""
for evo in range(evolutions):
finished = self.evolve()
if finished:
return True
return False
2018-12-01 19:37:18 +00:00
def evolve(self):
""" Evolves all active cells for one time step.
:return: True if all cells are inactive.
"""
2018-12-08 21:33:13 +00:00
if self._is_evolution_finished():
2018-12-02 16:45:08 +00:00
return True
else:
self.iteration += 1
2018-12-08 21:33:13 +00:00
self._evolve_all_active_cells()
2018-12-02 16:45:08 +00:00
return False
2018-12-08 21:33:13 +00:00
def _evolve_all_active_cells(self):
2018-12-09 14:25:12 +00:00
active_cells = self.grid.get_active_cells()
2018-12-02 16:45:08 +00:00
self.grid.clear_active_cells()
2018-12-09 14:25:12 +00:00
self._evolve_cells(active_cells.values())
2018-12-08 21:33:13 +00:00
def _is_evolution_finished(self):
return len(self.grid.get_active_cell_names()) == 0
2018-12-09 14:25:12 +00:00
def _evolve_cells(self, cells: list):
for cell in cells:
2019-01-05 14:12:07 +00:00
active = self.evolution_rule.evolve_cell(cell, self.iteration)
2018-12-08 21:33:13 +00:00
if active:
2018-12-09 14:25:12 +00:00
self.grid.set_cells_active([cell] + cell.neighbours)