# Title: Project 2 - Parse a bushfire scenario file # Author: Rory Healy # Date created - 8th May 2019 # Date modified - 9th May 2019 def strlist_to_listlist(grid): '''Converts a list of strings into a list of lists.''' for i in range(len(grid)): line_to_append = [] for j in range(len(grid[i])): current_coordinate = grid[i][j] if current_coordinate not in ",": line_to_append.append(int(grid[i][j])) grid[i] = line_to_append return grid def parse_scenario(filename): '''Parses a file with the structure described, validates the contents and returns a dictionary containing all values that are required to model a scenario, or None if any of the contents are invalid.''' structure_dict = {} # Converts the file to a list of strings. structure = open(filename, "r") all_lines = [] for line in structure.readlines(): line = line[:-1] all_lines.append(line) # Finds the length of the matrix and splits the data up acccordingly. # e.g. a M*M matrix will store f_grid and h_grid as a list of M lists. # This is used to return the f_grid and h_grid in the correct format. matrix_size = int(all_lines[0]) if matrix_size <= 0: return None f_grid = [] h_grid = [] for i in range(1, matrix_size + 1): f_grid.append(all_lines[i]) for i in range(matrix_size + 1, matrix_size * 2 + 1): h_grid.append(all_lines[i]) strlist_to_listlist(f_grid) strlist_to_listlist(h_grid) # Remove matrix_size, f_grid and h_grid from all_lines and define # i_threshold, w_direction and burn_seeds so that they can be added to # structure_dict. all_lines = all_lines[((matrix_size * 2) + 1):] i_threshold = int(all_lines[0]) w_direction = '' + all_lines[1] if all_lines[2]: burn_seeds = [] burn_seeds.append(all_lines[2]) burn_seeds = [(int(burn_seeds[0][0]), int(burn_seeds[0][-1]))] # Checks if the values are valid. if i_threshold > 8 or i_threshold < 0: return None for i in range(len(burn_seeds)): current_seeds = list(burn_seeds[i]) for j in range(len(current_seeds)): if current_seeds[j] > matrix_size: return None # Fills in structure_dict with the keys and associated values. all_dict_keys = ['f_grid', 'h_grid', 'i_threshold', 'w_direction', 'burn_seeds'] all_dict_values = [f_grid, h_grid, i_threshold, w_direction, burn_seeds] for i in range(len(all_dict_values)): structure_dict[all_dict_keys[i]] = all_dict_values[i] structure.close() return structure_dict