Difference between revisions of "Sage Embedding"

From WeBWorK_wiki
Jump to navigation Jump to search
m (Undo revision 12390 by Malcolm (talk))
Line 76: Line 76:
 
</td>
 
</td>
 
</tr>
 
</tr>
  +
  +
<!-- Initialize the Sage embedding -->
   
 
<tr valign="top">
 
<tr valign="top">
Line 92: Line 94:
 
At =A.transpose()
 
At =A.transpose()
 
# Notice the correct exact answer is given by x = A\b
 
# Notice the correct exact answer is given by x = A\b
  +
# Finding when a vector b is in the span of other vectors in 2-space
  +
</pre>
  +
</td>
   
  +
<td style="background-color:#ffcccc;padding:7px;">
  +
<p>
  +
<b>Special to the Sage embedding:</b>
  +
</p>
  +
<p>
  +
This &lt;div&gt; section contains the Sage code needed to implement the desired function.
  +
The ''id'' attribute of the <code>&lt;div&gt;</code> must match the value of ''inputLocation''
  +
in the server script below.
  +
</p>
  +
<p>
  +
We want to pass '''two''' answers from Sage to WeBWorK, so we need to include '''two'''
  +
<code>ans_rule</code>s inside the <code>&lt;div&gt;</<code>, but outside the
  +
<code>&lt;script&gt;</code> section. The numerical value for the size of the "answer blank" is unimportant since this blank will eventually be overwritten by the Sage Cell.
  +
</p>
  +
<p>
  +
The ''type'' attribute of the <code>&lt;script&gt;</code> tag is not currently checked, but may be in the future. Its suggested value is
  +
<code>application/sage</code>. The <code>&lt;script&gt; ... &lt;/script&gt;</code> tags
  +
delimit the code that will be passed to the Sage Cell Server.
  +
</p>
  +
<p>The content of the <code>&lt;script&gt;</code> section is preprocessed by WeBWorK before being written into
  +
the web page, so the <code>$a11, $a12</code> etc. constructs are replaced by their randomized values and
  +
comments preceded by <code># ... </code> are not ever seen by Sage.
  +
</td>
  +
</tr>
  +
  +
<!-- Sage section -->
  +
  +
<tr valign="top">
  +
<td style="background-color:#ffdddd;border:black 1px dashed;">
  +
<pre>
   
# Finding when a vector b is in the span of other vectors in 2-space
 
  +
~~@interact
<b>~~@interact</b>
 
 
def _(x1=slider(-3,3,1/20,1), x2=slider(-3,3,1/20,1)):
 
def _(x1=slider(-3,3,1/20,1), x2=slider(-3,3,1/20,1)):
 
 
Line 111: Line 145:
 
# Add fixed originals and dashed modified version of these
 
# Add fixed originals and dashed modified version of these
 
show(G,frame=False)
 
show(G,frame=False)
  +
</pre>
  +
</td>
  +
<td style="background-color:#ffcccc;padding:7px;">
  +
<p>
  +
<b>Main sage script:</b>
  +
</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 "~~@".
   
  +
Further, WeBWorK 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>
  +
</td>
  +
</tr>
   
  +
<!-- Answer boxes written by Sage -->
  +
  +
<tr valign="top">
  +
<td style="background-color:#ffdddd;border:black 1px dashed;">
  +
<pre>
 
