comp10001-project02/part3.py

93 lines
3.4 KiB
Python
Raw Normal View History

# Title: Project 2 - Run the model
# Author: Rory Healy
# Date created - 9th May 2019
# Create global variables to be accessed in multiple functions.
times_iterated = 0
current_state = []
previous_state = []
b_grid_initial = []
def create_b_grid(f_grid, burn_seeds):
'''Creates a matrix of size M, b_grid, which indicates whether a cell is
currently burning or not.'''
b_grid = []
for row in range(len(f_grid)):
b_grid.append([])
for column in range(len(f_grid)):
b_grid[row].append([])
for cell in burn_seeds:
for row in range(len(b_grid)):
for column in range(len(b_grid)):
if (row, column) == cell:
b_grid[row].remove([])
b_grid[row].append(True)
else:
b_grid[row].remove([])
b_grid[row].append(False)
return b_grid
def iterate_time(f_grid, h_grid, i_threshold, w_direction, b_grid):
'''Takes the conditions of the current state and iterates the grid so that
exactly 1 unit of time passes. Returns a list of the updated f_grid and
burn_seeds.'''
global current_state
# Creates a new b_grid and f_grid to be returned. Updates b_grid_new and
# f_grid_new to match the changes in the next timestep.
b_grid_new = b_grid
f_grid_new = f_grid
for cell in f_grid:
i = cell[0]
j = cell[1]
if check_ignition(b_grid, f_grid, h_grid, i_threshold, w_direction, i,
j) is True:
f_grid_new[cell] -= 1
for row in b_grid_new:
for column in b_grid_new:
b_grid_new[row][column] = True
current_state = [f_grid_new, b_grid_new]
return current_state
def run_model(f_grid, h_grid, i_threshold, w_direction, burn_seeds):
'''Takes the initial conditions as given above and returns a tuple
containing the final state of the grid once the fire has gone out, and the
total number of cells that were burned.'''
global times_iterated
global current_state
global previous_state
global b_grid_initial
# Calls iterate_time for the first time in order to generate a new value
# for current_state to be compared to the previous state.
if times_iterated == 0:
b_grid = create_b_grid(f_grid, burn_seeds)
b_grid_initial = create_b_grid(f_grid, burn_seeds)
current_state = [f_grid, b_grid]
times_iterated = 1
previous_state = current_state
current_state = iterate_time(f_grid, h_grid, i_threshold, w_direction,
b_grid)
# Either returns the final state and total burned cells, or continues to
# the next timestep and calls run_model again, repeating until the states
# aren't changing anymore.
elif current_state == previous_state:
total_burned_cells = len(burn_seeds)
for row in b_grid_initial:
for cell in b_grid_initial:
if cell == b_grid[row][cell]:
total_burned_cells += 1
return (current_state, total_burned_cells)
else:
times_iterated += 1
previous_state = current_state
current_state = iterate_time(f_grid, h_grid, i_threshold, w_direction,
b_grid)
run_model(f_grid, h_grid, i_threshold, w_direction, burn_seeds)