1
0
Fork 0

Add parsing functionality

This commit is contained in:
Rory Healy 2023-02-05 21:42:13 +11:00
parent 2b115ce3e7
commit c7e7dc074a
Signed by: roryhealy
GPG Key ID: 610ED1098B8F435B
2 changed files with 74 additions and 2 deletions

View File

@ -125,11 +125,11 @@ If any values are invalid, your function should return `None`.
For example:
>>> parse_scenario('bushfire-0.txt')
>>> 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('bushfire-1.txt')
>>> 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)]}

72
src/parse.py Normal file
View File

@ -0,0 +1,72 @@
"""
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'))