// Numbas version: exam_results_page_options {"name": "Embedding digital skills in the mathematics curriculum", "metadata": {"description": "

Some examples of interactive plots illustrating mathematical concepts, supported by Python exercises.

", "licence": "None specified"}, "duration": 0, "percentPass": 0, "showQuestionGroupNames": false, "shuffleQuestionGroups": false, "showstudentname": true, "question_groups": [{"name": "Group", "pickingStrategy": "all-ordered", "pickQuestions": 1, "questionNames": ["", "", "", ""], "variable_overrides": [[], [], [], []], "questions": [{"name": "Plotting a parametric surface with Python", "extensions": ["programming"], "custom_part_types": [{"source": {"pk": 195, "author": {"name": "Christian Lawson-Perfect", "pk": 7}, "edit_page": "/part_type/195/edit"}, "name": "Code", "short_name": "mark-code-3", "description": "

Mark code provided by the student by running it and a series of validation and marking tests.

\n

The validation tests are used to reject an answer if the student has misunderstood the task, for example if they haven't defined a required variable or function.

\n

Marking tests check properties of the student's code. Each test awards a proportion of the available credit if it is passed.

\n

You can optionally show the student the STDOUT and/or STDERR when running their code.

\n

You can give a preamble and postamble which are run before and after the student's code, and also modify the student's code before running it.

