Improve Reading/Using Colortable Files
What should we add?
A question came in on how to read and use a GEMPAK colortable file (basically a plain text file with a list of colors in RGB format) within MetPy. There was not a straightforward path to making this accessible...here is the code needed to go from reading the initial file, to a useful Matplotlib colormap:
from matplotlib.colors import ListedColormap
from metpy.plots.ctables import convert_gempak_table, read_colortable
infile = open("ir_upc2.tbl","r").readlines()
outfile = open('test_gempak_colortable.txt', 'w')
convert_gempak_table(infile, outfile)
outfile.close()
colortable = read_colortable(open('test_gempak_colortable.txt').readlines())
cmap = ListedColormap(colortable)
Potential Improvements:
- Accept filenames and back the opening and closing of the files within the
convert_gempak_table()function - Create a function/path to being able to read a colortable file directly to a Matplotlib Colormap object
Other thoughts/comments?
Reference
No response
The magic of Python and file-like objects can make this a little cleaner:
from io import StringIO
from matplotlib.colors import ListedColormap
from metpy.plots.ctables import convert_gempak_table, read_colortable
with open("ir_upc2.tbl","r") as infile:
converted = StringIO()
convert_gempak_table(infile, converted)
# Reset StringIO to have pointer at beginning
converted.seek(0)
colortable = read_colortable(converted)
cmap = ListedColormap(colortable)
Why would opening/closing the file within convert_gempak_table be better? It's almost always better to let the user handle this kind of thing. In fact, that function might actually be better if it were a generator yielding the lines of the converted colorable. In fact, with the exception of calling write() within convert_gempak_table, this is really just a set of functions operating on iterators and if we eliminated that you could do:
with open('ir_upc2.tbl', r') as infile:
camp = ListedColormap(read_colorable(convert_gempak_table(infile)))
We also made the intentional decision to start that we provided a path for people to convert the tables as needed, but we weren't going to make those a standard format for us in the name of moving away from the legacy tools, which is why the GEMPAK table format isn't "just" supported by the registry. Is that something we need to revisit?
Yeah, there may not need to be improvements to what the code is doing, but we have under documented this to make it accessible for at least a segment of our users (including myself). I think your suggestion of removing the write() portion from the convert_gempak_table and returned an iterator, that could make a substantial difference for users.
So, no probably don't need to revisit wholesale.