sierrapor / TFG

0 stars 1 forks source link

Avoid magic numbers #2

Closed jesusff closed 11 months ago

jesusff commented 11 months ago

These "magic numbers" in your code (e.g. 27) can be computed automatically:

https://github.com/sierrapor/TFG/blob/fbd3f173b1525f7c053c4a308249462cbe554572/VegeTables.ipynb#L796

The size of the tables is written in the tables themselves. A new table starts with a line containing only the string Vegetation Parameters. Then the next line contains the the name of the table, and the next one starts with the size. Try something like this:

with open('VEGPARM.TBL') as fp:
  table_as_list = fp.read().splitlines()

tables = {}
for i, line in enumerate(table_as_list):
  if line == 'Vegetation Parameters':
    table_name = table_as_list[i+1]
    table_size = int(table_as_list[i+2].split(',')[0])
    tables[table_name] = dict(size = table_size, start = i+2, end = i+2+table_size)

tables

The result is the info you need:

{'USGS': {'size': 27, 'start': 2, 'end': 29},
 'MODIFIED_IGBP_MODIS_NOAH': {'size': 20, 'start': 68, 'end': 88},
 'NLCD40': {'size': 40, 'start': 127, 'end': 167},
 'USGS-RUC': {'size': 28, 'start': 206, 'end': 234},
 'MODI-RUC': {'size': 21, 'start': 253, 'end': 274}}

Try to write a function that can be called like this as an example in your notebook:

df = read_wrf_vegparm('VEGPARM.TBL', 'MODIFIED_IGBP_MODIS_NOAH')