mctools / ncrystal

NCrystal : a library for thermal neutron transport in crystals and other materials
https://mctools.github.io/ncrystal/
Other
41 stars 18 forks source link

Make usage of matplotlib consistent and more robust throughout python API #202

Open tkittel opened 1 month ago

tkittel commented 1 month ago

During the work on #154 I am making command-line script functionality available as Python modules. One interesting and troublesome aspect in that respect is that while a command-line script can simply modify global matplotlib settings, that will not work as well in a longer running Python process where the code formerly in scripts might now be invoked again and again.

For instance, we want to use the new cliutils.run functionality to invoke command line scripts in a jupyter notebook in the current process (which incidently allows custom-in-memory files to be used as input for the command line scripts!).

So how do we clean this up? We have to make sure that we never modify global matplotlib rcparams, and we also have to be careful about modifying the matplotlib backends.

So we must have consistent global matplotlib infrastructure for all of NCrystal, and we must use a context manager to switch to the agg backend when we need pdf plots. We should also only every change rcParams with the matplotlib.pyplot.rc_context context manager. See also the discussion at: https://github.com/matplotlib/matplotlib/issues/26362

Maybe we should also ensure that all of our matplotlib plotting functions simply return standalone Figure() objects? See also https://matplotlib.org/devdocs/gallery/user_interfaces/web_application_server_sgskip.html

tkittel commented 1 month ago

We could also have a common helper function for creating a pdf file (or pdf data) from a list of Figure's.

tkittel commented 1 month ago

We should also take the opportunity to make this easier to use during non-graphical unit tests. Some of the functionality from _testimpl.py could be adopted, but also improved.