numbas / numbas-extension-programming

An extension for Numbas which provides a code editor and the ability to evaluate code written in Python and R.
Apache License 2.0
3 stars 1 forks source link

Allow unexpected plotting with matplotlib #7

Closed chrismgraham closed 2 years ago

chrismgraham commented 2 years ago

At the moment, if a student creates a plot unexpectedly in a question which is not prepared for it, a quite unhelpful error message is presented:

ImportError: cannot import name 'document' from 'js' (unknown location)

I can foresee this happening with exam questions where I'm asking for some code, but the plot is to be submitted as an upload: students could easily copy their code from their IDE with the plot command included.

We don't want to load matplotlib to set the backend etc in preamble/postamble to every question, just on the off chance they make a plot, but the following might work in a more light touch way, if it is possible to include the commands behind the scenes (rather than on a per question basis.

Set the requisite environment variable for the backend without loading matplotlib

import os
os.environ['MPLBACKEND'] = 'AGG'

And then after the student answer, if matplotlib has been loaded, grab the current figure

import sys
if 'matplotlib' in sys.modules:
   fig = plt.gcf()
   if fig.get_axes():
      fig.savefig(sys.stdout, format='svg')

These two in preamble and postamble work quite effectively to allow plotting, but without loading matplotlib unless the student does. Could such a solution be included silently for all questions...?