html('<input type=hidden size=15 name="\{ANS_NUM_TO_NAME(1)\}"
 
html('<input type=hidden size=15 name="\{ANS_NUM_TO_NAME(1)\}"
 
id="\{ANS_NUM_TO_NAME(1)\}" value="%s">' %str(x1) )
 
id="\{ANS_NUM_TO_NAME(1)\}" value="%s">' %str(x1) )
Line 124: Line 175:
 
<td style="background-color:#ffffcc;padding:7px;">
 
<td style="background-color:#ffffcc;padding:7px;">
   
 
This &lt;div&gt; section contains the Sage code needed to implement the desired function.
 
The ''id'' attribute of the <code>&lt;div&gt;</code> must match
 
<p>
 
We want to pass '''two''' answers from Sage to WeBWorK, so we need to include '''two'''
 
<code>ans_rule</code>s inside the <code>&lt;div&gt;</<code>, but outside the
 
<code>&lt;script&gt;</code> section. The numerical value for the size of the "answer blank" is unimportant since this blank will eventually be overwritten by the Sage Cell.
 
</p>
 
<p>
 
The ''type'' attribute of the <code>&lt;script&gt;</code> tag is not currently checked, but may be in the future. Its suggested value is
 
<code>application/sage</code>. The <code>&lt;script&gt; ... &lt;/script&gt;</code> tags
 
delimit the code that will be passed to the Sage Cell Server.
 
</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 "~~@".
 
 
Further, WeBWorK 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>
 
 
<p>
 
<p>
 
At the end of Sage code (usually an interact) you need to manually pass the answers you want from Sage back into WeBWorK by
 
At the end of Sage code (usually an interact) you need to manually pass the answers you want from Sage back into WeBWorK by
using Sage to write the answer <code>&lt;input&gt;</code> boxes (hidden since the student doesn't need to see them).
+
using Sage to write the answer <code>&lt;input&gt;</code> boxes (hidden since the student doesn't need to see them). Using
  +
<code>\{ANS_NUM_TO_NAME()\}</code> ensures they are given the correct names by WeBWorK.
 
</td>
 
</td>
 
</tr>
 
</tr>
Line 151: Line 184:
 
<td style="background-color:#ffffdd;border:black 1px dashed;">
 
<td style="background-color:#ffffdd;border:black 1px dashed;">
 
<pre>
 
<pre>
###################################
+
###########################################################
# Configure applet
+
##
###################################
+
## single cell server script
+
##
#data to set up the equation
+
## script that sends the Sage code above to the
$applet->configuration(qq{<XML expr='$function' />});
+
## single cell server and writes the return into
# initial points
+
## the webpage
$applet->initialState(qq{<XML> <pt xval='0' yval='0'/></XML>});
+
##
###################################
 
#insert applet into body
 
###################################
 
 
TEXT( MODES(TeX=>'object code', HTML=>$applet->insertAll(
 
debug=>0,
 
includeAnswerBox=>1,
 
reinitialize_button=>$permissionLevel>=10,
 
)));
 
   
</pre>
 
  +
TEXT(MODES(TeX=>"", HTML=><<'SAGE_SCRIPT'));
  +
  +
<script src="http://aleph.sagemath.org/static/jquery.min.js"></script>
  +
<script src="http://aleph.sagemath.org/embedded_sagecell.js"></script>
  +
  +
<script>
  +
$(function () {
  +
sagecell.makeSagecell({inputLocation: '#sagecell',
  +
template: sagecell.templates.minimal,
  +
autoeval: true,
  +
evalButtonText: 'Reset the interactive display'});
  +
});
  +
</script>
  +
  +
SAGE_SCRIPT
  +
</pre>
 
</td>
 
</td>
  +
 
<td style="background-color:#ffffcc;padding:7px;">
 
<td style="background-color:#ffffcc;padding:7px;">
 
<p>
 
<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.
 
  +
This section writes the javascript into the webpage that feeds the correct <code>&lt;div&gt;</code> to
</p>
 
  +
the Sage Cell Server and writes the output into the question page.
<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>
 
</tr>
 
</tr>
   
 
  +
<!-- Answer evaluation section -->
<!-- Question text section -->
 
   
 
<tr valign="top">
 
<tr valign="top">
<td style="background-color:#ffdddd;border:black 1px dashed;">
+
<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.
 
  +
BEGIN_TEXT
END_TEXT
 
  +
When you are comfortable with the coefficients that you have chosen, press
  +
the submit button below.
  +
END_TEXT
  +
  +
Context()->normalStrings;
  +
  +
#######################
  +
# Answer Evaluation
  +
  +
$showPartialCorrectAnswers = 1;
  +
  +
ANS( $x1ans->cmp() );
  +
ANS( $x2ans->cmp() );
 
</pre>
 
</pre>
<td style="background-color:#ffcccc;padding:7px;">
+
<td style="background-color:#eeccff;padding:7px;">
 
<p>
 
<p>
The problem text section of the file is as we'd expect.
 
  +
<b>Answer Evaluation:</b>
  +
</p>
  +
<p>The answers are checked in the same order as the input boxes appear
  +
in the Sage section. Some tweaking may be required to get the Sage format
  +
agreeing with the WeBWorK format of the objects the evaluator is
  +
checking
 
</p>
 
</p>
 
</td>
 
</td>
 
</tr>
 
</tr>
   
<!-- Answer section -->
+
<!-- Solutions and hints -->
   
 
<tr valign="top">
 
<tr valign="top">
<td style="background-color:#eeddff;border:black 1px dashed;">
+
<td style="background-color:#ddddff;border:black 1px dashed;">
 
<pre>
 
<pre>
NAMED_ANS('answerBox'=>$answer_point
 
  +
###########################################################
->with(tolType=>"absolute",tolerance=>.05)
 
  +
##
->cmp
 
  +
## Hint(s), delete or comment if not used
->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()->texStrings;
  +
  +
$showHint = 2;
  +
BEGIN_HINT
  +
By adjusting the sliders, you are changing the length of the corresponding vector. Remember that a negative
  +
coefficient makes the vector point in the opposite direction.
  +
END_HINT
  +
  +
$showHint = 4;
  +
$x1low = $x1-1/3;
  +
$x1high = $x1+1/5;
  +
BEGIN_HINT
  +
Consider choosing a value for the first coefficient somewhere between $x1low and $x1high.
  +
END_HINT
  +
  +
Context()->normalStrings;
  +
  +
###########################################################
  +
##
  +
## Solution, delete or comment if not used
  +
##
  +
  +
Context()->texStrings;
  +
  +
BEGIN_SOLUTION
  +
  +
Notice that \(($x1) *A_1 + ($x2) *A_2 = $b\)
  +
END_SOLUTION
  +
  +
Context()->normalStrings;
  +
  +
ENDDOCUMENT(); # This should be the last executable line in the problem.
 
</pre>
 
</pre>
<td style="background-color:#eeccff;padding:7px;">
+
<td style="background-color:#ddddff;padding:7px;">
 
<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
 
<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:Sample Problems]]
  +
[[Category:Subject Area Templates]]
  +
   
 
<p style="text-align:center;">
 
<p style="text-align:center;">
Line 225: Line 325:
   
 
[[Category:Problem Techniques]]
 
[[Category:Problem Techniques]]
[[Category:Flash Applets]]
+
[[Category:Sage embedding]]
 
   
  +
<!--
 
<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 232: Line 333:
   
 
</ul>
 
</ul>
  +
-->

Revision as of 02:07, 16 June 2012

Using the Sage Cell Server


This code snippet shows the essential PG code to embed a call to the Sage Cell Server from within a problem. Note that these are insertions, not a complete PG file. This code will have to be incorporated into the problem file on which you are working.

Problem Techniques Index

PG problem file Explanation
  loadMacros("PGstandard.pl",
             "MathObjects.pl",
  );

No special macros file is needed now although in the future AppletObjects.pl or another macros file may be required to get additional functionality.

###########################################################
##
##  pg initializations and regular WeBWorK code

$a11 = random(2,3,1/2);
$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);
$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);

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 $f = (x-(-2))(x+2)(x+4) it is best to create two versions of f: $f_raw = (x-(-2))*(x+2)*(x+4); to pass to Sage and the math object $f = Compute("$f_raw"); to use in WeBWorK.

BEGIN_TEXT
<div id="sagecell">

\{ ans_rule(15) \} \{ans_rule(15) \}.

<script type="application/sage">

b = matrix([[$b1],[$b2]])
bt = b.transpose()
A=matrix([[$a11,$a12],[$a21,$a22]])
At =A.transpose()
#   Notice the correct exact answer is given by x = A\b
#   Finding when a vector b is in the span of other vectors in 2-space

Special to the Sage embedding:

This <div> section contains the Sage code needed to implement the desired function. The id attribute of the <div> must match the value of inputLocation in the server script below.

We want to pass two answers from Sage to WeBWorK, so we need to include two ans_rules inside the <div></, but outside the <script> section. The numerical value for the size of the "answer blank" is unimportant since this blank will eventually be overwritten by the Sage Cell.

The type attribute of the <script> tag is not currently checked, but may be in the future. Its suggested value is application/sage. The <script> ... </script> tags delimit the code that will be passed to the Sage Cell Server.

The content of the <script> section is preprocessed by WeBWorK before being written into the web page, so the $a11, $a12 etc. constructs are replaced by their randomized values and comments preceded by # ... are not ever seen by Sage.


~~@interact
def _(x1=slider(-3,3,1/20,1), x2=slider(-3,3,1/20,1)): 
     
    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)

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 \( 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.

    html('<input type=hidden size=15 name="\{ANS_NUM_TO_NAME(1)\}" 
        id="\{ANS_NUM_TO_NAME(1)\}" value="%s">' %str(x1) )
    html('<input type=hidden size=15 name="\{ANS_NUM_TO_NAME(2)\}"
        id="\{ANS_NUM_TO_NAME(2)\}" value="%s">' %str(x2) )
</script>
</div>

At the end of Sage code (usually an interact) you need to manually pass the answers you want from Sage back into WeBWorK by using Sage to write the answer <input> boxes (hidden since the student doesn't need to see them). Using \{ANS_NUM_TO_NAME()\} ensures they are given the correct names by WeBWorK.

###########################################################
##
## single cell server script
##
## script that sends the Sage code above to the
## single cell server and writes the return into
## the webpage
##

TEXT(MODES(TeX=>"", HTML=><<'SAGE_SCRIPT'));

<script src="http://aleph.sagemath.org/static/jquery.min.js"></script>
<script src="http://aleph.sagemath.org/embedded_sagecell.js"></script>

<script>
$(function () {
  sagecell.makeSagecell({inputLocation:  '#sagecell',
                         template:       sagecell.templates.minimal,
                         autoeval:        true, 
                         evalButtonText: 'Reset the interactive display'});
});
</script>

SAGE_SCRIPT

This section writes the javascript into the webpage that feeds the correct <div> to the Sage Cell Server and writes the output into the question page.

####################################################
##
## Lower WeBWorK text
##
## Problem display following the Sage cell
##

Context()->texStrings;

BEGIN_TEXT
When you are comfortable with the coefficients that you have chosen, press
the submit button below.
END_TEXT

Context()->normalStrings;

#######################
# Answer Evaluation

$showPartialCorrectAnswers = 1;

ANS( $x1ans->cmp() );
ANS( $x2ans->cmp() );

Answer Evaluation:

The answers are checked in the same order as the input boxes appear in the Sage section. Some tweaking may be required to get the Sage format agreeing with the WeBWorK format of the objects the evaluator is checking

###########################################################
##
## Hint(s), delete or comment if not used
##

Context()->texStrings;

$showHint = 2;
BEGIN_HINT
By adjusting the sliders, you are changing the length of the corresponding vector.  Remember that a negative 
coefficient makes the vector point in the opposite direction.
END_HINT

$showHint = 4;
$x1low = $x1-1/3;
$x1high = $x1+1/5;
BEGIN_HINT
Consider choosing a value for the first coefficient somewhere between $x1low and $x1high.
END_HINT

Context()->normalStrings;

###########################################################
##
## Solution, delete or comment if not used
##

Context()->texStrings;

BEGIN_SOLUTION

Notice that \(($x1) *A_1 + ($x2) *A_2 = $b\) 
END_SOLUTION

Context()->normalStrings;

ENDDOCUMENT();        # This should be the last executable line in the problem.

Templates by Subject Area


Problem Techniques Index
More on how to embed applets in WeBWorK Questions