72 lines
2.3 KiB
Python
72 lines
2.3 KiB
Python
"""
|
|
Contains functions for parsing a file containing a bushfire scenario.
|
|
"""
|
|
|
|
def make_grid(grid: list[str], format_tuples: bool=False) -> list[list[int]]:
|
|
"""Makes a valid grid from the input.
|
|
|
|
### Parameters:
|
|
grid (list): Either a fuel load or height grid.
|
|
format_tuples (bool): To format the elements as tuples. Defaults to
|
|
False, meaning that the elements of the grid will be lists.
|
|
|
|
### Returns:
|
|
new_grid (list): The correctly formatted grid.
|
|
|
|
### Example:
|
|
>>> make_grid(['2,2', '0,2'])
|
|
[[2, 2], [0, 2]]
|
|
"""
|
|
|
|
new_grid = []
|
|
for row in grid:
|
|
cells = row.split(',')
|
|
new_row = [int(i.strip()) for i in cells]
|
|
if format_tuples:
|
|
new_grid.append(tuple(new_row))
|
|
else:
|
|
new_grid.append(new_row)
|
|
return new_grid
|
|
|
|
def parse_scenario(path: str) -> dict | None:
|
|
"""Parses a bushfire scenario file.
|
|
|
|
### Parameters:
|
|
path (str): The path to the bushfire scenario file.
|
|
|
|
### Returns:
|
|
scanario (dict): The dictionary containing information describing the
|
|
bushfire scenario. Returns None if path was not valid or the file was
|
|
not formatted correctly.
|
|
|
|
### Examples:
|
|
>>> parse_scenario('../data/bushfire-0.txt')
|
|
{'f_grid': [[2, 2], [0, 2]], 'h_grid': [[1, 2], [1, 2]], 'i_threshold': 1,
|
|
'w_direction': 'N', 'burn_seeds': [(0, 0)]}
|
|
|
|
>>> parse_scenario('data/bushfire-1.txt')
|
|
{'f_grid': [[1, 2, 1], [0, 1, 2], [0, 0, 1]],
|
|
'h_grid': [[1, 1, 1], [2, 1, 2], [3, 2, 2]], 'i_threshold': 1,
|
|
'w_direction': 'N', 'burn_seeds': [(1, 1)]}
|
|
"""
|
|
|
|
lines = []
|
|
with open(path, 'r', encoding='utf-8') as file:
|
|
lines = [line[:-1] for line in file]
|
|
|
|
if lines == []:
|
|
return None
|
|
|
|
size = int(lines[0])
|
|
f_grid = make_grid(lines[1 : 1 + size])
|
|
h_grid = make_grid(lines[1 + size : 1 + size * 2])
|
|
i_threshold = int(lines[1 + size * 2])
|
|
w_direction = None if lines[2 + size * 2] == 'None' else lines[2 + size * 2]
|
|
burn_seeds = make_grid(lines[3 + size * 2:], format_tuples=True)
|
|
|
|
return {'f_grid': f_grid, 'h_grid': h_grid, 'i_threshold': i_threshold,
|
|
'w_direction': w_direction, 'burn_seeds': burn_seeds}
|
|
|
|
print(parse_scenario('data/bushfire-0.txt'))
|
|
print()
|
|
print(parse_scenario('data/bushfire-1.txt'))
|