", "help_url": "", "input_widget": "code-editor", "input_options": {"correctAnswer": "if(settings[\"correct_answer_subvars\"],\n render(settings[\"correct_answer\"])\n,\n settings[\"correct_answer\"]\n)", "hint": {"static": false, "value": "\"Write \"+capitalise(language_synonym(settings[\"code_language\"]))+\" code\""}, "language": {"static": false, "value": "language_synonym(settings[\"code_language\"])"}, "placeholder": {"static": false, "value": "if(settings[\"correct_answer_subvars\"],\n render(settings[\"placeholder\"])\n,\n settings[\"placeholder\"]\n)"}, "theme": {"static": true, "value": "textmate"}}, "can_be_gap": true, "can_be_step": true, "marking_script": "mark:\napply(main_error);\napply(show_images);\napply(matplotlib_feedback);\napply(postamble_feedback);\napply(validation_test_feedback);\napply(marking_test_feedback)\n\ninterpreted_answer:\nstudentAnswer\n\nmain_result:\ncode_result[3]\n\nmarking_results:\ncode_result[6..(len(settings[\"tests\"])+6)]\n\nvalidation_results:\ncode_result[(len(settings[\"tests\"])+6)..len(code_result)]\n\nmain_error:\nassert(main_stdout=\"\" or not settings[\"show_stdout\"],\n feedback(\"Your code produced this output:
{escape_html(main_stdout)}
\")\n);\nassert(main_result[\"success\"],\n if(settings[\"show_stderr\"],\n fail(\"\"\"There was an error in your code:
{escape_html(main_result[\"stderr\"])}
\"\"\")\n ,\n fail(\"There was an error in your code.\")\n )\n)\n\nmarking_test_feedback:\nmap(\n let(\n [name,weight,code], test,\n header, \"Test: {name} \",\n if(r[\"success\"],\n let(\n result, r[\"result\"],\n max_credit, weight/total_weight,\n credit, if(result isa \"number\", result, award(1,result)),\n switch(\n credit=0, negative_feedback(header+\"was not passed.\"),\n credit=1, add_credit(max_credit, header+\"was passed.\"),\n add_credit(credit*max_credit, header+\"was partially passed.\")\n )\n )\n ,\n if(settings[\"show_marking_errors\"],\n negative_feedback(\"\"\"There was an error:
{escape_html(r[\"stderr\"])}
\"\"\")\n ,\n negative_feedback(header+\"was not passed.\")\n )\n )\n ),\n [test,r],\n zip(settings[\"tests\"],marking_results)\n)\n\nvalidation_test_feedback:\nmap(\n let([name,code], test,\n if(r[\"success\"],\n if(r[\"result\"],\n true\n ,\n fail(\"\"\"Your code failed the test {name}.\"\"\");false\n )\n ,\n fail(\"\"\"There was an error running the test {name}:
{escape_html(r[\"stderr\"])}
\"\"\")\n )\n ),\n [test,r],\n zip(settings[\"validation_tests\"],validation_results)\n)\n\ntotal_weight:\nsum(map(weight,[name,weight,code],settings[\"tests\"]))\n\npre_submit:\n[run_code(code_language,\n [\n matplotlib_preamble,\n variables_as_code(language_synonym(code_language), settings[\"variables\"]),\n render(settings[\"preamble\"]),\n if(trim(settings[\"modifier\"])=\"\", studentAnswer, eval(expression(settings[\"modifier\"]))),\n render(settings[\"postamble\"]),\n matplotlib_postamble\n ]\n +map(code,[name,marks,code],settings[\"tests\"])\n +map(code,[name,code],settings[\"validation_tests\"])\n)]\n\ncode_result:\npre_submit[\"code_result\"]\n\nmain_stdout:\nsafe(main_result[\"stdout\"])\n\ncode_language:\nsettings[\"code_language\"]\n\npreamble_result:\ncode_result[2]\n\npreamble_stderr:\npreamble_result[\"stderr\"]\n\npostamble_result:\ncode_result[4]\n\npostamble_stderr:\npostamble_result[\"stderr\"]\n\npostamble_feedback:\nassert(postamble_result[\"stdout\"]=\"\",\n feedback(\n if(settings[\"postamble_feedback_whitespace\"],\n html(\"\"\"
{escape_html(postamble_result[\"stdout\"])}
\"\"\")\n ,\n postamble_result[\"stdout\"]\n )\n )\n);\nassert(postamble_result[\"success\"],\n if(settings[\"show_stderr\"],\n fail(\"\"\"There was an error in the marking routine postamble:
{escape_html(postamble_result[\"stderr\"])}
\"\"\")\n ,\n fail(\"There was an error in the marking routine postamble.\")\n )\n)\n\nmatplotlib_preamble:\nif(code_language=\"pyodide\",\n safe(\"\"\"\nimport sys\nif 'matplotlib' in sys.modules:\n import matplotlib.pyplot as plt\n plt.clf() \n\"\"\"),\n \"\"\n)\n\nmatplotlib_postamble:\nswitch(\ncode_language=\"pyodide\",\n safe(\"\"\"\nimport sys\nif 'matplotlib' in sys.modules:\n import matplotlib.pyplot as plt\n fig = plt.gcf()\n if fig.get_axes():\n fig.savefig(sys.stdout, format='svg')\n\"\"\"),\n \"\"\n)\n\nmatplotlib_result:\ncode_result[5]\n\nmatplotlib_feedback:\nswitch(\ncode_language=\"pyodide\",\n assert(matplotlib_result[\"stdout\"]=\"\",\n feedback(matplotlib_result[\"stdout\"])\n ),\n \"\"\n)\n\n\n\nimages:\nflatten(map(\n get(r,\"images\",[]),\n r,\n code_result\n))\n\nshow_images:\nassert(len(images)=0 or not settings[\"show_stdout\"],\n feedback(\"Your code produced the following {pluralise(len(images),'image','images')}:\");\n map(\n feedback(html(x)),\n x,\n images\n )\n)", "marking_notes": [{"name": "mark", "description": "This is the main marking note. It should award credit and provide feedback based on the student's answer.", "definition": "apply(main_error);\napply(show_images);\napply(matplotlib_feedback);\napply(postamble_feedback);\napply(validation_test_feedback);\napply(marking_test_feedback)"}, {"name": "interpreted_answer", "description": "A value representing the student's answer to this part.", "definition": "studentAnswer"}, {"name": "main_result", "description": "

The result of running the student's code and the preamble, without any tests.

\n

Normally used to detect errors in the student's code.

", "definition": "code_result[3]"}, {"name": "marking_results", "description": "

The results of running the marking tests.

", "definition": "code_result[6..(len(settings[\"tests\"])+6)]"}, {"name": "validation_results", "description": "

The results of running the validation tests.

", "definition": "code_result[(len(settings[\"tests\"])+6)..len(code_result)]"}, {"name": "main_error", "description": "

Show STDOUT if allowed.

\n

Check the student's code runs on its own. Fail if there was an error, and show STDERR if allowed.

", "definition": "assert(main_stdout=\"\" or not settings[\"show_stdout\"],\n feedback(\"Your code produced this output:
{escape_html(main_stdout)}
\")\n);\nassert(main_result[\"success\"],\n if(settings[\"show_stderr\"],\n fail(\"\"\"There was an error in your code:
{escape_html(main_result[\"stderr\"])}
\"\"\")\n ,\n fail(\"There was an error in your code.\")\n )\n)"}, {"name": "marking_test_feedback", "description": "

Feedback on the marking tests. For each test, if the test was passed then add the corresponding amount of credit. If there was an error, show the error.

", "definition": "map(\n let(\n [name,weight,code], test,\n header, \"Test: {name} \",\n if(r[\"success\"],\n let(\n result, r[\"result\"],\n max_credit, weight/total_weight,\n credit, if(result isa \"number\", result, award(1,result)),\n switch(\n credit=0, negative_feedback(header+\"was not passed.\"),\n credit=1, add_credit(max_credit, header+\"was passed.\"),\n add_credit(credit*max_credit, header+\"was partially passed.\")\n )\n )\n ,\n if(settings[\"show_marking_errors\"],\n negative_feedback(\"\"\"There was an error:
{escape_html(r[\"stderr\"])}
\"\"\")\n ,\n negative_feedback(header+\"was not passed.\")\n )\n )\n ),\n [test,r],\n zip(settings[\"tests\"],marking_results)\n)"}, {"name": "validation_test_feedback", "description": "

Give feedback on the validation tests. If any of them are not passed, the student's answer is invalid.

", "definition": "map(\n let([name,code], test,\n if(r[\"success\"],\n if(r[\"result\"],\n true\n ,\n fail(\"\"\"Your code failed the test {name}.\"\"\");false\n )\n ,\n fail(\"\"\"There was an error running the test {name}:
{escape_html(r[\"stderr\"])}
\"\"\")\n )\n ),\n [test,r],\n zip(settings[\"validation_tests\"],validation_results)\n)"}, {"name": "total_weight", "description": "

The sum of the weights of the marking tests. Each test's weight is divided by this to produce a proportion of the available credit.

", "definition": "sum(map(weight,[name,weight,code],settings[\"tests\"]))"}, {"name": "pre_submit", "description": "

The code blocks to run.

\n

In order, they are:

\n", "definition": "[run_code(code_language,\n [\n matplotlib_preamble,\n variables_as_code(language_synonym(code_language), settings[\"variables\"]),\n render(settings[\"preamble\"]),\n if(trim(settings[\"modifier\"])=\"\", studentAnswer, eval(expression(settings[\"modifier\"]))),\n render(settings[\"postamble\"]),\n matplotlib_postamble\n ]\n +map(code,[name,marks,code],settings[\"tests\"])\n +map(code,[name,code],settings[\"validation_tests\"])\n)]"}, {"name": "code_result", "description": "

The results of the code blocks: a list with an entry corresponding to each block of code.

", "definition": "pre_submit[\"code_result\"]"}, {"name": "main_stdout", "description": "

The stdout from the student's code.

", "definition": "safe(main_result[\"stdout\"])"}, {"name": "code_language", "description": "

The language the code is written in. Either \"pyodide\" (Python) or \"webr\" (R)

", "definition": "settings[\"code_language\"]"}, {"name": "preamble_result", "description": "

The result of running the preamble block.

", "definition": "code_result[2]"}, {"name": "preamble_stderr", "description": "

The STDERR produced by the preamble block.

", "definition": "preamble_result[\"stderr\"]"}, {"name": "postamble_result", "description": "

The result of running the postamble.

", "definition": "code_result[4]"}, {"name": "postamble_stderr", "description": "

The STDERR produced by the postamble block.

", "definition": "postamble_result[\"stderr\"]"}, {"name": "postamble_feedback", "description": "

Show the STDOUT from the postamble, if there is any.

", "definition": "assert(postamble_result[\"stdout\"]=\"\",\n feedback(\n if(settings[\"postamble_feedback_whitespace\"],\n html(\"\"\"
{escape_html(postamble_result[\"stdout\"])}
\"\"\")\n ,\n postamble_result[\"stdout\"]\n )\n )\n);\nassert(postamble_result[\"success\"],\n if(settings[\"show_stderr\"],\n fail(\"\"\"There was an error in the marking routine postamble:
{escape_html(postamble_result[\"stderr\"])}
\"\"\")\n ,\n fail(\"There was an error in the marking routine postamble.\")\n )\n)"}, {"name": "matplotlib_preamble", "description": "

Preamble for a hack to ensure that figures produced by matplotlib in Python are displayed.

\n

This code clears the matplotlib output, if matplotlib has been loaded.

", "definition": "if(code_language=\"pyodide\",\n safe(\"\"\"\nimport sys\nif 'matplotlib' in sys.modules:\n import matplotlib.pyplot as plt\n plt.clf() \n\"\"\"),\n \"\"\n)"}, {"name": "matplotlib_postamble", "description": "

A hack to show any figures produced with matplotlib in the stdout.

", "definition": "switch(\ncode_language=\"pyodide\",\n safe(\"\"\"\nimport sys\nif 'matplotlib' in sys.modules:\n import matplotlib.pyplot as plt\n fig = plt.gcf()\n if fig.get_axes():\n fig.savefig(sys.stdout, format='svg')\n\"\"\"),\n \"\"\n)"}, {"name": "matplotlib_result", "description": "

The result of running the matplotlib hack.

", "definition": "code_result[5]"}, {"name": "matplotlib_feedback", "description": "

Feedback from the matplotlib hack: if a figure is produced, it's displayed as SVG here.

", "definition": "switch(\ncode_language=\"pyodide\",\n assert(matplotlib_result[\"stdout\"]=\"\",\n feedback(matplotlib_result[\"stdout\"])\n ),\n \"\"\n)\n\n"}, {"name": "images", "description": "

Any images produced by the code blocks.

", "definition": "flatten(map(\n get(r,\"images\",[]),\n r,\n code_result\n))"}, {"name": "show_images", "description": "

Show the images produced by the code.

", "definition": "assert(len(images)=0 or not settings[\"show_stdout\"],\n feedback(\"Your code produced the following {pluralise(len(images),'image','images')}:\");\n map(\n feedback(html(x)),\n x,\n images\n )\n)"}], "settings": [{"name": "show_input_hint", "label": "Show the input hint?", "help_url": "", "hint": "", "input_type": "checkbox", "default_value": true}, {"name": "code_language", "label": "Code language", "help_url": "", "hint": "The language that the student's code will be written in.", "input_type": "dropdown", "default_value": "pyodide", "choices": [{"value": "pyodide", "label": "Python"}, {"value": "webr", "label": "R"}]}, {"name": "correct_answer", "label": "Correct answer", "help_url": "", "hint": "A correct answer to the part.", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "correct_answer_subvars", "label": "Substitute question variables into the correct answer?", "help_url": "", "hint": "If ticked, then JME expressions between curly braces will be evaluated and substituted into the correct answer.

If not ticked, then the correct answer will be displayed exactly as it is.", "input_type": "checkbox", "default_value": true}, {"name": "show_stdout", "label": "Show stdout?", "help_url": "", "hint": "If ticked, the STDOUT produced after running the student's code will be shown in the feedback.", "input_type": "checkbox", "default_value": true}, {"name": "show_stderr", "label": "Show stderr?", "help_url": "", "hint": "If ticked, the STDERR produced after running the student's code will be shown in the feedback.", "input_type": "checkbox", "default_value": true}, {"name": "show_marking_errors", "label": "Show errors produced by marking tests?", "help_url": "", "hint": "", "input_type": "checkbox", "default_value": false}, {"name": "placeholder", "label": "Placeholder", "help_url": "", "hint": "Initial text for the code editor", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "modifier", "label": "Student code modifier", "help_url": "", "hint": "JME expression to modify the student's submitted code before being passed to the marking template. The student's code is available as the string variable studentAnswer.", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "preamble", "label": "Preamble", "help_url": "", "hint": "This code is run before the student's code. Define anything that the student's code or your tests need.", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "postamble", "label": "Postamble", "help_url": "", "hint": "This code is run after the student's code but before the validation and unit tests.", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "postamble_feedback_whitespace", "label": "Format postamble output as code?", "help_url": "", "hint": "If ticked, any output produced by the postamble will be formatted in monospace font, with whitespace preserved. If not ticked, it'll be presented as prose text or HTML.", "input_type": "checkbox", "default_value": false}, {"name": "tests", "label": "Marking tests", "help_url": "", "hint": "A list of tests used to mark the student's answer.
Each item is a list with three values:
\n", "input_type": "code", "default_value": "[\n [\"Test 1\", 1, \"True\"]\n]", "evaluate": true}, {"name": "validation_tests", "label": "Validation tests", "help_url": "", "hint": "

A list of tests used to validate that the student's code is acceptable.
Each item is a list with two string values:

\n", "input_type": "code", "default_value": "[\n [\"arithmetic works\", \"1+1 == 2\"]\n]", "evaluate": true}, {"name": "variables", "label": "Variables to include in code", "help_url": "", "hint": "Give a dictionary mapping variable names to their values. These variables will be available in the code that is run.", "input_type": "code", "default_value": "dict()", "evaluate": true}], "public_availability": "always", "published": true, "extensions": ["programming"]}], "resources": [], "navigation": {"allowregen": true, "showfrontpage": false, "preventleave": false, "typeendtoleave": false}, "contributors": [{"name": "Christian Lawson-Perfect", "profile_url": "https://numbas.mathcentre.ac.uk/accounts/profile/7/"}, {"name": "Chris Graham", "profile_url": "https://numbas.mathcentre.ac.uk/accounts/profile/369/"}, {"name": "Toby Wood", "profile_url": "https://numbas.mathcentre.ac.uk/accounts/profile/400/"}, {"name": "George Stagg", "profile_url": "https://numbas.mathcentre.ac.uk/accounts/profile/930/"}], "tags": [], "metadata": {"description": "

Edit the Python code to make a 3D plot of a surface defined parametrically.

", "licence": "Creative Commons Attribution 4.0 International"}, "statement": "", "advice": "

Now you can try plotting other parametric surfaces.  Remember, as well as changing the definitions of $x(u,v)$, $y(u,v)$ and $z(u,v)$, you'll also need to set the correct ranges for $u$ and $v$.

", "rulesets": {}, "builtin_constants": {"e": true, "pi,\u03c0": true, "i": true}, "constants": [], "variables": {"python_preamble": {"name": "python_preamble", "group": "Ungrouped variables", "definition": "safe(\"import matplotlib.pyplot as plt\\nfig = plt.figure()\")", "description": "", "templateType": "long plain string", "can_override": false}}, "variablesTest": {"condition": "", "maxRuns": 100}, "ungrouped_variables": ["python_preamble"], "variable_groups": [], "functions": {"r_load_files": {"parameters": [["files", "list of string"]], "type": "promise", "language": "javascript", "definition": "const mime_types = {\n '.pdf': 'application/pdf',\n '.svg': 'image/svg+xml'\n}\nreturn new Numbas.jme.types.TPromise(Numbas.extensions.programming.language_runners['webr'].load_webR().then(async (webR) => {\n var promises = [];\n files.forEach(filename => {\n promises.push(new Promise((resolve,reject) => {\n setTimeout(async function() {\n try {\n const buf = await webR.getFileData(filename);\n const extension = filename.match(/\\.[^.]*$/)[0];\n const mime_type = mime_types[extension] || 'text/plain';\n var blob = new Blob([buf], {type: mime_type});\n if(mime_type == 'text/plain' || mime_type == 'image/svg+xml') {\n const text = await blob.text();\n resolve({exists: true, text: text, mime_type});\n } else {\n resolve({exists: true, blob: URL.createObjectURL(blob), mime_type});\n }\n } catch(err) {\n resolve({exists: false, error: err.message});\n }\n },10);\n }));\n });\n const results = await Promise.all(promises);\n var o = {};\n results.forEach((value,i) => { o[files[i]] = jme.wrapValue(value); });\n return {\n r_files: new Numbas.jme.types.TDict(o)\n }\n}));"}, "show_pdf": {"parameters": [["url", "string"]], "type": "html", "language": "jme", "definition": "html(\"\"\"\"\"\")"}, "show_svg": {"parameters": [["text", "string"]], "type": "html", "language": "jme", "definition": "html(text)"}, "r_load_package": {"parameters": [["name", "string"]], "type": "anything", "language": "javascript", "definition": "return new Numbas.jme.types.TPromise(Numbas.extensions.programming.language_runners['webr'].load_webR().then(async (webR) => {\n await webR.loadPackage(name);\n return {};\n}));"}}, "preamble": {"js": "Numbas.extensions.programming.preload('pyodide');", "css": ""}, "parts": [{"type": "mark-code-3", "useCustomName": false, "customName": "", "marks": "0", "scripts": {}, "customMarkingAlgorithm": "mark:\n feedback(\"Here's your figure:\");\n feedback(html(code_result[4][\"stdout\"])) ", "extendBaseMarkingAlgorithm": true, "unitTests": [], "showCorrectAnswer": false, "showFeedbackIcon": false, "variableReplacements": [], "variableReplacementStrategy": "originalfirst", "nextParts": [], "suggestGoingBack": false, "adaptiveMarkingPenalty": 0, "exploreObjective": null, "prompt": "

A figure, called fig, has already been created as follows:

\n

{code_block(python_preamble,\"python\")}

\n

Now we'll plot a parametric surface in this figure.

\n

The code below is designed to plot the particular surface

\n

$(u,v) \\longmapsto (\\sin(u)\\cos(v),\\ \\sin(u)\\sin(v),\\ \\cos(u)), \\; 0 \\leqslant u \\leqslant \\pi, \\; 0 \\leqslant v \\leqslant 2\\pi\\,.$

\n

You'll need to edit the code before it will run.  Why not try changing the colour map from 'binary' to 'turbo' or 'copper'?

", "settings": {"show_input_hint": true, "code_language": "pyodide", "correct_answer": "", "correct_answer_subvars": true, "show_stdout": true, "show_stderr": true, "show_marking_errors": false, "placeholder": "# To do maths stuff, the numpy package is essential\nimport numpy as np\n\n# We first define linear arrays for our two surface parameters\npoints = 21\nu_lin = np.linspace(0,np.pi,points) # A linear array from 0 to pi\nv_lin = np.linspace(0,2*np.pi,points) # A linear array from 0 to 2*pi\n# We now convert the linear arrays into a pair of 2D arrays called u and v\nu,v = np.meshgrid(u_lin,v_lin,indexing='ij')\n\n# Now we can define x, y and z as functions of the parameters u and v\nx = np.sin(u)*np.cos(v)\ny = np.sin(u)*np.sin(v)\nz = np.cos(u)\n\n# Finally, we create some 3D axes and plot the surface\nax = plt.axes(projection='3d')\nax.plot_surface(x, y, z, cmap='binary', edgecolor='red')", "modifier": "", "preamble": "import sys\nimport matplotlib\n\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfig = plt.figure()\nfig.savefig(sys.stdout, format='svg')", "postamble": "fig.savefig(sys.stdout, format='svg')", "postamble_feedback_whitespace": false, "tests": "[\n [\"Test 1\", 1, \"True\"]\n]", "validation_tests": "[\n [\"arithmetic works\", \"1+1 == 2\"]\n]", "variables": "dict()"}}], "partsMode": "all", "maxMarks": 0, "objectives": [], "penalties": [], "objectiveVisibility": "always", "penaltyVisibility": "always"}, {"name": "Fourier sine series coefficients", "extensions": ["jsxgraph", "programming"], "custom_part_types": [{"source": {"pk": 195, "author": {"name": "Christian Lawson-Perfect", "pk": 7}, "edit_page": "/part_type/195/edit"}, "name": "Code", "short_name": "mark-code-3", "description": "

Mark code provided by the student by running it and a series of validation and marking tests.

\n

The validation tests are used to reject an answer if the student has misunderstood the task, for example if they haven't defined a required variable or function.

\n

Marking tests check properties of the student's code. Each test awards a proportion of the available credit if it is passed.

\n

You can optionally show the student the STDOUT and/or STDERR when running their code.

\n

You can give a preamble and postamble which are run before and after the student's code, and also modify the student's code before running it.

", "help_url": "", "input_widget": "code-editor", "input_options": {"correctAnswer": "if(settings[\"correct_answer_subvars\"],\n render(settings[\"correct_answer\"])\n,\n settings[\"correct_answer\"]\n)", "hint": {"static": false, "value": "\"Write \"+capitalise(language_synonym(settings[\"code_language\"]))+\" code\""}, "language": {"static": false, "value": "language_synonym(settings[\"code_language\"])"}, "placeholder": {"static": false, "value": "if(settings[\"correct_answer_subvars\"],\n render(settings[\"placeholder\"])\n,\n settings[\"placeholder\"]\n)"}, "theme": {"static": true, "value": "textmate"}}, "can_be_gap": true, "can_be_step": true, "marking_script": "mark:\napply(main_error);\napply(show_images);\napply(matplotlib_feedback);\napply(postamble_feedback);\napply(validation_test_feedback);\napply(marking_test_feedback)\n\ninterpreted_answer:\nstudentAnswer\n\nmain_result:\ncode_result[3]\n\nmarking_results:\ncode_result[6..(len(settings[\"tests\"])+6)]\n\nvalidation_results:\ncode_result[(len(settings[\"tests\"])+6)..len(code_result)]\n\nmain_error:\nassert(main_stdout=\"\" or not settings[\"show_stdout\"],\n feedback(\"Your code produced this output:
{escape_html(main_stdout)}
\")\n);\nassert(main_result[\"success\"],\n if(settings[\"show_stderr\"],\n fail(\"\"\"There was an error in your code:
{escape_html(main_result[\"stderr\"])}
\"\"\")\n ,\n fail(\"There was an error in your code.\")\n )\n)\n\nmarking_test_feedback:\nmap(\n let(\n [name,weight,code], test,\n header, \"Test: {name} \",\n if(r[\"success\"],\n let(\n result, r[\"result\"],\n max_credit, weight/total_weight,\n credit, if(result isa \"number\", result, award(1,result)),\n switch(\n credit=0, negative_feedback(header+\"was not passed.\"),\n credit=1, add_credit(max_credit, header+\"was passed.\"),\n add_credit(credit*max_credit, header+\"was partially passed.\")\n )\n )\n ,\n if(settings[\"show_marking_errors\"],\n negative_feedback(\"\"\"There was an error:
{escape_html(r[\"stderr\"])}
\"\"\")\n ,\n negative_feedback(header+\"was not passed.\")\n )\n )\n ),\n [test,r],\n zip(settings[\"tests\"],marking_results)\n)\n\nvalidation_test_feedback:\nmap(\n let([name,code], test,\n if(r[\"success\"],\n if(r[\"result\"],\n true\n ,\n fail(\"\"\"Your code failed the test {name}.\"\"\");false\n )\n ,\n fail(\"\"\"There was an error running the test {name}:
{escape_html(r[\"stderr\"])}
\"\"\")\n )\n ),\n [test,r],\n zip(settings[\"validation_tests\"],validation_results)\n)\n\ntotal_weight:\nsum(map(weight,[name,weight,code],settings[\"tests\"]))\n\npre_submit:\n[run_code(code_language,\n [\n matplotlib_preamble,\n variables_as_code(language_synonym(code_language), settings[\"variables\"]),\n render(settings[\"preamble\"]),\n if(trim(settings[\"modifier\"])=\"\", studentAnswer, eval(expression(settings[\"modifier\"]))),\n render(settings[\"postamble\"]),\n matplotlib_postamble\n ]\n +map(code,[name,marks,code],settings[\"tests\"])\n +map(code,[name,code],settings[\"validation_tests\"])\n)]\n\ncode_result:\npre_submit[\"code_result\"]\n\nmain_stdout:\nsafe(main_result[\"stdout\"])\n\ncode_language:\nsettings[\"code_language\"]\n\npreamble_result:\ncode_result[2]\n\npreamble_stderr:\npreamble_result[\"stderr\"]\n\npostamble_result:\ncode_result[4]\n\npostamble_stderr:\npostamble_result[\"stderr\"]\n\npostamble_feedback:\nassert(postamble_result[\"stdout\"]=\"\",\n feedback(\n if(settings[\"postamble_feedback_whitespace\"],\n html(\"\"\"
{escape_html(postamble_result[\"stdout\"])}
\"\"\")\n ,\n postamble_result[\"stdout\"]\n )\n )\n);\nassert(postamble_result[\"success\"],\n if(settings[\"show_stderr\"],\n fail(\"\"\"There was an error in the marking routine postamble:
{escape_html(postamble_result[\"stderr\"])}
\"\"\")\n ,\n fail(\"There was an error in the marking routine postamble.\")\n )\n)\n\nmatplotlib_preamble:\nif(code_language=\"pyodide\",\n safe(\"\"\"\nimport sys\nif 'matplotlib' in sys.modules:\n import matplotlib.pyplot as plt\n plt.clf() \n\"\"\"),\n \"\"\n)\n\nmatplotlib_postamble:\nswitch(\ncode_language=\"pyodide\",\n safe(\"\"\"\nimport sys\nif 'matplotlib' in sys.modules:\n import matplotlib.pyplot as plt\n fig = plt.gcf()\n if fig.get_axes():\n fig.savefig(sys.stdout, format='svg')\n\"\"\"),\n \"\"\n)\n\nmatplotlib_result:\ncode_result[5]\n\nmatplotlib_feedback:\nswitch(\ncode_language=\"pyodide\",\n assert(matplotlib_result[\"stdout\"]=\"\",\n feedback(matplotlib_result[\"stdout\"])\n ),\n \"\"\n)\n\n\n\nimages:\nflatten(map(\n get(r,\"images\",[]),\n r,\n code_result\n))\n\nshow_images:\nassert(len(images)=0 or not settings[\"show_stdout\"],\n feedback(\"Your code produced the following {pluralise(len(images),'image','images')}:\");\n map(\n feedback(html(x)),\n x,\n images\n )\n)", "marking_notes": [{"name": "mark", "description": "This is the main marking note. It should award credit and provide feedback based on the student's answer.", "definition": "apply(main_error);\napply(show_images);\napply(matplotlib_feedback);\napply(postamble_feedback);\napply(validation_test_feedback);\napply(marking_test_feedback)"}, {"name": "interpreted_answer", "description": "A value representing the student's answer to this part.", "definition": "studentAnswer"}, {"name": "main_result", "description": "

The result of running the student's code and the preamble, without any tests.

\n

Normally used to detect errors in the student's code.

", "definition": "code_result[3]"}, {"name": "marking_results", "description": "

The results of running the marking tests.

", "definition": "code_result[6..(len(settings[\"tests\"])+6)]"}, {"name": "validation_results", "description": "

The results of running the validation tests.

", "definition": "code_result[(len(settings[\"tests\"])+6)..len(code_result)]"}, {"name": "main_error", "description": "

Show STDOUT if allowed.

\n

Check the student's code runs on its own. Fail if there was an error, and show STDERR if allowed.

", "definition": "assert(main_stdout=\"\" or not settings[\"show_stdout\"],\n feedback(\"Your code produced this output:
{escape_html(main_stdout)}
\")\n);\nassert(main_result[\"success\"],\n if(settings[\"show_stderr\"],\n fail(\"\"\"There was an error in your code:
{escape_html(main_result[\"stderr\"])}
\"\"\")\n ,\n fail(\"There was an error in your code.\")\n )\n)"}, {"name": "marking_test_feedback", "description": "

Feedback on the marking tests. For each test, if the test was passed then add the corresponding amount of credit. If there was an error, show the error.

", "definition": "map(\n let(\n [name,weight,code], test,\n header, \"Test: {name} \",\n if(r[\"success\"],\n let(\n result, r[\"result\"],\n max_credit, weight/total_weight,\n credit, if(result isa \"number\", result, award(1,result)),\n switch(\n credit=0, negative_feedback(header+\"was not passed.\"),\n credit=1, add_credit(max_credit, header+\"was passed.\"),\n add_credit(credit*max_credit, header+\"was partially passed.\")\n )\n )\n ,\n if(settings[\"show_marking_errors\"],\n negative_feedback(\"\"\"There was an error:
{escape_html(r[\"stderr\"])}
\"\"\")\n ,\n negative_feedback(header+\"was not passed.\")\n )\n )\n ),\n [test,r],\n zip(settings[\"tests\"],marking_results)\n)"}, {"name": "validation_test_feedback", "description": "

Give feedback on the validation tests. If any of them are not passed, the student's answer is invalid.

", "definition": "map(\n let([name,code], test,\n if(r[\"success\"],\n if(r[\"result\"],\n true\n ,\n fail(\"\"\"Your code failed the test {name}.\"\"\");false\n )\n ,\n fail(\"\"\"There was an error running the test {name}:
{escape_html(r[\"stderr\"])}
\"\"\")\n )\n ),\n [test,r],\n zip(settings[\"validation_tests\"],validation_results)\n)"}, {"name": "total_weight", "description": "

The sum of the weights of the marking tests. Each test's weight is divided by this to produce a proportion of the available credit.

", "definition": "sum(map(weight,[name,weight,code],settings[\"tests\"]))"}, {"name": "pre_submit", "description": "

The code blocks to run.

\n

In order, they are:

\n", "definition": "[run_code(code_language,\n [\n matplotlib_preamble,\n variables_as_code(language_synonym(code_language), settings[\"variables\"]),\n render(settings[\"preamble\"]),\n if(trim(settings[\"modifier\"])=\"\", studentAnswer, eval(expression(settings[\"modifier\"]))),\n render(settings[\"postamble\"]),\n matplotlib_postamble\n ]\n +map(code,[name,marks,code],settings[\"tests\"])\n +map(code,[name,code],settings[\"validation_tests\"])\n)]"}, {"name": "code_result", "description": "

The results of the code blocks: a list with an entry corresponding to each block of code.

", "definition": "pre_submit[\"code_result\"]"}, {"name": "main_stdout", "description": "

The stdout from the student's code.

", "definition": "safe(main_result[\"stdout\"])"}, {"name": "code_language", "description": "

The language the code is written in. Either \"pyodide\" (Python) or \"webr\" (R)

", "definition": "settings[\"code_language\"]"}, {"name": "preamble_result", "description": "

The result of running the preamble block.

", "definition": "code_result[2]"}, {"name": "preamble_stderr", "description": "

The STDERR produced by the preamble block.

", "definition": "preamble_result[\"stderr\"]"}, {"name": "postamble_result", "description": "

The result of running the postamble.

", "definition": "code_result[4]"}, {"name": "postamble_stderr", "description": "

The STDERR produced by the postamble block.

", "definition": "postamble_result[\"stderr\"]"}, {"name": "postamble_feedback", "description": "

Show the STDOUT from the postamble, if there is any.

", "definition": "assert(postamble_result[\"stdout\"]=\"\",\n feedback(\n if(settings[\"postamble_feedback_whitespace\"],\n html(\"\"\"
{escape_html(postamble_result[\"stdout\"])}
\"\"\")\n ,\n postamble_result[\"stdout\"]\n )\n )\n);\nassert(postamble_result[\"success\"],\n if(settings[\"show_stderr\"],\n fail(\"\"\"There was an error in the marking routine postamble:
{escape_html(postamble_result[\"stderr\"])}
\"\"\")\n ,\n fail(\"There was an error in the marking routine postamble.\")\n )\n)"}, {"name": "matplotlib_preamble", "description": "

Preamble for a hack to ensure that figures produced by matplotlib in Python are displayed.

\n

This code clears the matplotlib output, if matplotlib has been loaded.

", "definition": "if(code_language=\"pyodide\",\n safe(\"\"\"\nimport sys\nif 'matplotlib' in sys.modules:\n import matplotlib.pyplot as plt\n plt.clf() \n\"\"\"),\n \"\"\n)"}, {"name": "matplotlib_postamble", "description": "

A hack to show any figures produced with matplotlib in the stdout.

", "definition": "switch(\ncode_language=\"pyodide\",\n safe(\"\"\"\nimport sys\nif 'matplotlib' in sys.modules:\n import matplotlib.pyplot as plt\n fig = plt.gcf()\n if fig.get_axes():\n fig.savefig(sys.stdout, format='svg')\n\"\"\"),\n \"\"\n)"}, {"name": "matplotlib_result", "description": "

The result of running the matplotlib hack.

", "definition": "code_result[5]"}, {"name": "matplotlib_feedback", "description": "

Feedback from the matplotlib hack: if a figure is produced, it's displayed as SVG here.

", "definition": "switch(\ncode_language=\"pyodide\",\n assert(matplotlib_result[\"stdout\"]=\"\",\n feedback(matplotlib_result[\"stdout\"])\n ),\n \"\"\n)\n\n"}, {"name": "images", "description": "

Any images produced by the code blocks.

", "definition": "flatten(map(\n get(r,\"images\",[]),\n r,\n code_result\n))"}, {"name": "show_images", "description": "

Show the images produced by the code.

", "definition": "assert(len(images)=0 or not settings[\"show_stdout\"],\n feedback(\"Your code produced the following {pluralise(len(images),'image','images')}:\");\n map(\n feedback(html(x)),\n x,\n images\n )\n)"}], "settings": [{"name": "show_input_hint", "label": "Show the input hint?", "help_url": "", "hint": "", "input_type": "checkbox", "default_value": true}, {"name": "code_language", "label": "Code language", "help_url": "", "hint": "The language that the student's code will be written in.", "input_type": "dropdown", "default_value": "pyodide", "choices": [{"value": "pyodide", "label": "Python"}, {"value": "webr", "label": "R"}]}, {"name": "correct_answer", "label": "Correct answer", "help_url": "", "hint": "A correct answer to the part.", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "correct_answer_subvars", "label": "Substitute question variables into the correct answer?", "help_url": "", "hint": "If ticked, then JME expressions between curly braces will be evaluated and substituted into the correct answer.

If not ticked, then the correct answer will be displayed exactly as it is.", "input_type": "checkbox", "default_value": true}, {"name": "show_stdout", "label": "Show stdout?", "help_url": "", "hint": "If ticked, the STDOUT produced after running the student's code will be shown in the feedback.", "input_type": "checkbox", "default_value": true}, {"name": "show_stderr", "label": "Show stderr?", "help_url": "", "hint": "If ticked, the STDERR produced after running the student's code will be shown in the feedback.", "input_type": "checkbox", "default_value": true}, {"name": "show_marking_errors", "label": "Show errors produced by marking tests?", "help_url": "", "hint": "", "input_type": "checkbox", "default_value": false}, {"name": "placeholder", "label": "Placeholder", "help_url": "", "hint": "Initial text for the code editor", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "modifier", "label": "Student code modifier", "help_url": "", "hint": "JME expression to modify the student's submitted code before being passed to the marking template. The student's code is available as the string variable studentAnswer.", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "preamble", "label": "Preamble", "help_url": "", "hint": "This code is run before the student's code. Define anything that the student's code or your tests need.", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "postamble", "label": "Postamble", "help_url": "", "hint": "This code is run after the student's code but before the validation and unit tests.", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "postamble_feedback_whitespace", "label": "Format postamble output as code?", "help_url": "", "hint": "If ticked, any output produced by the postamble will be formatted in monospace font, with whitespace preserved. If not ticked, it'll be presented as prose text or HTML.", "input_type": "checkbox", "default_value": false}, {"name": "tests", "label": "Marking tests", "help_url": "", "hint": "A list of tests used to mark the student's answer.
Each item is a list with three values:
\n", "input_type": "code", "default_value": "[\n [\"Test 1\", 1, \"True\"]\n]", "evaluate": true}, {"name": "validation_tests", "label": "Validation tests", "help_url": "", "hint": "

A list of tests used to validate that the student's code is acceptable.
Each item is a list with two string values:

\n", "input_type": "code", "default_value": "[\n [\"arithmetic works\", \"1+1 == 2\"]\n]", "evaluate": true}, {"name": "variables", "label": "Variables to include in code", "help_url": "", "hint": "Give a dictionary mapping variable names to their values. These variables will be available in the code that is run.", "input_type": "code", "default_value": "dict()", "evaluate": true}], "public_availability": "always", "published": true, "extensions": ["programming"]}], "resources": [], "navigation": {"allowregen": true, "showfrontpage": false, "preventleave": false, "typeendtoleave": false}, "contributors": [{"name": "Christian Lawson-Perfect", "profile_url": "https://numbas.mathcentre.ac.uk/accounts/profile/7/"}, {"name": "Toby Wood", "profile_url": "https://numbas.mathcentre.ac.uk/accounts/profile/400/"}], "tags": [], "metadata": {"description": "

Plot the Fourier series coefficients for a piece-wise linear function.  Write a Python script to reproduce the same figure.

", "licence": "None specified"}, "statement": "

The plot below shows the first 10 coefficients of the Fourier sine series for the function
$f(x) = \\displaystyle\\sum_{n=1}^{\\infty}b_n\\sin\\frac{\\pi nx}{l} = \\begin{cases}hx/d & \\mbox{if}\\ 0 \\leqslant x \\leqslant d \\\\ h(l-x)/(l-d) & \\mbox{if}\\ d \\leqslant x \\leqslant l\\end{cases}$.

\n

These coefficients are given by $b_n = \\frac{2h}{d(l-d)}\\left(\\frac{l}{\\pi n}\\right)^2\\sin\\frac{\\pi nd}{l}$.

\n

{diagram}

", "advice": "

Remember that, if you want to use constants like $\\pi$, or functions like $\\sin$, you need to code these as np.pi and np.sin().

", "rulesets": {}, "builtin_constants": {"e": true, "pi,\u03c0": true, "i": true}, "constants": [], "variables": {"diagram": {"name": "diagram", "group": "Ungrouped variables", "definition": "jessiecode(700,200,[-5.6,1.5,1.4,-0.5],safe(\"\"\"\n \n sinc = function(x) {\n if(abs(x)<0.001) {\n return 1;\n }\n else {\n return sin(x)/x;\n };\n };\n fourier_coefficient = function(i, d) {\n return 2/(PI*i)*(sinc(PI*i*d)-(-1)^i*sinc(PI*i*(1-d)));\n };\n \n // A slider for the value of d\n d = slider([-2,0.5],[-1,0.5],[0,0.5,1]) <>;\n \n // Plot of the graph of f(x)/h\n functiongraph(function(x) {\n if(x - d < 0) {\n return x/d;\n } else {\n return (1-x)/(1-d); \n };\n }, 0, 1);\n \n // Axes and labels for the graph\n xaxis = arrow([0,0], [1.2,0]) <>;\n point(1.2,0) <> >>;\n ticks(xaxis) <>, fixed: true, highlight: false>>;\n yaxis = arrow([0,0], [0,1.2]) <>;\n point(0,1.2) <> >>;\n ticks(yaxis) <>, fixed: true, highlight: false>>;\n \n xaxis2 = arrow([-5,0.2],[-2,0.2]) <>;\n point(-2,0.2) <> >>;\n ticks(xaxis2) <>, fixed: true, highlight: false, minorTicks: 0>>;\n \n yaxis2 = arrow([-5,-0.3],[-5,1.2]) <>;\n point(-5,1.2) <> >>;\n ticks(yaxis2) <>, fixed: true, highlight: false, minorTicks: 0>>;\n\n // Functions to transform coordinates for the plot of Fourier series\n x_series = function(x) {\n return x * 3*10/11 - 5;\n };\n y_series = function(y) {\n return y*0.8 + 0.2;\n };\n \n // Points representing the coefficients of the Fourier series\n make_point = function (i) {\n return point(x_series(i/10),function() { return y_series(fourier_coefficient(i,d.Value())); }) <>; \n };\n \n for(i=1;i<=10;i=i+1) {\n make_point(i);\n };\n \n\"\"\"),\n [\"axis\": false]\n)", "description": "", "templateType": "anything", "can_override": false}, "python_code": {"name": "python_code", "group": "Ungrouped variables", "definition": "safe(\"%matplotlib qt\\n\\nimport numpy as np\\nimport matplotlib.pyplot as plt\\nfrom matplotlib.widgets import Slider\\n\\n# Create the axes for the plots and the slider for d, with an initial value of d/l = d_init\\nfig, (coeffs, displacement) = plt.subplots(1,2,figsize=(24,12))\\ndaxis = fig.add_axes([0.45,0.49,0.1,0.02])\\nd_init = 0.5\\ndslider = Slider(ax=daxis,label=\\\"$d/l$\\\",valmin=0,valmax=1,valinit=d_init,valstep=0.01,initcolor=\\'none\\')\\n\\ndef fourier_coefficient(n,d):\\n# Add your code here to calculate the value of b_n/h, for given values of n and d/l\\n return\\n\\n# Plot the first 10 coefficients, assuming that d/l = d_init initially\\nvals = np.arange(10)+1\\npoints, = coeffs.plot(vals,fourier_coefficient(vals,d_init),\\'o\\')\\ncoeffs.set_ylim((-0.5,1))\\ncoeffs.set_xlabel(\\\"$n$\\\",loc=\\'right\\')\\ncoeffs.set_ylabel(\\\"$b_n/h$\\\",loc=\\'top\\',rotation=\\'horizontal\\')\\n\\n# Plot the function f(x)/h, again assuming that d/l = d_init initially\\ncurve, = displacement.plot([0,d_init,1],[0,1,0])\\ndisplacement.set_xlabel(\\\"$x/l$\\\",loc=\\'right\\')\\ndisplacement.set_ylabel(\\\"$f(x)/h$\\\",loc=\\'top\\',rotation=\\'horizontal\\')\\n\\n# When the slider is moved, this function will update the plots\\ndef update(val):\\n points.set_ydata(fourier_coefficient(vals,dslider.val))\\n curve.set_xdata([0,dslider.val,1])\\n fig.canvas.draw_idle()\\n \\ndslider.on_changed(update)\\n\\nplt.show()\")", "description": "", "templateType": "long plain string", "can_override": false}}, "variablesTest": {"condition": "", "maxRuns": 100}, "ungrouped_variables": ["diagram", "python_code"], "variable_groups": [], "functions": {}, "preamble": {"js": "", "css": ""}, "parts": [{"type": "mark-code-3", "useCustomName": true, "customName": "Reproducing the plots with Python", "marks": "0", "scripts": {}, "customMarkingAlgorithm": "mark:\n feedback(\"Here's your figure:\");\n feedback(html(code_result[4][\"stdout\"])) ", "extendBaseMarkingAlgorithm": true, "unitTests": [], "showCorrectAnswer": false, "showFeedbackIcon": false, "variableReplacements": [], "variableReplacementStrategy": "originalfirst", "nextParts": [], "suggestGoingBack": false, "adaptiveMarkingPenalty": 0, "exploreObjective": null, "prompt": "

You can make this figure yourself in Python by running the code below. But you'll need to code the function fourier_coefficient yourself first.

\n

{code_block(python_code,\"python\")}

\n

You can practice by modifying the code snippet below.

\n

Note: If you're not careful, your function will produce errors when $d/l = 0$ or $1$.

", "settings": {"show_input_hint": true, "code_language": "pyodide", "correct_answer": "", "correct_answer_subvars": true, "show_stdout": true, "show_stderr": true, "show_marking_errors": false, "placeholder": "d_init = 0.5\n\ndef fourier_coefficient(n,d):\n# Add your code here to calculate the value of b_n/h, for given values of n and d/l\n return\n\n# Plot the first 10 coefficients, assuming that d/l = d_init initially\nvals = np.arange(10)+1\npoints, = coeffs.plot(vals,fourier_coefficient(vals,d_init),'o')\ncoeffs.set_ylim((-0.5,1))\ncoeffs.set_xlabel(\"$n$\",loc='right')\ncoeffs.set_ylabel(\"$b_n/h$\",loc='top',rotation='horizontal')", "modifier": "", "preamble": "import sys\nimport matplotlib\n\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nfig = plt.figure()\nfig.savefig(sys.stdout, format='svg')\ncoeffs = plt.axes()", "postamble": "fig.savefig(sys.stdout, format='svg')", "postamble_feedback_whitespace": false, "tests": "[\n [\"Test 1\", 1, \"True\"]\n]", "validation_tests": "[\n [\"arithmetic works\", \"1+1 == 2\"]\n]", "variables": "dict()"}}], "partsMode": "all", "maxMarks": 0, "objectives": [], "penalties": [], "objectiveVisibility": "always", "penaltyVisibility": "always"}, {"name": "Plot the eigenfunctions", "extensions": ["jsxgraph", "programming"], "custom_part_types": [{"source": {"pk": 195, "author": {"name": "Christian Lawson-Perfect", "pk": 7}, "edit_page": "/part_type/195/edit"}, "name": "Code", "short_name": "mark-code-3", "description": "

Mark code provided by the student by running it and a series of validation and marking tests.

\n

The validation tests are used to reject an answer if the student has misunderstood the task, for example if they haven't defined a required variable or function.

\n

Marking tests check properties of the student's code. Each test awards a proportion of the available credit if it is passed.

\n

You can optionally show the student the STDOUT and/or STDERR when running their code.

\n

You can give a preamble and postamble which are run before and after the student's code, and also modify the student's code before running it.

", "help_url": "", "input_widget": "code-editor", "input_options": {"correctAnswer": "if(settings[\"correct_answer_subvars\"],\n render(settings[\"correct_answer\"])\n,\n settings[\"correct_answer\"]\n)", "hint": {"static": false, "value": "\"Write \"+capitalise(language_synonym(settings[\"code_language\"]))+\" code\""}, "language": {"static": false, "value": "language_synonym(settings[\"code_language\"])"}, "placeholder": {"static": false, "value": "if(settings[\"correct_answer_subvars\"],\n render(settings[\"placeholder\"])\n,\n settings[\"placeholder\"]\n)"}, "theme": {"static": true, "value": "textmate"}}, "can_be_gap": true, "can_be_step": true, "marking_script": "mark:\napply(main_error);\napply(show_images);\napply(matplotlib_feedback);\napply(postamble_feedback);\napply(validation_test_feedback);\napply(marking_test_feedback)\n\ninterpreted_answer:\nstudentAnswer\n\nmain_result:\ncode_result[3]\n\nmarking_results:\ncode_result[6..(len(settings[\"tests\"])+6)]\n\nvalidation_results:\ncode_result[(len(settings[\"tests\"])+6)..len(code_result)]\n\nmain_error:\nassert(main_stdout=\"\" or not settings[\"show_stdout\"],\n feedback(\"Your code produced this output:
{escape_html(main_stdout)}
\")\n);\nassert(main_result[\"success\"],\n if(settings[\"show_stderr\"],\n fail(\"\"\"There was an error in your code:
{escape_html(main_result[\"stderr\"])}
\"\"\")\n ,\n fail(\"There was an error in your code.\")\n )\n)\n\nmarking_test_feedback:\nmap(\n let(\n [name,weight,code], test,\n header, \"Test: {name} \",\n if(r[\"success\"],\n let(\n result, r[\"result\"],\n max_credit, weight/total_weight,\n credit, if(result isa \"number\", result, award(1,result)),\n switch(\n credit=0, negative_feedback(header+\"was not passed.\"),\n credit=1, add_credit(max_credit, header+\"was passed.\"),\n add_credit(credit*max_credit, header+\"was partially passed.\")\n )\n )\n ,\n if(settings[\"show_marking_errors\"],\n negative_feedback(\"\"\"There was an error:
{escape_html(r[\"stderr\"])}
\"\"\")\n ,\n negative_feedback(header+\"was not passed.\")\n )\n )\n ),\n [test,r],\n zip(settings[\"tests\"],marking_results)\n)\n\nvalidation_test_feedback:\nmap(\n let([name,code], test,\n if(r[\"success\"],\n if(r[\"result\"],\n true\n ,\n fail(\"\"\"Your code failed the test {name}.\"\"\");false\n )\n ,\n fail(\"\"\"There was an error running the test {name}:
{escape_html(r[\"stderr\"])}
\"\"\")\n )\n ),\n [test,r],\n zip(settings[\"validation_tests\"],validation_results)\n)\n\ntotal_weight:\nsum(map(weight,[name,weight,code],settings[\"tests\"]))\n\npre_submit:\n[run_code(code_language,\n [\n matplotlib_preamble,\n variables_as_code(language_synonym(code_language), settings[\"variables\"]),\n render(settings[\"preamble\"]),\n if(trim(settings[\"modifier\"])=\"\", studentAnswer, eval(expression(settings[\"modifier\"]))),\n render(settings[\"postamble\"]),\n matplotlib_postamble\n ]\n +map(code,[name,marks,code],settings[\"tests\"])\n +map(code,[name,code],settings[\"validation_tests\"])\n)]\n\ncode_result:\npre_submit[\"code_result\"]\n\nmain_stdout:\nsafe(main_result[\"stdout\"])\n\ncode_language:\nsettings[\"code_language\"]\n\npreamble_result:\ncode_result[2]\n\npreamble_stderr:\npreamble_result[\"stderr\"]\n\npostamble_result:\ncode_result[4]\n\npostamble_stderr:\npostamble_result[\"stderr\"]\n\npostamble_feedback:\nassert(postamble_result[\"stdout\"]=\"\",\n feedback(\n if(settings[\"postamble_feedback_whitespace\"],\n html(\"\"\"
{escape_html(postamble_result[\"stdout\"])}
\"\"\")\n ,\n postamble_result[\"stdout\"]\n )\n )\n);\nassert(postamble_result[\"success\"],\n if(settings[\"show_stderr\"],\n fail(\"\"\"There was an error in the marking routine postamble:
{escape_html(postamble_result[\"stderr\"])}
\"\"\")\n ,\n fail(\"There was an error in the marking routine postamble.\")\n )\n)\n\nmatplotlib_preamble:\nif(code_language=\"pyodide\",\n safe(\"\"\"\nimport sys\nif 'matplotlib' in sys.modules:\n import matplotlib.pyplot as plt\n plt.clf() \n\"\"\"),\n \"\"\n)\n\nmatplotlib_postamble:\nswitch(\ncode_language=\"pyodide\",\n safe(\"\"\"\nimport sys\nif 'matplotlib' in sys.modules:\n import matplotlib.pyplot as plt\n fig = plt.gcf()\n if fig.get_axes():\n fig.savefig(sys.stdout, format='svg')\n\"\"\"),\n \"\"\n)\n\nmatplotlib_result:\ncode_result[5]\n\nmatplotlib_feedback:\nswitch(\ncode_language=\"pyodide\",\n assert(matplotlib_result[\"stdout\"]=\"\",\n feedback(matplotlib_result[\"stdout\"])\n ),\n \"\"\n)\n\n\n\nimages:\nflatten(map(\n get(r,\"images\",[]),\n r,\n code_result\n))\n\nshow_images:\nassert(len(images)=0 or not settings[\"show_stdout\"],\n feedback(\"Your code produced the following {pluralise(len(images),'image','images')}:\");\n map(\n feedback(html(x)),\n x,\n images\n )\n)", "marking_notes": [{"name": "mark", "description": "This is the main marking note. It should award credit and provide feedback based on the student's answer.", "definition": "apply(main_error);\napply(show_images);\napply(matplotlib_feedback);\napply(postamble_feedback);\napply(validation_test_feedback);\napply(marking_test_feedback)"}, {"name": "interpreted_answer", "description": "A value representing the student's answer to this part.", "definition": "studentAnswer"}, {"name": "main_result", "description": "

The result of running the student's code and the preamble, without any tests.

\n

Normally used to detect errors in the student's code.

", "definition": "code_result[3]"}, {"name": "marking_results", "description": "

The results of running the marking tests.

", "definition": "code_result[6..(len(settings[\"tests\"])+6)]"}, {"name": "validation_results", "description": "

The results of running the validation tests.

", "definition": "code_result[(len(settings[\"tests\"])+6)..len(code_result)]"}, {"name": "main_error", "description": "

Show STDOUT if allowed.

\n

Check the student's code runs on its own. Fail if there was an error, and show STDERR if allowed.

", "definition": "assert(main_stdout=\"\" or not settings[\"show_stdout\"],\n feedback(\"Your code produced this output:
{escape_html(main_stdout)}
\")\n);\nassert(main_result[\"success\"],\n if(settings[\"show_stderr\"],\n fail(\"\"\"There was an error in your code:
{escape_html(main_result[\"stderr\"])}
\"\"\")\n ,\n fail(\"There was an error in your code.\")\n )\n)"}, {"name": "marking_test_feedback", "description": "

Feedback on the marking tests. For each test, if the test was passed then add the corresponding amount of credit. If there was an error, show the error.

", "definition": "map(\n let(\n [name,weight,code], test,\n header, \"Test: {name} \",\n if(r[\"success\"],\n let(\n result, r[\"result\"],\n max_credit, weight/total_weight,\n credit, if(result isa \"number\", result, award(1,result)),\n switch(\n credit=0, negative_feedback(header+\"was not passed.\"),\n credit=1, add_credit(max_credit, header+\"was passed.\"),\n add_credit(credit*max_credit, header+\"was partially passed.\")\n )\n )\n ,\n if(settings[\"show_marking_errors\"],\n negative_feedback(\"\"\"There was an error:
{escape_html(r[\"stderr\"])}
\"\"\")\n ,\n negative_feedback(header+\"was not passed.\")\n )\n )\n ),\n [test,r],\n zip(settings[\"tests\"],marking_results)\n)"}, {"name": "validation_test_feedback", "description": "

Give feedback on the validation tests. If any of them are not passed, the student's answer is invalid.

", "definition": "map(\n let([name,code], test,\n if(r[\"success\"],\n if(r[\"result\"],\n true\n ,\n fail(\"\"\"Your code failed the test {name}.\"\"\");false\n )\n ,\n fail(\"\"\"There was an error running the test {name}:
{escape_html(r[\"stderr\"])}
\"\"\")\n )\n ),\n [test,r],\n zip(settings[\"validation_tests\"],validation_results)\n)"}, {"name": "total_weight", "description": "

The sum of the weights of the marking tests. Each test's weight is divided by this to produce a proportion of the available credit.

", "definition": "sum(map(weight,[name,weight,code],settings[\"tests\"]))"}, {"name": "pre_submit", "description": "

The code blocks to run.

\n

In order, they are:

\n
    \n
  • 0 - The matplotlib hack preamble (in Python, make sure matplotlib plots are displayed)
  • \n
  • 1 - Set passed-in variables
  • \n
  • 2 - Preamble
  • \n
  • 3 - The student's code
  • \n
  • 4 - Postamble
  • \n
  • 5 - The matplotlib hack postamble
  • \n
  • Marking tests
  • \n
  • Validation tests
  • \n
", "definition": "[run_code(code_language,\n [\n matplotlib_preamble,\n variables_as_code(language_synonym(code_language), settings[\"variables\"]),\n render(settings[\"preamble\"]),\n if(trim(settings[\"modifier\"])=\"\", studentAnswer, eval(expression(settings[\"modifier\"]))),\n render(settings[\"postamble\"]),\n matplotlib_postamble\n ]\n +map(code,[name,marks,code],settings[\"tests\"])\n +map(code,[name,code],settings[\"validation_tests\"])\n)]"}, {"name": "code_result", "description": "

The results of the code blocks: a list with an entry corresponding to each block of code.

", "definition": "pre_submit[\"code_result\"]"}, {"name": "main_stdout", "description": "

The stdout from the student's code.

", "definition": "safe(main_result[\"stdout\"])"}, {"name": "code_language", "description": "

The language the code is written in. Either \"pyodide\" (Python) or \"webr\" (R)

", "definition": "settings[\"code_language\"]"}, {"name": "preamble_result", "description": "

The result of running the preamble block.

", "definition": "code_result[2]"}, {"name": "preamble_stderr", "description": "

The STDERR produced by the preamble block.

", "definition": "preamble_result[\"stderr\"]"}, {"name": "postamble_result", "description": "

The result of running the postamble.

", "definition": "code_result[4]"}, {"name": "postamble_stderr", "description": "

The STDERR produced by the postamble block.

", "definition": "postamble_result[\"stderr\"]"}, {"name": "postamble_feedback", "description": "

Show the STDOUT from the postamble, if there is any.

", "definition": "assert(postamble_result[\"stdout\"]=\"\",\n feedback(\n if(settings[\"postamble_feedback_whitespace\"],\n html(\"\"\"
{escape_html(postamble_result[\"stdout\"])}
\"\"\")\n ,\n postamble_result[\"stdout\"]\n )\n )\n);\nassert(postamble_result[\"success\"],\n if(settings[\"show_stderr\"],\n fail(\"\"\"There was an error in the marking routine postamble:
{escape_html(postamble_result[\"stderr\"])}
\"\"\")\n ,\n fail(\"There was an error in the marking routine postamble.\")\n )\n)"}, {"name": "matplotlib_preamble", "description": "

Preamble for a hack to ensure that figures produced by matplotlib in Python are displayed.

\n

This code clears the matplotlib output, if matplotlib has been loaded.

", "definition": "if(code_language=\"pyodide\",\n safe(\"\"\"\nimport sys\nif 'matplotlib' in sys.modules:\n import matplotlib.pyplot as plt\n plt.clf() \n\"\"\"),\n \"\"\n)"}, {"name": "matplotlib_postamble", "description": "

A hack to show any figures produced with matplotlib in the stdout.

", "definition": "switch(\ncode_language=\"pyodide\",\n safe(\"\"\"\nimport sys\nif 'matplotlib' in sys.modules:\n import matplotlib.pyplot as plt\n fig = plt.gcf()\n if fig.get_axes():\n fig.savefig(sys.stdout, format='svg')\n\"\"\"),\n \"\"\n)"}, {"name": "matplotlib_result", "description": "

The result of running the matplotlib hack.

", "definition": "code_result[5]"}, {"name": "matplotlib_feedback", "description": "

Feedback from the matplotlib hack: if a figure is produced, it's displayed as SVG here.

", "definition": "switch(\ncode_language=\"pyodide\",\n assert(matplotlib_result[\"stdout\"]=\"\",\n feedback(matplotlib_result[\"stdout\"])\n ),\n \"\"\n)\n\n"}, {"name": "images", "description": "

Any images produced by the code blocks.

", "definition": "flatten(map(\n get(r,\"images\",[]),\n r,\n code_result\n))"}, {"name": "show_images", "description": "

Show the images produced by the code.

", "definition": "assert(len(images)=0 or not settings[\"show_stdout\"],\n feedback(\"Your code produced the following {pluralise(len(images),'image','images')}:\");\n map(\n feedback(html(x)),\n x,\n images\n )\n)"}], "settings": [{"name": "show_input_hint", "label": "Show the input hint?", "help_url": "", "hint": "", "input_type": "checkbox", "default_value": true}, {"name": "code_language", "label": "Code language", "help_url": "", "hint": "The language that the student's code will be written in.", "input_type": "dropdown", "default_value": "pyodide", "choices": [{"value": "pyodide", "label": "Python"}, {"value": "webr", "label": "R"}]}, {"name": "correct_answer", "label": "Correct answer", "help_url": "", "hint": "A correct answer to the part.", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "correct_answer_subvars", "label": "Substitute question variables into the correct answer?", "help_url": "", "hint": "If ticked, then JME expressions between curly braces will be evaluated and substituted into the correct answer.

If not ticked, then the correct answer will be displayed exactly as it is.", "input_type": "checkbox", "default_value": true}, {"name": "show_stdout", "label": "Show stdout?", "help_url": "", "hint": "If ticked, the STDOUT produced after running the student's code will be shown in the feedback.", "input_type": "checkbox", "default_value": true}, {"name": "show_stderr", "label": "Show stderr?", "help_url": "", "hint": "If ticked, the STDERR produced after running the student's code will be shown in the feedback.", "input_type": "checkbox", "default_value": true}, {"name": "show_marking_errors", "label": "Show errors produced by marking tests?", "help_url": "", "hint": "", "input_type": "checkbox", "default_value": false}, {"name": "placeholder", "label": "Placeholder", "help_url": "", "hint": "Initial text for the code editor", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "modifier", "label": "Student code modifier", "help_url": "", "hint": "JME expression to modify the student's submitted code before being passed to the marking template. The student's code is available as the string variable studentAnswer.", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "preamble", "label": "Preamble", "help_url": "", "hint": "This code is run before the student's code. Define anything that the student's code or your tests need.", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "postamble", "label": "Postamble", "help_url": "", "hint": "This code is run after the student's code but before the validation and unit tests.", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "postamble_feedback_whitespace", "label": "Format postamble output as code?", "help_url": "", "hint": "If ticked, any output produced by the postamble will be formatted in monospace font, with whitespace preserved. If not ticked, it'll be presented as prose text or HTML.", "input_type": "checkbox", "default_value": false}, {"name": "tests", "label": "Marking tests", "help_url": "", "hint": "A list of tests used to mark the student's answer.
Each item is a list with three values:
\n
    \n
  • The name of the test, shown to the student above any feedback.
  • \n
  • The proportion of the credit available for the part to award if this test is passed.
  • \n
  • The code to run.
  • \n
", "input_type": "code", "default_value": "[\n [\"Test 1\", 1, \"True\"]\n]", "evaluate": true}, {"name": "validation_tests", "label": "Validation tests", "help_url": "", "hint": "

A list of tests used to validate that the student's code is acceptable.
Each item is a list with two string values:

\n
    \n
  • A name which will be shown to the student if the test fails.
  • \n
  • The code to run.
  • \n
", "input_type": "code", "default_value": "[\n [\"arithmetic works\", \"1+1 == 2\"]\n]", "evaluate": true}, {"name": "variables", "label": "Variables to include in code", "help_url": "", "hint": "Give a dictionary mapping variable names to their values. These variables will be available in the code that is run.", "input_type": "code", "default_value": "dict()", "evaluate": true}], "public_availability": "always", "published": true, "extensions": ["programming"]}], "resources": [], "navigation": {"allowregen": true, "showfrontpage": false, "preventleave": false, "typeendtoleave": false}, "contributors": [{"name": "Christian Lawson-Perfect", "profile_url": "https://numbas.mathcentre.ac.uk/accounts/profile/7/"}, {"name": "Toby Wood", "profile_url": "https://numbas.mathcentre.ac.uk/accounts/profile/400/"}], "tags": [], "metadata": {"description": "

Shows how to use JSXGraph to make a sine graph with amplitude, frequency and phase controlled by sliders.

", "licence": "Creative Commons Attribution 4.0 International"}, "statement": "

Consider the eigenvalue problem

\n

\\[\\dfrac{\\mathrm{d}^2y}{\\mathrm{d}x^2} - 2\\dfrac{\\mathrm{d}y}{\\mathrm{d}x} + \\lambda y = 0, \\qquad \\mbox{for $\\;0 < x < \\pi$},\\]

\n

with the boundary conditions

\n

\\[y(0) = 0, \\quad y(\\pi) = 0.\\]

\n

Our goal is to identify the eigenvalues, i.e. the values of $\\lambda$ for which this problem has non-zero solutions.

", "advice": "

The first boundary condition, $y(0) = 0$, requires that $\\phi = 0$.  The other boundary condition, $y(\\pi) = 0$, is then met for $\\lambda = 1 + n^2 = 2, 5, 10, \\ldots$

", "rulesets": {}, "builtin_constants": {"e": true, "pi,\u03c0": true, "i": true}, "constants": [], "variables": {"eigenfunction": {"name": "eigenfunction", "group": "Ungrouped variables", "definition": "jessiecode(800,800,[-0.5,6,3.5,-6], safe(\"\"\"\nxaxis = axis([0,0],[1,0]) <>;\n\namplitude = slider([1, 4.5], [3, 4.5], [0,1,1]) <>;\neigenvalue = slider([1, 2.5], [3, 2.5], [0,1,10]) <>;\nB = point(0, 0) << color: function(){if(abs(sin(PI*V(phase))) < 0.01){return 'red';} else {return 'black';};}, face: 'circle', size: 2, name: '', fixed: 'true' >>;\nC = point(PI, 0) << color: function(){if(abs(sin(PI*sqrt(V(eigenvalue) - 1) + PI*V(phase))) < 0.01){return 'red';} else {return 'black';};}, face: 'circle', size: 2, name: '', fixed: 'true' >>;\n\n\"\"\")\n)", "description": "

A plot of the eigenfunction with amplitude, phase shift and eigenvalue controlled by sliders.

", "templateType": "anything", "can_override": false}}, "variablesTest": {"condition": "", "maxRuns": 100}, "ungrouped_variables": ["eigenfunction"], "variable_groups": [], "functions": {}, "preamble": {"js": "", "css": ""}, "parts": [{"type": "mark-code-3", "useCustomName": false, "customName": "", "marks": "0", "scripts": {}, "customMarkingAlgorithm": "mark:\n feedback(\"Here's your figure:\");\n feedback(html(code_result[4][\"stdout\"])) ", "extendBaseMarkingAlgorithm": true, "unitTests": [], "showCorrectAnswer": false, "showFeedbackIcon": false, "variableReplacements": [], "variableReplacementStrategy": "originalfirst", "nextParts": [], "suggestGoingBack": false, "adaptiveMarkingPenalty": 0, "exploreObjective": null, "prompt": "

The general solution of this ordinary differential equation can be expressed as

\n

\\[y = A\\mathrm{e}^x\\sin(\\sqrt{\\lambda-1}\\,x + \\phi),\\]

\n

where $A$ and $\\phi$ are arbitrary constants. This function is plotted below. Use the sliders to find solutions that meet both of the boundary conditions, and hence identify the eigenvalues.

\n

{eigenfunction}

\n

Complete the Python code below to plot the first three eigenfunctions.  If your answer is correct then all three plots should intersect both of the black circles.

", "settings": {"show_input_hint": true, "code_language": "pyodide", "correct_answer": "", "correct_answer_subvars": true, "show_stdout": true, "show_stderr": true, "show_marking_errors": false, "placeholder": "import numpy as np\nimport matplotlib.pyplot as plt\nfig = plt.figure()\n\nx = np.linspace(0,np.pi,101)\nplt.plot([0,np.pi],[0,0],'ok')\n\n# Complete the code below to calculate\n# A, phi and lambda for each value of n.\nfor n in np.arange(3)+1:\n amp = # Code the value of A (the amplitude) here\n phi = # Code the value of phi here\n lam = # Code the value of lambda here\n y = amp*np.exp(x)*np.sin(np.sqrt(lam-1)*x + phi)\n plt.plot(x,y)\n\nplt.legend(['_','$y_1$','$y_2$','$y_3$'])", "modifier": "", "preamble": "import sys\nimport matplotlib\nmatplotlib.use('Agg')", "postamble": "fig.savefig(sys.stdout, format='svg')", "postamble_feedback_whitespace": false, "tests": "[\n [\"Test 1\", 1, \"True\"]\n]", "validation_tests": "[\n [\"arithmetic works\", \"1+1 == 2\"]\n]", "variables": "dict()"}}], "partsMode": "all", "maxMarks": 0, "objectives": [], "penalties": [], "objectiveVisibility": "always", "penaltyVisibility": "always"}, {"name": "Plotting streamlines and pathlines", "extensions": ["programming"], "custom_part_types": [{"source": {"pk": 195, "author": {"name": "Christian Lawson-Perfect", "pk": 7}, "edit_page": "/part_type/195/edit"}, "name": "Code", "short_name": "mark-code-3", "description": "

Mark code provided by the student by running it and a series of validation and marking tests.

\n

The validation tests are used to reject an answer if the student has misunderstood the task, for example if they haven't defined a required variable or function.

\n

Marking tests check properties of the student's code. Each test awards a proportion of the available credit if it is passed.

\n

You can optionally show the student the STDOUT and/or STDERR when running their code.

\n

You can give a preamble and postamble which are run before and after the student's code, and also modify the student's code before running it.

", "help_url": "", "input_widget": "code-editor", "input_options": {"correctAnswer": "if(settings[\"correct_answer_subvars\"],\n render(settings[\"correct_answer\"])\n,\n settings[\"correct_answer\"]\n)", "hint": {"static": false, "value": "\"Write \"+capitalise(language_synonym(settings[\"code_language\"]))+\" code\""}, "language": {"static": false, "value": "language_synonym(settings[\"code_language\"])"}, "placeholder": {"static": false, "value": "if(settings[\"correct_answer_subvars\"],\n render(settings[\"placeholder\"])\n,\n settings[\"placeholder\"]\n)"}, "theme": {"static": true, "value": "textmate"}}, "can_be_gap": true, "can_be_step": true, "marking_script": "mark:\napply(main_error);\napply(show_images);\napply(matplotlib_feedback);\napply(postamble_feedback);\napply(validation_test_feedback);\napply(marking_test_feedback)\n\ninterpreted_answer:\nstudentAnswer\n\nmain_result:\ncode_result[3]\n\nmarking_results:\ncode_result[6..(len(settings[\"tests\"])+6)]\n\nvalidation_results:\ncode_result[(len(settings[\"tests\"])+6)..len(code_result)]\n\nmain_error:\nassert(main_stdout=\"\" or not settings[\"show_stdout\"],\n feedback(\"Your code produced this output:
{escape_html(main_stdout)}
\")\n);\nassert(main_result[\"success\"],\n if(settings[\"show_stderr\"],\n fail(\"\"\"There was an error in your code:
{escape_html(main_result[\"stderr\"])}
\"\"\")\n ,\n fail(\"There was an error in your code.\")\n )\n)\n\nmarking_test_feedback:\nmap(\n let(\n [name,weight,code], test,\n header, \"Test: {name} \",\n if(r[\"success\"],\n let(\n result, r[\"result\"],\n max_credit, weight/total_weight,\n credit, if(result isa \"number\", result, award(1,result)),\n switch(\n credit=0, negative_feedback(header+\"was not passed.\"),\n credit=1, add_credit(max_credit, header+\"was passed.\"),\n add_credit(credit*max_credit, header+\"was partially passed.\")\n )\n )\n ,\n if(settings[\"show_marking_errors\"],\n negative_feedback(\"\"\"There was an error:
{escape_html(r[\"stderr\"])}
\"\"\")\n ,\n negative_feedback(header+\"was not passed.\")\n )\n )\n ),\n [test,r],\n zip(settings[\"tests\"],marking_results)\n)\n\nvalidation_test_feedback:\nmap(\n let([name,code], test,\n if(r[\"success\"],\n if(r[\"result\"],\n true\n ,\n fail(\"\"\"Your code failed the test {name}.\"\"\");false\n )\n ,\n fail(\"\"\"There was an error running the test {name}:
{escape_html(r[\"stderr\"])}
\"\"\")\n )\n ),\n [test,r],\n zip(settings[\"validation_tests\"],validation_results)\n)\n\ntotal_weight:\nsum(map(weight,[name,weight,code],settings[\"tests\"]))\n\npre_submit:\n[run_code(code_language,\n [\n matplotlib_preamble,\n variables_as_code(language_synonym(code_language), settings[\"variables\"]),\n render(settings[\"preamble\"]),\n if(trim(settings[\"modifier\"])=\"\", studentAnswer, eval(expression(settings[\"modifier\"]))),\n render(settings[\"postamble\"]),\n matplotlib_postamble\n ]\n +map(code,[name,marks,code],settings[\"tests\"])\n +map(code,[name,code],settings[\"validation_tests\"])\n)]\n\ncode_result:\npre_submit[\"code_result\"]\n\nmain_stdout:\nsafe(main_result[\"stdout\"])\n\ncode_language:\nsettings[\"code_language\"]\n\npreamble_result:\ncode_result[2]\n\npreamble_stderr:\npreamble_result[\"stderr\"]\n\npostamble_result:\ncode_result[4]\n\npostamble_stderr:\npostamble_result[\"stderr\"]\n\npostamble_feedback:\nassert(postamble_result[\"stdout\"]=\"\",\n feedback(\n if(settings[\"postamble_feedback_whitespace\"],\n html(\"\"\"
{escape_html(postamble_result[\"stdout\"])}
\"\"\")\n ,\n postamble_result[\"stdout\"]\n )\n )\n);\nassert(postamble_result[\"success\"],\n if(settings[\"show_stderr\"],\n fail(\"\"\"There was an error in the marking routine postamble:
{escape_html(postamble_result[\"stderr\"])}
\"\"\")\n ,\n fail(\"There was an error in the marking routine postamble.\")\n )\n)\n\nmatplotlib_preamble:\nif(code_language=\"pyodide\",\n safe(\"\"\"\nimport sys\nif 'matplotlib' in sys.modules:\n import matplotlib.pyplot as plt\n plt.clf() \n\"\"\"),\n \"\"\n)\n\nmatplotlib_postamble:\nswitch(\ncode_language=\"pyodide\",\n safe(\"\"\"\nimport sys\nif 'matplotlib' in sys.modules:\n import matplotlib.pyplot as plt\n fig = plt.gcf()\n if fig.get_axes():\n fig.savefig(sys.stdout, format='svg')\n\"\"\"),\n \"\"\n)\n\nmatplotlib_result:\ncode_result[5]\n\nmatplotlib_feedback:\nswitch(\ncode_language=\"pyodide\",\n assert(matplotlib_result[\"stdout\"]=\"\",\n feedback(matplotlib_result[\"stdout\"])\n ),\n \"\"\n)\n\n\n\nimages:\nflatten(map(\n get(r,\"images\",[]),\n r,\n code_result\n))\n\nshow_images:\nassert(len(images)=0 or not settings[\"show_stdout\"],\n feedback(\"Your code produced the following {pluralise(len(images),'image','images')}:\");\n map(\n feedback(html(x)),\n x,\n images\n )\n)", "marking_notes": [{"name": "mark", "description": "This is the main marking note. It should award credit and provide feedback based on the student's answer.", "definition": "apply(main_error);\napply(show_images);\napply(matplotlib_feedback);\napply(postamble_feedback);\napply(validation_test_feedback);\napply(marking_test_feedback)"}, {"name": "interpreted_answer", "description": "A value representing the student's answer to this part.", "definition": "studentAnswer"}, {"name": "main_result", "description": "

The result of running the student's code and the preamble, without any tests.

\n

Normally used to detect errors in the student's code.

", "definition": "code_result[3]"}, {"name": "marking_results", "description": "

The results of running the marking tests.

", "definition": "code_result[6..(len(settings[\"tests\"])+6)]"}, {"name": "validation_results", "description": "

The results of running the validation tests.

", "definition": "code_result[(len(settings[\"tests\"])+6)..len(code_result)]"}, {"name": "main_error", "description": "

Show STDOUT if allowed.

\n

Check the student's code runs on its own. Fail if there was an error, and show STDERR if allowed.

", "definition": "assert(main_stdout=\"\" or not settings[\"show_stdout\"],\n feedback(\"Your code produced this output:
{escape_html(main_stdout)}
\")\n);\nassert(main_result[\"success\"],\n if(settings[\"show_stderr\"],\n fail(\"\"\"There was an error in your code:
{escape_html(main_result[\"stderr\"])}
\"\"\")\n ,\n fail(\"There was an error in your code.\")\n )\n)"}, {"name": "marking_test_feedback", "description": "

Feedback on the marking tests. For each test, if the test was passed then add the corresponding amount of credit. If there was an error, show the error.

", "definition": "map(\n let(\n [name,weight,code], test,\n header, \"Test: {name} \",\n if(r[\"success\"],\n let(\n result, r[\"result\"],\n max_credit, weight/total_weight,\n credit, if(result isa \"number\", result, award(1,result)),\n switch(\n credit=0, negative_feedback(header+\"was not passed.\"),\n credit=1, add_credit(max_credit, header+\"was passed.\"),\n add_credit(credit*max_credit, header+\"was partially passed.\")\n )\n )\n ,\n if(settings[\"show_marking_errors\"],\n negative_feedback(\"\"\"There was an error:
{escape_html(r[\"stderr\"])}
\"\"\")\n ,\n negative_feedback(header+\"was not passed.\")\n )\n )\n ),\n [test,r],\n zip(settings[\"tests\"],marking_results)\n)"}, {"name": "validation_test_feedback", "description": "

Give feedback on the validation tests. If any of them are not passed, the student's answer is invalid.

", "definition": "map(\n let([name,code], test,\n if(r[\"success\"],\n if(r[\"result\"],\n true\n ,\n fail(\"\"\"Your code failed the test {name}.\"\"\");false\n )\n ,\n fail(\"\"\"There was an error running the test {name}:
{escape_html(r[\"stderr\"])}
\"\"\")\n )\n ),\n [test,r],\n zip(settings[\"validation_tests\"],validation_results)\n)"}, {"name": "total_weight", "description": "

The sum of the weights of the marking tests. Each test's weight is divided by this to produce a proportion of the available credit.

", "definition": "sum(map(weight,[name,weight,code],settings[\"tests\"]))"}, {"name": "pre_submit", "description": "

The code blocks to run.

\n

In order, they are:

\n
    \n
  • 0 - The matplotlib hack preamble (in Python, make sure matplotlib plots are displayed)
  • \n
  • 1 - Set passed-in variables
  • \n
  • 2 - Preamble
  • \n
  • 3 - The student's code
  • \n
  • 4 - Postamble
  • \n
  • 5 - The matplotlib hack postamble
  • \n
  • Marking tests
  • \n
  • Validation tests
  • \n
", "definition": "[run_code(code_language,\n [\n matplotlib_preamble,\n variables_as_code(language_synonym(code_language), settings[\"variables\"]),\n render(settings[\"preamble\"]),\n if(trim(settings[\"modifier\"])=\"\", studentAnswer, eval(expression(settings[\"modifier\"]))),\n render(settings[\"postamble\"]),\n matplotlib_postamble\n ]\n +map(code,[name,marks,code],settings[\"tests\"])\n +map(code,[name,code],settings[\"validation_tests\"])\n)]"}, {"name": "code_result", "description": "

The results of the code blocks: a list with an entry corresponding to each block of code.

", "definition": "pre_submit[\"code_result\"]"}, {"name": "main_stdout", "description": "

The stdout from the student's code.

", "definition": "safe(main_result[\"stdout\"])"}, {"name": "code_language", "description": "

The language the code is written in. Either \"pyodide\" (Python) or \"webr\" (R)

", "definition": "settings[\"code_language\"]"}, {"name": "preamble_result", "description": "

The result of running the preamble block.

", "definition": "code_result[2]"}, {"name": "preamble_stderr", "description": "

The STDERR produced by the preamble block.

", "definition": "preamble_result[\"stderr\"]"}, {"name": "postamble_result", "description": "

The result of running the postamble.

", "definition": "code_result[4]"}, {"name": "postamble_stderr", "description": "

The STDERR produced by the postamble block.

", "definition": "postamble_result[\"stderr\"]"}, {"name": "postamble_feedback", "description": "

Show the STDOUT from the postamble, if there is any.

", "definition": "assert(postamble_result[\"stdout\"]=\"\",\n feedback(\n if(settings[\"postamble_feedback_whitespace\"],\n html(\"\"\"
{escape_html(postamble_result[\"stdout\"])}
\"\"\")\n ,\n postamble_result[\"stdout\"]\n )\n )\n);\nassert(postamble_result[\"success\"],\n if(settings[\"show_stderr\"],\n fail(\"\"\"There was an error in the marking routine postamble:
{escape_html(postamble_result[\"stderr\"])}
\"\"\")\n ,\n fail(\"There was an error in the marking routine postamble.\")\n )\n)"}, {"name": "matplotlib_preamble", "description": "

Preamble for a hack to ensure that figures produced by matplotlib in Python are displayed.

\n

This code clears the matplotlib output, if matplotlib has been loaded.

", "definition": "if(code_language=\"pyodide\",\n safe(\"\"\"\nimport sys\nif 'matplotlib' in sys.modules:\n import matplotlib.pyplot as plt\n plt.clf() \n\"\"\"),\n \"\"\n)"}, {"name": "matplotlib_postamble", "description": "

A hack to show any figures produced with matplotlib in the stdout.

", "definition": "switch(\ncode_language=\"pyodide\",\n safe(\"\"\"\nimport sys\nif 'matplotlib' in sys.modules:\n import matplotlib.pyplot as plt\n fig = plt.gcf()\n if fig.get_axes():\n fig.savefig(sys.stdout, format='svg')\n\"\"\"),\n \"\"\n)"}, {"name": "matplotlib_result", "description": "

The result of running the matplotlib hack.

", "definition": "code_result[5]"}, {"name": "matplotlib_feedback", "description": "

Feedback from the matplotlib hack: if a figure is produced, it's displayed as SVG here.

", "definition": "switch(\ncode_language=\"pyodide\",\n assert(matplotlib_result[\"stdout\"]=\"\",\n feedback(matplotlib_result[\"stdout\"])\n ),\n \"\"\n)\n\n"}, {"name": "images", "description": "

Any images produced by the code blocks.

", "definition": "flatten(map(\n get(r,\"images\",[]),\n r,\n code_result\n))"}, {"name": "show_images", "description": "

Show the images produced by the code.

", "definition": "assert(len(images)=0 or not settings[\"show_stdout\"],\n feedback(\"Your code produced the following {pluralise(len(images),'image','images')}:\");\n map(\n feedback(html(x)),\n x,\n images\n )\n)"}], "settings": [{"name": "show_input_hint", "label": "Show the input hint?", "help_url": "", "hint": "", "input_type": "checkbox", "default_value": true}, {"name": "code_language", "label": "Code language", "help_url": "", "hint": "The language that the student's code will be written in.", "input_type": "dropdown", "default_value": "pyodide", "choices": [{"value": "pyodide", "label": "Python"}, {"value": "webr", "label": "R"}]}, {"name": "correct_answer", "label": "Correct answer", "help_url": "", "hint": "A correct answer to the part.", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "correct_answer_subvars", "label": "Substitute question variables into the correct answer?", "help_url": "", "hint": "If ticked, then JME expressions between curly braces will be evaluated and substituted into the correct answer.

If not ticked, then the correct answer will be displayed exactly as it is.", "input_type": "checkbox", "default_value": true}, {"name": "show_stdout", "label": "Show stdout?", "help_url": "", "hint": "If ticked, the STDOUT produced after running the student's code will be shown in the feedback.", "input_type": "checkbox", "default_value": true}, {"name": "show_stderr", "label": "Show stderr?", "help_url": "", "hint": "If ticked, the STDERR produced after running the student's code will be shown in the feedback.", "input_type": "checkbox", "default_value": true}, {"name": "show_marking_errors", "label": "Show errors produced by marking tests?", "help_url": "", "hint": "", "input_type": "checkbox", "default_value": false}, {"name": "placeholder", "label": "Placeholder", "help_url": "", "hint": "Initial text for the code editor", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "modifier", "label": "Student code modifier", "help_url": "", "hint": "JME expression to modify the student's submitted code before being passed to the marking template. The student's code is available as the string variable studentAnswer.", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "preamble", "label": "Preamble", "help_url": "", "hint": "This code is run before the student's code. Define anything that the student's code or your tests need.", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "postamble", "label": "Postamble", "help_url": "", "hint": "This code is run after the student's code but before the validation and unit tests.", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "postamble_feedback_whitespace", "label": "Format postamble output as code?", "help_url": "", "hint": "If ticked, any output produced by the postamble will be formatted in monospace font, with whitespace preserved. If not ticked, it'll be presented as prose text or HTML.", "input_type": "checkbox", "default_value": false}, {"name": "tests", "label": "Marking tests", "help_url": "", "hint": "A list of tests used to mark the student's answer.
Each item is a list with three values:
\n
    \n
  • The name of the test, shown to the student above any feedback.
  • \n
  • The proportion of the credit available for the part to award if this test is passed.
  • \n
  • The code to run.
  • \n
", "input_type": "code", "default_value": "[\n [\"Test 1\", 1, \"True\"]\n]", "evaluate": true}, {"name": "validation_tests", "label": "Validation tests", "help_url": "", "hint": "

A list of tests used to validate that the student's code is acceptable.
Each item is a list with two string values:

\n
    \n
  • A name which will be shown to the student if the test fails.
  • \n
  • The code to run.
  • \n
", "input_type": "code", "default_value": "[\n [\"arithmetic works\", \"1+1 == 2\"]\n]", "evaluate": true}, {"name": "variables", "label": "Variables to include in code", "help_url": "", "hint": "Give a dictionary mapping variable names to their values. These variables will be available in the code that is run.", "input_type": "code", "default_value": "dict()", "evaluate": true}], "public_availability": "always", "published": true, "extensions": ["programming"]}], "resources": [], "navigation": {"allowregen": true, "showfrontpage": false, "preventleave": false, "typeendtoleave": false}, "contributors": [{"name": "Christian Lawson-Perfect", "profile_url": "https://numbas.mathcentre.ac.uk/accounts/profile/7/"}, {"name": "Chris Graham", "profile_url": "https://numbas.mathcentre.ac.uk/accounts/profile/369/"}, {"name": "Toby Wood", "profile_url": "https://numbas.mathcentre.ac.uk/accounts/profile/400/"}, {"name": "George Stagg", "profile_url": "https://numbas.mathcentre.ac.uk/accounts/profile/930/"}], "tags": [], "metadata": {"description": "

Edit the Python code to plot the stream and pathlines of a 2D flow.

", "licence": "Creative Commons Attribution 4.0 International"}, "statement": "", "advice": "

Now you can try plotting other flows, by changing the definitions of u_x and u_y.

", "rulesets": {}, "builtin_constants": {"e": true, "pi,\u03c0": true, "i": true}, "constants": [], "variables": {"python_preamble": {"name": "python_preamble", "group": "Ungrouped variables", "definition": "safe(\"import matplotlib.pyplot as plt\\nfig = plt.figure()\")", "description": "", "templateType": "long plain string", "can_override": false}}, "variablesTest": {"condition": "", "maxRuns": 100}, "ungrouped_variables": ["python_preamble"], "variable_groups": [], "functions": {"r_load_files": {"parameters": [["files", "list of string"]], "type": "promise", "language": "javascript", "definition": "const mime_types = {\n '.pdf': 'application/pdf',\n '.svg': 'image/svg+xml'\n}\nreturn new Numbas.jme.types.TPromise(Numbas.extensions.programming.language_runners['webr'].load_webR().then(async (webR) => {\n var promises = [];\n files.forEach(filename => {\n promises.push(new Promise((resolve,reject) => {\n setTimeout(async function() {\n try {\n const buf = await webR.getFileData(filename);\n const extension = filename.match(/\\.[^.]*$/)[0];\n const mime_type = mime_types[extension] || 'text/plain';\n var blob = new Blob([buf], {type: mime_type});\n if(mime_type == 'text/plain' || mime_type == 'image/svg+xml') {\n const text = await blob.text();\n resolve({exists: true, text: text, mime_type});\n } else {\n resolve({exists: true, blob: URL.createObjectURL(blob), mime_type});\n }\n } catch(err) {\n resolve({exists: false, error: err.message});\n }\n },10);\n }));\n });\n const results = await Promise.all(promises);\n var o = {};\n results.forEach((value,i) => { o[files[i]] = jme.wrapValue(value); });\n return {\n r_files: new Numbas.jme.types.TDict(o)\n }\n}));"}, "show_pdf": {"parameters": [["url", "string"]], "type": "html", "language": "jme", "definition": "html(\"\"\"\"\"\")"}, "show_svg": {"parameters": [["text", "string"]], "type": "html", "language": "jme", "definition": "html(text)"}, "r_load_package": {"parameters": [["name", "string"]], "type": "anything", "language": "javascript", "definition": "return new Numbas.jme.types.TPromise(Numbas.extensions.programming.language_runners['webr'].load_webR().then(async (webR) => {\n await webR.loadPackage(name);\n return {};\n}));"}}, "preamble": {"js": "Numbas.extensions.programming.preload('pyodide');", "css": ".part.type-mark-code-3 .feedbackMessages {\n max-width: none;\n max-height: none;\n}\n\n.svglite {\n max-width: 100%;\n height: auto;\n}\n"}, "parts": [{"type": "mark-code-3", "useCustomName": false, "customName": "", "marks": "0", "scripts": {}, "customMarkingAlgorithm": "mark:\n feedback(\"Here's your figure:\");\n feedback(html(code_result[4][\"stdout\"])) ", "extendBaseMarkingAlgorithm": true, "unitTests": [], "showCorrectAnswer": false, "showFeedbackIcon": false, "variableReplacements": [], "variableReplacementStrategy": "originalfirst", "nextParts": [], "suggestGoingBack": false, "adaptiveMarkingPenalty": 0, "exploreObjective": null, "prompt": "

A figure, called fig, has already been created as follows:

\n

{code_block(python_preamble,\"python\")}

\n

Now we'll plot some streamlines and pathlines for a particular two-dimensional flow in this figure.

\n

The code below takes the velocity field to be

\n

$\\mathbf{u} = \\bigl(u_x(x,y,t),\\ u_y(x,y,t)\\bigr) = (xt+1,\\ yt+1)$

\n

but you can change this to whatever flow you want to plot.

", "settings": {"show_input_hint": true, "code_language": "pyodide", "correct_answer": "", "correct_answer_subvars": true, "show_stdout": true, "show_stderr": true, "show_marking_errors": false, "placeholder": "# We'll need to use numpy arrays\nimport numpy as np\n\n# Set the size of the region to be plotted\nx_lims = [-1,1]\ny_lims = [-1,1]\n\nt0 = 0 # The (initial) time for the lines to be plotted\nline_length = 1 # The \"length\" (in time units) of each line\nstep = 0.01 # We'll plot the lines in discrete steps.\n # Reducing this quantity will make the lines more accurate,\n # but will take longer to run.\n\n# Where should we start drawing the streamlines and pathlines?\n# We'll draw 15 lines with random initial x & y coordinates:\nx0 = np.random.uniform(*x_lims,15)\ny0 = np.random.uniform(*y_lims,15)\n\n# Now specify the two components of the flow velocity\ndef u_x(x,y,t):\n return x*t + 1\n\ndef u_y(x,y,t):\n return y*t + 1\n\n# Create two subplots within our figure,\n# and mark the start of each line with a circle.\n(left, right) = fig.subplots(1,2)\nleft.title.set_text(\"streamlines at $t=$\"+str(t0))\nright.title.set_text(\"pathlines starting at $t=$\"+str(t0))\nleft.axis(x_lims+y_lims)\nright.axis(x_lims+y_lims)\nleft.plot(x0,y0,'ok')\nright.plot(x0,y0,'ok')\n\n\n# Plot the streamlines in the left-hand plot\nx_old = x0\ny_old = y0\nlength = 0\nwhile (length < line_length):\n # Find the next point on the line\n x_new = x_old + step * u_x(x_old,y_old,t0)\n y_new = y_old + step * u_y(x_old,y_old,t0)\n length = length + step\n # Draw a straight line from the old coordinates to the new ones\n left.plot([x_old,x_new],[y_old,y_new],'b')\n x_old = x_new\n y_old = y_new\n# Add arrowheads to the end of each line\nleft.quiver(x_new,y_new,u_x(x_new,y_new,t0),u_y(x_new,y_new,t0))\n\n# Plot the pathlines in the right-hand plot\nx_old = x0\ny_old = y0\nt = t0\nlength = 0\nwhile (length < line_length):\n # Find the next point on the line\n x_new = x_old + step * u_x(x_old,y_old,t)\n y_new = y_old + step * u_y(x_old,y_old,t)\n t = t + step # Unlike with streamlines, we need to keep track of time\n length = length + step\n # Draw a straight line from the old coordinates to the new ones\n right.plot([x_old,x_new],[y_old,y_new],'r')\n x_old = x_new\n y_old = y_new\n# Add arrowheads to the end of each line\nright.quiver(x_new,y_new,u_x(x_new,y_new,t),u_y(x_new,y_new,t))", "modifier": "", "preamble": "import sys\nimport matplotlib\n\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfig = plt.figure(figsize=(9,4))\n#fig.savefig(sys.stdout, format='svg')", "postamble": "fig.savefig(sys.stdout, format='svg')", "postamble_feedback_whitespace": false, "tests": "[\n [\"Test 1\", 1, \"True\"]\n]", "validation_tests": "[\n [\"arithmetic works\", \"1+1 == 2\"]\n]", "variables": "dict()"}}], "partsMode": "all", "maxMarks": 0, "objectives": [], "penalties": [], "objectiveVisibility": "always", "penaltyVisibility": "always"}]}], "allowPrinting": true, "navigation": {"allowregen": true, "reverse": true, "browse": true, "allowsteps": true, "showfrontpage": false, "showresultspage": "never", "navigatemode": "menu", "onleave": {"action": "none", "message": ""}, "preventleave": false, "typeendtoleave": false, "startpassword": "", "allowAttemptDownload": false, "downloadEncryptionKey": ""}, "timing": {"allowPause": true, "timeout": {"action": "none", "message": ""}, "timedwarning": {"action": "none", "message": ""}}, "feedback": {"showactualmark": true, "showtotalmark": true, "showanswerstate": true, "allowrevealanswer": true, "advicethreshold": 0, "intro": "

This demo contains some examples of interactive plots illustrating mathematical concepts, supported by Python exercises.

", "end_message": "", "reviewshowscore": true, "reviewshowfeedback": true, "reviewshowexpectedanswer": true, "reviewshowadvice": true, "results_options": {"printquestions": true, "printadvice": true}, "feedbackmessages": []}, "diagnostic": {"knowledge_graph": {"topics": [], "learning_objectives": []}, "script": "diagnosys", "customScript": ""}, "contributors": [{"name": "Toby Wood", "profile_url": "https://numbas.mathcentre.ac.uk/accounts/profile/400/"}], "extensions": ["jsxgraph", "programming"], "custom_part_types": [{"source": {"pk": 195, "author": {"name": "Christian Lawson-Perfect", "pk": 7}, "edit_page": "/part_type/195/edit"}, "name": "Code", "short_name": "mark-code-3", "description": "

Mark code provided by the student by running it and a series of validation and marking tests.

\n

The validation tests are used to reject an answer if the student has misunderstood the task, for example if they haven't defined a required variable or function.

\n

Marking tests check properties of the student's code. Each test awards a proportion of the available credit if it is passed.

\n

You can optionally show the student the STDOUT and/or STDERR when running their code.

\n

You can give a preamble and postamble which are run before and after the student's code, and also modify the student's code before running it.

", "help_url": "", "input_widget": "code-editor", "input_options": {"correctAnswer": "if(settings[\"correct_answer_subvars\"],\n render(settings[\"correct_answer\"])\n,\n settings[\"correct_answer\"]\n)", "hint": {"static": false, "value": "\"Write \"+capitalise(language_synonym(settings[\"code_language\"]))+\" code\""}, "language": {"static": false, "value": "language_synonym(settings[\"code_language\"])"}, "placeholder": {"static": false, "value": "if(settings[\"correct_answer_subvars\"],\n render(settings[\"placeholder\"])\n,\n settings[\"placeholder\"]\n)"}, "theme": {"static": true, "value": "textmate"}}, "can_be_gap": true, "can_be_step": true, "marking_script": "mark:\napply(main_error);\napply(show_images);\napply(matplotlib_feedback);\napply(postamble_feedback);\napply(validation_test_feedback);\napply(marking_test_feedback)\n\ninterpreted_answer:\nstudentAnswer\n\nmain_result:\ncode_result[3]\n\nmarking_results:\ncode_result[6..(len(settings[\"tests\"])+6)]\n\nvalidation_results:\ncode_result[(len(settings[\"tests\"])+6)..len(code_result)]\n\nmain_error:\nassert(main_stdout=\"\" or not settings[\"show_stdout\"],\n feedback(\"Your code produced this output:
{escape_html(main_stdout)}
\")\n);\nassert(main_result[\"success\"],\n if(settings[\"show_stderr\"],\n fail(\"\"\"There was an error in your code:
{escape_html(main_result[\"stderr\"])}
\"\"\")\n ,\n fail(\"There was an error in your code.\")\n )\n)\n\nmarking_test_feedback:\nmap(\n let(\n [name,weight,code], test,\n header, \"Test: {name} \",\n if(r[\"success\"],\n let(\n result, r[\"result\"],\n max_credit, weight/total_weight,\n credit, if(result isa \"number\", result, award(1,result)),\n switch(\n credit=0, negative_feedback(header+\"was not passed.\"),\n credit=1, add_credit(max_credit, header+\"was passed.\"),\n add_credit(credit*max_credit, header+\"was partially passed.\")\n )\n )\n ,\n if(settings[\"show_marking_errors\"],\n negative_feedback(\"\"\"There was an error:
{escape_html(r[\"stderr\"])}
\"\"\")\n ,\n negative_feedback(header+\"was not passed.\")\n )\n )\n ),\n [test,r],\n zip(settings[\"tests\"],marking_results)\n)\n\nvalidation_test_feedback:\nmap(\n let([name,code], test,\n if(r[\"success\"],\n if(r[\"result\"],\n true\n ,\n fail(\"\"\"Your code failed the test {name}.\"\"\");false\n )\n ,\n fail(\"\"\"There was an error running the test {name}:
{escape_html(r[\"stderr\"])}
\"\"\")\n )\n ),\n [test,r],\n zip(settings[\"validation_tests\"],validation_results)\n)\n\ntotal_weight:\nsum(map(weight,[name,weight,code],settings[\"tests\"]))\n\npre_submit:\n[run_code(code_language,\n [\n matplotlib_preamble,\n variables_as_code(language_synonym(code_language), settings[\"variables\"]),\n render(settings[\"preamble\"]),\n if(trim(settings[\"modifier\"])=\"\", studentAnswer, eval(expression(settings[\"modifier\"]))),\n render(settings[\"postamble\"]),\n matplotlib_postamble\n ]\n +map(code,[name,marks,code],settings[\"tests\"])\n +map(code,[name,code],settings[\"validation_tests\"])\n)]\n\ncode_result:\npre_submit[\"code_result\"]\n\nmain_stdout:\nsafe(main_result[\"stdout\"])\n\ncode_language:\nsettings[\"code_language\"]\n\npreamble_result:\ncode_result[2]\n\npreamble_stderr:\npreamble_result[\"stderr\"]\n\npostamble_result:\ncode_result[4]\n\npostamble_stderr:\npostamble_result[\"stderr\"]\n\npostamble_feedback:\nassert(postamble_result[\"stdout\"]=\"\",\n feedback(\n if(settings[\"postamble_feedback_whitespace\"],\n html(\"\"\"
{escape_html(postamble_result[\"stdout\"])}
\"\"\")\n ,\n postamble_result[\"stdout\"]\n )\n )\n);\nassert(postamble_result[\"success\"],\n if(settings[\"show_stderr\"],\n fail(\"\"\"There was an error in the marking routine postamble:
{escape_html(postamble_result[\"stderr\"])}
\"\"\")\n ,\n fail(\"There was an error in the marking routine postamble.\")\n )\n)\n\nmatplotlib_preamble:\nif(code_language=\"pyodide\",\n safe(\"\"\"\nimport sys\nif 'matplotlib' in sys.modules:\n import matplotlib.pyplot as plt\n plt.clf() \n\"\"\"),\n \"\"\n)\n\nmatplotlib_postamble:\nswitch(\ncode_language=\"pyodide\",\n safe(\"\"\"\nimport sys\nif 'matplotlib' in sys.modules:\n import matplotlib.pyplot as plt\n fig = plt.gcf()\n if fig.get_axes():\n fig.savefig(sys.stdout, format='svg')\n\"\"\"),\n \"\"\n)\n\nmatplotlib_result:\ncode_result[5]\n\nmatplotlib_feedback:\nswitch(\ncode_language=\"pyodide\",\n assert(matplotlib_result[\"stdout\"]=\"\",\n feedback(matplotlib_result[\"stdout\"])\n ),\n \"\"\n)\n\n\n\nimages:\nflatten(map(\n get(r,\"images\",[]),\n r,\n code_result\n))\n\nshow_images:\nassert(len(images)=0 or not settings[\"show_stdout\"],\n feedback(\"Your code produced the following {pluralise(len(images),'image','images')}:\");\n map(\n feedback(html(x)),\n x,\n images\n )\n)", "marking_notes": [{"name": "mark", "description": "This is the main marking note. It should award credit and provide feedback based on the student's answer.", "definition": "apply(main_error);\napply(show_images);\napply(matplotlib_feedback);\napply(postamble_feedback);\napply(validation_test_feedback);\napply(marking_test_feedback)"}, {"name": "interpreted_answer", "description": "A value representing the student's answer to this part.", "definition": "studentAnswer"}, {"name": "main_result", "description": "

The result of running the student's code and the preamble, without any tests.

\n

Normally used to detect errors in the student's code.

", "definition": "code_result[3]"}, {"name": "marking_results", "description": "

The results of running the marking tests.

", "definition": "code_result[6..(len(settings[\"tests\"])+6)]"}, {"name": "validation_results", "description": "

The results of running the validation tests.

", "definition": "code_result[(len(settings[\"tests\"])+6)..len(code_result)]"}, {"name": "main_error", "description": "

Show STDOUT if allowed.

\n

Check the student's code runs on its own. Fail if there was an error, and show STDERR if allowed.

", "definition": "assert(main_stdout=\"\" or not settings[\"show_stdout\"],\n feedback(\"Your code produced this output:
{escape_html(main_stdout)}
\")\n);\nassert(main_result[\"success\"],\n if(settings[\"show_stderr\"],\n fail(\"\"\"There was an error in your code:
{escape_html(main_result[\"stderr\"])}
\"\"\")\n ,\n fail(\"There was an error in your code.\")\n )\n)"}, {"name": "marking_test_feedback", "description": "

Feedback on the marking tests. For each test, if the test was passed then add the corresponding amount of credit. If there was an error, show the error.

", "definition": "map(\n let(\n [name,weight,code], test,\n header, \"Test: {name} \",\n if(r[\"success\"],\n let(\n result, r[\"result\"],\n max_credit, weight/total_weight,\n credit, if(result isa \"number\", result, award(1,result)),\n switch(\n credit=0, negative_feedback(header+\"was not passed.\"),\n credit=1, add_credit(max_credit, header+\"was passed.\"),\n add_credit(credit*max_credit, header+\"was partially passed.\")\n )\n )\n ,\n if(settings[\"show_marking_errors\"],\n negative_feedback(\"\"\"There was an error:
{escape_html(r[\"stderr\"])}
\"\"\")\n ,\n negative_feedback(header+\"was not passed.\")\n )\n )\n ),\n [test,r],\n zip(settings[\"tests\"],marking_results)\n)"}, {"name": "validation_test_feedback", "description": "

Give feedback on the validation tests. If any of them are not passed, the student's answer is invalid.

", "definition": "map(\n let([name,code], test,\n if(r[\"success\"],\n if(r[\"result\"],\n true\n ,\n fail(\"\"\"Your code failed the test {name}.\"\"\");false\n )\n ,\n fail(\"\"\"There was an error running the test {name}:
{escape_html(r[\"stderr\"])}
\"\"\")\n )\n ),\n [test,r],\n zip(settings[\"validation_tests\"],validation_results)\n)"}, {"name": "total_weight", "description": "

The sum of the weights of the marking tests. Each test's weight is divided by this to produce a proportion of the available credit.

", "definition": "sum(map(weight,[name,weight,code],settings[\"tests\"]))"}, {"name": "pre_submit", "description": "

The code blocks to run.

\n

In order, they are:

\n
    \n
  • 0 - The matplotlib hack preamble (in Python, make sure matplotlib plots are displayed)
  • \n
  • 1 - Set passed-in variables
  • \n
  • 2 - Preamble
  • \n
  • 3 - The student's code
  • \n
  • 4 - Postamble
  • \n
  • 5 - The matplotlib hack postamble
  • \n
  • Marking tests
  • \n
  • Validation tests
  • \n
", "definition": "[run_code(code_language,\n [\n matplotlib_preamble,\n variables_as_code(language_synonym(code_language), settings[\"variables\"]),\n render(settings[\"preamble\"]),\n if(trim(settings[\"modifier\"])=\"\", studentAnswer, eval(expression(settings[\"modifier\"]))),\n render(settings[\"postamble\"]),\n matplotlib_postamble\n ]\n +map(code,[name,marks,code],settings[\"tests\"])\n +map(code,[name,code],settings[\"validation_tests\"])\n)]"}, {"name": "code_result", "description": "

The results of the code blocks: a list with an entry corresponding to each block of code.

", "definition": "pre_submit[\"code_result\"]"}, {"name": "main_stdout", "description": "

The stdout from the student's code.

", "definition": "safe(main_result[\"stdout\"])"}, {"name": "code_language", "description": "

The language the code is written in. Either \"pyodide\" (Python) or \"webr\" (R)

", "definition": "settings[\"code_language\"]"}, {"name": "preamble_result", "description": "

The result of running the preamble block.

", "definition": "code_result[2]"}, {"name": "preamble_stderr", "description": "

The STDERR produced by the preamble block.

", "definition": "preamble_result[\"stderr\"]"}, {"name": "postamble_result", "description": "

The result of running the postamble.

", "definition": "code_result[4]"}, {"name": "postamble_stderr", "description": "

The STDERR produced by the postamble block.

", "definition": "postamble_result[\"stderr\"]"}, {"name": "postamble_feedback", "description": "

Show the STDOUT from the postamble, if there is any.

", "definition": "assert(postamble_result[\"stdout\"]=\"\",\n feedback(\n if(settings[\"postamble_feedback_whitespace\"],\n html(\"\"\"
{escape_html(postamble_result[\"stdout\"])}
\"\"\")\n ,\n postamble_result[\"stdout\"]\n )\n )\n);\nassert(postamble_result[\"success\"],\n if(settings[\"show_stderr\"],\n fail(\"\"\"There was an error in the marking routine postamble:
{escape_html(postamble_result[\"stderr\"])}
\"\"\")\n ,\n fail(\"There was an error in the marking routine postamble.\")\n )\n)"}, {"name": "matplotlib_preamble", "description": "

Preamble for a hack to ensure that figures produced by matplotlib in Python are displayed.

\n

This code clears the matplotlib output, if matplotlib has been loaded.

", "definition": "if(code_language=\"pyodide\",\n safe(\"\"\"\nimport sys\nif 'matplotlib' in sys.modules:\n import matplotlib.pyplot as plt\n plt.clf() \n\"\"\"),\n \"\"\n)"}, {"name": "matplotlib_postamble", "description": "

A hack to show any figures produced with matplotlib in the stdout.

", "definition": "switch(\ncode_language=\"pyodide\",\n safe(\"\"\"\nimport sys\nif 'matplotlib' in sys.modules:\n import matplotlib.pyplot as plt\n fig = plt.gcf()\n if fig.get_axes():\n fig.savefig(sys.stdout, format='svg')\n\"\"\"),\n \"\"\n)"}, {"name": "matplotlib_result", "description": "

The result of running the matplotlib hack.

", "definition": "code_result[5]"}, {"name": "matplotlib_feedback", "description": "

Feedback from the matplotlib hack: if a figure is produced, it's displayed as SVG here.

", "definition": "switch(\ncode_language=\"pyodide\",\n assert(matplotlib_result[\"stdout\"]=\"\",\n feedback(matplotlib_result[\"stdout\"])\n ),\n \"\"\n)\n\n"}, {"name": "images", "description": "

Any images produced by the code blocks.

", "definition": "flatten(map(\n get(r,\"images\",[]),\n r,\n code_result\n))"}, {"name": "show_images", "description": "

Show the images produced by the code.

", "definition": "assert(len(images)=0 or not settings[\"show_stdout\"],\n feedback(\"Your code produced the following {pluralise(len(images),'image','images')}:\");\n map(\n feedback(html(x)),\n x,\n images\n )\n)"}], "settings": [{"name": "show_input_hint", "label": "Show the input hint?", "help_url": "", "hint": "", "input_type": "checkbox", "default_value": true}, {"name": "code_language", "label": "Code language", "help_url": "", "hint": "The language that the student's code will be written in.", "input_type": "dropdown", "default_value": "pyodide", "choices": [{"value": "pyodide", "label": "Python"}, {"value": "webr", "label": "R"}]}, {"name": "correct_answer", "label": "Correct answer", "help_url": "", "hint": "A correct answer to the part.", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "correct_answer_subvars", "label": "Substitute question variables into the correct answer?", "help_url": "", "hint": "If ticked, then JME expressions between curly braces will be evaluated and substituted into the correct answer.

If not ticked, then the correct answer will be displayed exactly as it is.", "input_type": "checkbox", "default_value": true}, {"name": "show_stdout", "label": "Show stdout?", "help_url": "", "hint": "If ticked, the STDOUT produced after running the student's code will be shown in the feedback.", "input_type": "checkbox", "default_value": true}, {"name": "show_stderr", "label": "Show stderr?", "help_url": "", "hint": "If ticked, the STDERR produced after running the student's code will be shown in the feedback.", "input_type": "checkbox", "default_value": true}, {"name": "show_marking_errors", "label": "Show errors produced by marking tests?", "help_url": "", "hint": "", "input_type": "checkbox", "default_value": false}, {"name": "placeholder", "label": "Placeholder", "help_url": "", "hint": "Initial text for the code editor", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "modifier", "label": "Student code modifier", "help_url": "", "hint": "JME expression to modify the student's submitted code before being passed to the marking template. The student's code is available as the string variable studentAnswer.", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "preamble", "label": "Preamble", "help_url": "", "hint": "This code is run before the student's code. Define anything that the student's code or your tests need.", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "postamble", "label": "Postamble", "help_url": "", "hint": "This code is run after the student's code but before the validation and unit tests.", "input_type": "code", "default_value": "", "evaluate": false}, {"name": "postamble_feedback_whitespace", "label": "Format postamble output as code?", "help_url": "", "hint": "If ticked, any output produced by the postamble will be formatted in monospace font, with whitespace preserved. If not ticked, it'll be presented as prose text or HTML.", "input_type": "checkbox", "default_value": false}, {"name": "tests", "label": "Marking tests", "help_url": "", "hint": "A list of tests used to mark the student's answer.
Each item is a list with three values:
\n
    \n
  • The name of the test, shown to the student above any feedback.
  • \n
  • The proportion of the credit available for the part to award if this test is passed.
  • \n
  • The code to run.
  • \n
", "input_type": "code", "default_value": "[\n [\"Test 1\", 1, \"True\"]\n]", "evaluate": true}, {"name": "validation_tests", "label": "Validation tests", "help_url": "", "hint": "

A list of tests used to validate that the student's code is acceptable.
Each item is a list with two string values:

\n
    \n
  • A name which will be shown to the student if the test fails.
  • \n
  • The code to run.
  • \n
", "input_type": "code", "default_value": "[\n [\"arithmetic works\", \"1+1 == 2\"]\n]", "evaluate": true}, {"name": "variables", "label": "Variables to include in code", "help_url": "", "hint": "Give a dictionary mapping variable names to their values. These variables will be available in the code that is run.", "input_type": "code", "default_value": "dict()", "evaluate": true}], "public_availability": "always", "published": true, "extensions": ["programming"]}], "resources": []}