Difference between revisions of "Sage Embedding"
(Sage Cell from within WebWork problem) |
m (Insert link to AskSage, correct comment about sage.pl) |
||
(47 intermediate revisions by 4 users not shown) | |||
Line 2: | Line 2: | ||
<!-- Header for these sections -- no modification needed --> |
<!-- Header for these sections -- no modification needed --> |
||
+ | <!-- |
||
+ | [[File:GraphicsFilename1.png|300px|thumb|right|Click to enlarge]] |
||
+ | --> |
||
− | <p style="background-color:# |
+ | <p style="background-color:#f9f9f9;border:black solid 1px;padding:3px;"> |
− | + | This PG code shows how to embed a call to the Sage Cell Server from within a problem to insert Sage interacts, graphics, etc. See [[AskSage]] if you only need to run Sage programs. |
|
</p> |
</p> |
||
Line 20: | Line 23: | ||
<!-- Load specialized macro files section --> |
<!-- Load specialized macro files section --> |
||
− | |||
− | <!-- Make this section visible once SageCell applet is created. |
||
<tr valign="top"> |
<tr valign="top"> |
||
<td style="background-color:#ddffdd;border:black 1px dashed;"> |
<td style="background-color:#ddffdd;border:black 1px dashed;"> |
||
<pre> |
<pre> |
||
− | loadMacros("AppletObjects.pl", |
||
+ | DOCUMENT(); |
||
− | "answerHints.pl" |
||
+ | loadMacros( |
||
− | ); |
||
+ | "PGstandard.pl", |
||
+ | "MathObjects.pl", |
||
+ | "sage.pl", |
||
+ | ); |
||
</pre> |
</pre> |
||
+ | </td> |
||
− | </td> |
||
<td style="background-color:#ccffcc;padding:7px;"> |
<td style="background-color:#ccffcc;padding:7px;"> |
||
− | <p> |
||
+ | <p> The sage.pl macro is now part of the standard WeBWorK distribution. |
||
− | In the initialization section, we need to include the macros file <code>AppletObjects.pl</code> |
||
− | and, to provide good feedback, <code>answerHints.pl</code>. |
||
</p> |
</p> |
||
</td> |
</td> |
||
</tr> |
</tr> |
||
− | |||
− | --> |
||
− | |||
<!-- Setup section --> |
<!-- Setup section --> |
||
Line 49: | Line 48: | ||
<td style="background-color:#ffffdd;border:black 1px dashed;"> |
<td style="background-color:#ffffdd;border:black 1px dashed;"> |
||
<pre> |
<pre> |
||
− | + | ############################################### |
|
## |
## |
||
## pg initializations and regular WeBWorK code |
## pg initializations and regular WeBWorK code |
||
− | $ |
+ | $a = random(2,5,1); |
− | $a12 = 1; |
||
− | $a21 = random(-3,-1,1/2); |
||
− | $a22 = non_zero_random(-2,5,1/20); |
||
− | $A = Matrix([[$a11,$a12],[$a21,$a22]]); |
||
− | $A1 = Vector($a11,$a21); |
||
− | $x1 = non_zero_random(-2,2,1/20); |
||
+ | $ansList = List("(-cos(pi*$a)/$a + 1/$a)"); |
||
− | $x1ans = Compute("$x1"); |
||
− | $x2 = non_zero_random(-2,2,1/10); |
||
− | $x2ans = Compute("$x2"); |
||
− | $x = Vector($x1,$x2); |
||
− | |||
− | $b1 = $a11*$x1+$a12*$x2; |
||
− | $b2 = $a21*$x1+$a22*$x2; |
||
− | $b = Vector($b1,$b2); |
||
</pre> |
</pre> |
||
</td> |
</td> |
||
<td style="background-color:#ffffcc;padding:7px;"> |
<td style="background-color:#ffffcc;padding:7px;"> |
||
− | |||
+ | The WeBWorK set up for the problem is the same, but in addition you have |
||
− | </td> |
||
+ | to consider how you will pass the problem parameters into Sage. For example, |
||
− | </tr> |
||
+ | if you want to pass |
||
− | |||
+ | <code>$f = (x-(-2))(x+2)(x+4)</code> it may be best to create two versions of <code>f</code>: |
||
− | <tr> |
||
+ | <code>$f_raw = (x-(-2))*(x+2)*(x+4);</code> to pass to Sage and the math object |
||
− | <td> |
||
+ | <code>$f = Compute("$f_raw");</code> to use in WeBWorK. |
||
− | Next you add a <tt><div></tt> section which contains the actual answer call and Sage code needed to implement the desired function. |
||
<p> |
<p> |
||
− | Notice, the answer call appears near the top between a <div> tag and a <script> tag. Multiple results will need to have multiple answer calls. The numerical value for the size of the "answer blank" is unimportant since this blank will eventually be overwritten by the Sage Cell. |
||
+ | Also, you will need to store the list of correct answers in a variable named $ansList (which is also customizable). |
||
+ | </p> |
||
<p> |
<p> |
||
− | Working Sage code will work verbatim except for a couple of notational changes caused by conflicting syntax between perl and sage. in particular, since "@" is used for tables in perl and for interacts in sage, one will need to replace "@" with "~~@". |
||
+ | Finally, if your final answer is a matrix converted to a list, then do not use extra parenthesis here. Otherwise $ansList will be a List of Lists which is probably a bad thing. |
||
− | <p> |
+ | </p> |
− | Further, perl uses \( and \) to delimit latex and "$" for variables while Sage uses "$' to delimit latex. Therefore, changing each of Sage's latex delimiters to the \( and \) format averts any conflict. |
||
− | <p> |
||
− | An example of they usage is illustrated in the code fragment below. |
||
</td> |
</td> |
||
</tr> |
</tr> |
||
+ | |||
+ | <!-- Initialize the Sage embedding --> |
||
<tr valign="top"> |
<tr valign="top"> |
||
<td style="background-color:#ffffdd;border:black 1px dashed;"> |
<td style="background-color:#ffffdd;border:black 1px dashed;"> |
||
<pre> |
<pre> |
||
− | BEGIN_TEXT |
||
− | <div id="sagecell"> |
||
− | The solution x for Ax=b is given by x1=\{ ans_rule(15) \} and x2=\{ans_rule(15) \}. |
||
− | <script type="text/code"> |
||
+ | $SageCode = <<SAGE_CODE; |
||
− | b = matrix([[$b1],[$b2]]) |
||
+ | Area = integrate(sin($a*x),x,0,pi) |
||
− | bt = b.transpose() |
||
− | A=matrix([[$a11,$a12],[$a21,$a22]]) |
||
− | At =A.transpose() |
||
− | # Notice the correct exact answer is given by x = A\b |
||
+ | record_answer((Area)) # leave out if you return no answer |
||
− | # Finding when a vector b is in the span of other vectors in 2-space |
||
+ | SAGE_CODE |
||
− | <b>~~@interact</b> |
||
+ | </pre> |
||
− | def _(x1=slider(-3,3,1/20,1), x2=slider(-3,3,1/20,1)): |
||
+ | </td> |
||
− | |||
− | G = arrow((0,0),x1*At[0],rgbcolor=(0,0,1)) |
||
− | G += arrow(x1*At[0],x1*At[0]+x2*At[1],rgbcolor=(0,1,0)) |
||
− | G += arrow((0,0),($b1,$b2),rgbcolor=(1,0,0),width=5) |
||
− | G += text("A1",(x1*At[0][0]/2,x1*At[0][1]/2),fontsize=30,color='purple') |
||
− | G += text("A2",(x1*At[0][0]+x2*At[1][0]/2,x1*At[0][1]+x2*At[1][1]/2),fontsize=30,color='purple') |
||
− | G += text("b",($b1/2,$b2/2),fontsize=40,color='purple') |
||
− | G += point(x1*At[0],color='blue',pointsize=40) |
||
− | G += point(($b1,$b2),color='red',pointsize=30) |
||
− | G += point(x1*At[0]+x2*At[1],color='green',pointsize=40) |
||
− | G += point(($b1,$b2),color='red',pointsize=20) |
||
− | # Add fixed originals and dashed modified version of these |
||
− | show(G,frame=False) |
||
+ | <td style="background-color:#ffcccc;padding:7px;"> |
||
+ | <p> |
||
+ | $SageCode = <<SAGE_CODE; |
||
+ | </p> |
||
+ | <p> |
||
+ | denotes the beginning of the Sage Python code to be inserted into the WeBWorK problem. This will be paired at the end with and ending SAGE_CODE which must be left-justified. This portion will create a perl variable $SageCode which is the complete Python text. |
||
+ | </p> |
||
+ | <p>To share values computed inside the Sage cell back to the WeBWorK problem, create a single Sage list named "sageAnswer" (which is configurable).</p> |
||
+ | </td> |
||
+ | </tr> |
||
− | html('<input type=hidden size=15 name="\{ANS_NUM_TO_NAME(1)\}" id="\{ANS_NUM_TO_NAME(1)\}" value="%s">' %str(x1) ) |
||
+ | <!-- Sage macro and options section --> |
||
− | html('<input type=hidden size=15 name="\{ANS_NUM_TO_NAME(2)\}" id="\{ANS_NUM_TO_NAME(2)\}" value="%s">' %str(x2) ) |
||
− | </script> |
||
− | </div> |
||
− | |||
+ | <tr valign="top"> |
||
+ | <td style="background-color:#ffdddd;border:black 1px dashed;"> |
||
+ | <pre> |
||
+ | Sage( |
||
+ | SageCode=>$SageCode, |
||
+ | ); |
||
</pre> |
</pre> |
||
</td> |
</td> |
||
− | <td style="background-color:# |
+ | <td style="background-color:#ffcccc;padding:7px;"> |
− | <p> |
||
− | This snippet defines the applet <code>PointGraph</code>. |
||
− | This applet was designed by Doug Ensley. The applet .swf file can be obtained [http://webwork.maa.org/viewvc/system/trunk/webwork2/htdocs/applets/PointGraph/PointGraph.swf?revision=6776&view=markup here]. |
||
− | This wiki has more information on '''[[FlashApplets| designing Flash applets]]''' for WeBWorK and a |
||
− | '''[[Simple_example]]''' of converting an existing flash applet for use in WeBWorK. Functional WeBWorK questions using the "PointGraph" applet can be viewed [http://hosted2.webwork.rochester.edu/webwork2/wikiExamples/PointAndGraph_AppletDemos/?login_practice_user=true here ]. |
||
− | </p> |
||
<p> |
<p> |
||
− | The <code>findAppletCodebase("PointGraph.swf")</code> asks that the file <code>PointGraph.swf</code> be searched for in (1) the course's html directory (accessible from WeBWorK's File Manager) (2) the webwork sites's htdocs/applets directory -- maintained by the site administrator. The locations searched for the file <code>PointGraph.swf</code> are defined in the site's <code>global.conf</code> file. |
||
+ | <b>Main sage script:</b> |
||
</p> |
</p> |
||
<p> |
<p> |
||
− | The <code>aliases</code> connect the names used by WeBWorK javaScript code to the subroutine and function names used by the FlashApplet. If the applet has been designed specifically to work with WeBWorK questions you will not need to change these, but if you are adapting an applet designed for other uses to a WeBWorK question then you can use these aliases to avoid making modifications to the applet. |
||
+ | Working Sage code will work verbatim except for a couple of notational changes caused by conflicting syntax between perl and sage. In particular, since "@" is used for tables in perl and for interacts in sage, one will need to replace "@" with "~~@". |
||
+ | |||
+ | Further, WeBWorK uses <code>\( and \)</code> to delimit latex and "$" for variables while Sage uses "$' to delimit latex. Therefore, converting each pair of Sage's latex $ delimiters averts any conflict. |
||
</p> |
</p> |
||
<p> |
<p> |
||
− | <code>getState</code> and <code>setState</code> are used to remember the applets state between invocations of the question. Students will find their questions in the same state they left them when they last worked on the question. The state changes as the student manipulate the applet. |
||
+ | The defaults for several of the customizable options: |
||
− | < |
+ | <pre> |
− | + | SageCode => 'print 1+2', # This is the default code if none given. |
|
+ | ButtonText => 'Start/Restart the Interactive Cell', |
||
+ | CellServer => 'http://sagecell.sagemath.org', |
||
+ | SageAnswerName => 'sageAnswer', # not used yet |
||
+ | SageAnswerValue => 'ansList', # not used yet |
||
+ | AutoEvaluateCell => 'true', # 'false' requires student to activate cell |
||
+ | ShowAnswerBlank => 'hidden', # Set to 'input' to see Sage answer |
||
+ | AnswerReturn => 1, # Set to 0 if Sage returns nothing |
||
+ | HideElements => [''], # List of items to hide in cell |
||
+ | LinkedCells => 'false', # To allow for sharing between multiple cells |
||
+ | </pre> |
||
</p> |
</p> |
||
− | <p><code>answerBox</code> is the name of the default text box for returning the answer from the applet. It is revealed when debugMode is 1 or 2 and hidden otherwise. </p> |
||
<p> |
<p> |
||
− | <code>debugMode</code>, when equal to 1, reveals two text boxes -- one containing the state of the applet and the other the answer that the flash applet submits to the WeBWorK question, along with some buttons for controlling the information in these boxes. When <code> debugMode</code>==2, additional alert messages are generated which detail progress through the initialization steps. This can be very helpful for debugging communication difficulties between the applet and the WeBWorK question |
||
+ | You can hide various elements of the sage cell by listing them in the HideElements flag. Some options: |
||
− | <p><code>submitActionScript</code> is a short javaScript command which is one way of customizing the behavior of the applet when the submit button is pressed. (It should not contain line breaks to satisfy javaScript requirements.) |
||
− | </p> |
||
− | <p>'''[[FlashApplets | FlashApplets]]''' describes this interface from the flash applets point of view. |
||
− | </p> |
||
− | </td> |
||
− | </tr> |
||
− | <tr valign="top"> |
||
− | <td style="background-color:#ffffdd;border:black 1px dashed;"> |
||
<pre> |
<pre> |
||
− | ################################### |
||
+ | Input Elements: |
||
− | # Configure applet |
||
+ | Editor (editor) |
||
− | ################################### |
||
+ | Editor type toggle (editorToggle) |
||
− | |||
+ | Language selection box (language) |
||
− | #data to set up the equation |
||
+ | Evaluate button (evalButton) |
||
− | $applet->configuration(qq{<XML expr='$function' />}); |
||
+ | Output Elements: |
||
− | # initial points |
||
+ | Permalinks (permalinks) |
||
− | $applet->initialState(qq{<XML> <pt xval='0' yval='0'/></XML>}); |
||
+ | Session output (output) |
||
− | ################################### |
||
+ | Session end message (done) |
||
− | #insert applet into body |
||
+ | Session files (sessionFiles) |
||
− | ################################### |
||
− | |||
− | TEXT( MODES(TeX=>'object code', HTML=>$applet->insertAll( |
||
− | debug=>0, |
||
− | includeAnswerBox=>1, |
||
− | reinitialize_button=>$permissionLevel>=10, |
||
− | ))); |
||
− | |||
</pre> |
</pre> |
||
− | </td> |
||
− | <td style="background-color:#ffffcc;padding:7px;"> |
||
− | <p> |
||
− | Now we configure the applet. The contents of <code>configuration</code> is sent to the applet when <code>setConfig</code> is called. In this case it defines the function the student will see. The contents of <code>initialState</code> is used for <code>setState</code> if the student has never looked at the problem. After that the applet is set to the state in which the student left the flash applet in the previous session. |
||
− | </p> |
||
− | <p> The <code>debug</code> switch is an alternate to the <code>debugMode</code> flag in the applet definition. The <code>includeAnswerBox</code> should be set to one if you are using the default answerBox. The <code>reinitialize_button</code> allows the flash applet to be reset to its virgin state, as if the student had ever looked at the WeBWorK question. In this example the button is only visible to professors (users with permission level greater than 10) so that they can reset a student's problem if it is stuck for some reason. |
||
</p> |
</p> |
||
</td> |
</td> |
||
Line 182: | Line 147: | ||
− | <!-- Question text section --> |
||
+ | |||
+ | <!-- Answer evaluation section --> |
||
<tr valign="top"> |
<tr valign="top"> |
||
− | <td style="background-color:# |
+ | <td style="background-color:#eeddff;border:black 1px dashed;"> |
<pre> |
<pre> |
||
− | BEGIN_TEXT |
||
+ | ## Lower WeBWorK text |
||
+ | ## |
||
+ | ## Problem display following the Sage cell |
||
+ | ## |
||
− | $PAR |
||
+ | Context()->texStrings; |
||
− | Drag the point to the inflection point of |
||
− | the given curve and press the submit button. |
||
− | END_TEXT |
||
− | </pre> |
||
− | <td style="background-color:#ffcccc;padding:7px;"> |
||
− | <p> |
||
− | The problem text section of the file is as we'd expect. |
||
− | </p> |
||
− | </td> |
||
− | </tr> |
||
− | <!-- Answer section --> |
||
+ | BEGIN_TEXT |
||
+ | Determine the definite integral of |
||
+ | \( \sin(${a}x) \) from \(a=0\) to \(b=\pi\). |
||
− | <tr valign="top"> |
||
+ | END_TEXT |
||
− | <td style="background-color:#eeddff;border:black 1px dashed;"> |
||
− | <pre> |
||
− | NAMED_ANS('answerBox'=>$answer_point |
||
− | ->with(tolType=>"absolute",tolerance=>.05) |
||
− | ->cmp |
||
− | ->withPostFilter(AnswerHints( |
||
− | sub { |
||
− | my ($correct,$student,$ans) = @_; |
||
− | return Vector($correct-$student)->norm<.2 ; |
||
− | } => ["You're close. You need to position |
||
− | the dot more precisely.", replaceMessage=>1] |
||
− | ))); |
||
+ | Context()->normalStrings; |
||
+ | |||
+ | # Answer Evaluation |
||
+ | |||
+ | $showPartialCorrectAnswers = 1; |
||
+ | NAMED_ANS( sageAnswer => $ansList->cmp ); # Leave out if no Sage answer. |
||
+ | |||
+ | |||
+ | ENDDOCUMENT(); |
||
</pre> |
</pre> |
||
− | <td style="background-color:# |
+ | <td style="background-color:#ddddff;padding:7px;"> |
+ | <p> ${a}x allows you to place the value of $a adjacent to x without a space. $ax would be interpreted as the value of |
||
+ | a variable called ax while $a x would produce a space between the number and x. |
||
+ | </p> |
||
<p> |
<p> |
||
− | The answer checker grabs the answer from the default <code>answerBox</code> where the applet has placed it. The answer is coordinates of the dot |
||
+ | The list of values computed inside the Sage cell are sageAnswer => $ansList. |
||
− | <code>"(x, y)"</code>. We checke it with an absolute tolerance of 0.05. If the |
||
− | the student's dot is within .2 of the correct position then we give an encouraging message to show they are on the right track. |
||
</p> |
</p> |
||
</td> |
</td> |
||
</tr> |
</tr> |
||
</table> |
</table> |
||
+ | |||
+ | <p style="text-align:center;"> |
||
+ | [[SubjectAreaTemplates|Templates by Subject Area]] |
||
+ | </p> |
||
+ | |||
+ | [[Category:Applets]] |
||
+ | [[Category:Sample Problems]] |
||
+ | [[Category:Subject Area Templates]] |
||
+ | |||
<p style="text-align:center;"> |
<p style="text-align:center;"> |
||
[[IndexOfProblemTechniques|Problem Techniques Index]]<br/> |
[[IndexOfProblemTechniques|Problem Techniques Index]]<br/> |
||
− | [[:Category:Applets | More on how to embed applets in WeBWorK Questions]] |
||
</p> |
</p> |
||
[[Category:Problem Techniques]] |
[[Category:Problem Techniques]] |
||
− | [[Category:Flash Applets]] |
||
− | |||
+ | <!-- |
||
<ul> |
<ul> |
||
<li>POD documentation: [http://webwork.maa.org/pod/pg_TRUNK/macros/AppletObjects.pl.html AppletObjects.pl.html]</li> |
<li>POD documentation: [http://webwork.maa.org/pod/pg_TRUNK/macros/AppletObjects.pl.html AppletObjects.pl.html]</li> |
||
Line 243: | Line 206: | ||
</ul> |
</ul> |
||
+ | --> |
Latest revision as of 16:35, 16 September 2021
Using the Sage Cell Server
This PG code shows how to embed a call to the Sage Cell Server from within a problem to insert Sage interacts, graphics, etc. See AskSage if you only need to run Sage programs.
PG problem file | Explanation |
---|---|
DOCUMENT(); loadMacros( "PGstandard.pl", "MathObjects.pl", "sage.pl", ); |
The sage.pl macro is now part of the standard WeBWorK distribution. |
############################################### ## ## pg initializations and regular WeBWorK code $a = random(2,5,1); $ansList = List("(-cos(pi*$a)/$a + 1/$a)"); |
The WeBWorK set up for the problem is the same, but in addition you have
to consider how you will pass the problem parameters into Sage. For example,
if you want to pass
Also, you will need to store the list of correct answers in a variable named $ansList (which is also customizable). Finally, if your final answer is a matrix converted to a list, then do not use extra parenthesis here. Otherwise $ansList will be a List of Lists which is probably a bad thing. |
$SageCode = <<SAGE_CODE; Area = integrate(sin($a*x),x,0,pi) record_answer((Area)) # leave out if you return no answer SAGE_CODE |
$SageCode = <<SAGE_CODE; denotes the beginning of the Sage Python code to be inserted into the WeBWorK problem. This will be paired at the end with and ending SAGE_CODE which must be left-justified. This portion will create a perl variable $SageCode which is the complete Python text. To share values computed inside the Sage cell back to the WeBWorK problem, create a single Sage list named "sageAnswer" (which is configurable). |
Sage( SageCode=>$SageCode, ); |
Main sage script:
Working Sage code will work verbatim except for a couple of notational changes caused by conflicting syntax between perl and sage. In particular, since "@" is used for tables in perl and for interacts in sage, one will need to replace "@" with "~~@".
Further, WeBWorK uses The defaults for several of the customizable options: SageCode => 'print 1+2', # This is the default code if none given. ButtonText => 'Start/Restart the Interactive Cell', CellServer => 'http://sagecell.sagemath.org', SageAnswerName => 'sageAnswer', # not used yet SageAnswerValue => 'ansList', # not used yet AutoEvaluateCell => 'true', # 'false' requires student to activate cell ShowAnswerBlank => 'hidden', # Set to 'input' to see Sage answer AnswerReturn => 1, # Set to 0 if Sage returns nothing HideElements => [''], # List of items to hide in cell LinkedCells => 'false', # To allow for sharing between multiple cells You can hide various elements of the sage cell by listing them in the HideElements flag. Some options: Input Elements: Editor (editor) Editor type toggle (editorToggle) Language selection box (language) Evaluate button (evalButton) Output Elements: Permalinks (permalinks) Session output (output) Session end message (done) Session files (sessionFiles) |
## Lower WeBWorK text ## ## Problem display following the Sage cell ## Context()->texStrings; BEGIN_TEXT Determine the definite integral of \( \sin(${a}x) \) from \(a=0\) to \(b=\pi\). END_TEXT Context()->normalStrings; # Answer Evaluation $showPartialCorrectAnswers = 1; NAMED_ANS( sageAnswer => $ansList->cmp ); # Leave out if no Sage answer. ENDDOCUMENT(); |
${a}x allows you to place the value of $a adjacent to x without a space. $ax would be interpreted as the value of a variable called ax while $a x would produce a space between the number and x. The list of values computed inside the Sage cell are sageAnswer => $ansList. |