Difference between revisions of "Sage Embedding"

From WeBWorK_wiki
Jump to navigation Jump to search
m (Insert link to AskSage, correct comment about sage.pl)
 
(36 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:#eeeeee;border:black solid 1px;padding:3px;">
+
<p style="background-color:#f9f9f9;border:black solid 1px;padding:3px;">
<em>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 <b>insertions</b>, not a complete PG file. This code will have to be incorporated into the problem file on which you are working.</em>
+
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 24: Line 27:
   
 
<pre>
 
<pre>
loadMacros("PGstandard.pl",
 
  +
DOCUMENT();
"MathObjects.pl",
 
  +
loadMacros(
);
 
  +
"PGstandard.pl",
  +
"MathObjects.pl",
  +
"sage.pl",
  +
);
 
</pre>
 
</pre>
   
Line 32: Line 38:
   
 
<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.
No special macros file is needed now although in the future <code>AppletObjects.pl</code>
 
or another macros file may be required to get additional functionality.
 
 
</p>
 
</p>
 
</td>
 
</td>
Line 44: 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
   
$a11 = random(2,3,1/2);
+
$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>
Line 66: Line 62:
 
to consider how you will pass the problem parameters into Sage. For example,
 
to consider how you will pass the problem parameters into Sage. For example,
 
if you want to pass
 
if you want to pass
<code>$f = (x-(-2))(x+2)(x+4)</code> it is best to create two versions of <code>f</code>:
+
<code>$f = (x-(-2))(x+2)(x+4)</code> it may be best to create two versions of <code>f</code>:
 
<code>$f_raw = (x-(-2))*(x+2)*(x+4);</code> to pass to Sage and the math object
 
<code>$f_raw = (x-(-2))*(x+2)*(x+4);</code> to pass to Sage and the math object
 
<code>$f = Compute("$f_raw");</code> to use in WeBWorK.
 
<code>$f = Compute("$f_raw");</code> to use in WeBWorK.
  +
<p>
  +
Also, you will need to store the list of correct answers in a variable named $ansList (which is also customizable).
  +
</p>
  +
<p>
  +
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>
 
</td>
 
</td>
 
</tr>
 
</tr>
Line 77: Line 79:
 
<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">
 
   
\{ ans_rule(15) \} \{ans_rule(15) \}.
 
  +
$SageCode = <<SAGE_CODE;
   
<script type="application/sage">
 
  +
Area = integrate(sin($a*x),x,0,pi)
   
b = matrix([[$b1],[$b2]])
 
  +
record_answer((Area)) # leave out if you return no answer
bt = b.transpose()
 
  +
A=matrix([[$a11,$a12],[$a21,$a22]])
 
  +
SAGE_CODE
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
 
 
</pre>
 
</pre>
 
</td>
 
</td>
Line 95: Line 92:
 
<td style="background-color:#ffcccc;padding:7px;">
 
<td style="background-color:#ffcccc;padding:7px;">
 
<p>
 
<p>
<b>Special to the Sage embedding:</b>
 
  +
$SageCode = <<SAGE_CODE;
</p>
+
</p>
<p>
+
<p>
This &lt;div&gt; section contains the Sage code needed to implement the desired function.
+
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.
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>
<p>The content of the <code>&lt;script&gt;</code> section is preprocessed by WeBWorK before being written into
 
  +
<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>
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>
 
</td>
 
</tr>
 
</tr>
   
<!-- Sage section -->
+
<!-- Sage macro and options section -->
   
 
<tr valign="top">
 
<tr valign="top">
Line 112: Line 107:
 
<pre>
 
<pre>
   
~~@interact
 
  +
Sage(
def _(x1=slider(-3,3,1/20,1), x2=slider(-3,3,1/20,1)):
 
  +
SageCode=>$SageCode,
 
  +
);
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)
 
 
</pre>
 
</pre>
 
</td>
 
</td>
  +
 
<td style="background-color:#ffcccc;padding:7px;">
 
<td style="background-color:#ffcccc;padding:7px;">
 
<p>
 
<p>
Line 137: Line 121:
 
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 "~~@".
 
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.
+
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>
</td>
+
<p>
</tr>
+
The defaults for several of the customizable options:
 
<!-- Answer boxes written by Sage -->
 
 
<tr valign="top">
 
<td style="background-color:#ffdddd;border:black 1px dashed;">
 
 
<pre>
 
<pre>
html('<input type=hidden size=15 name="\{ANS_NUM_TO_NAME(1)\}"
 
  +
SageCode => 'print 1+2', # This is the default code if none given.
id="\{ANS_NUM_TO_NAME(1)\}" value="%s">' %str(x1) )
 
  +
ButtonText => 'Start/Restart the Interactive Cell',
html('<input type=hidden size=15 name="\{ANS_NUM_TO_NAME(2)\}"
 
  +
CellServer => 'http://sagecell.sagemath.org',
id="\{ANS_NUM_TO_NAME(2)\}" value="%s">' %str(x2) )
 
  +
SageAnswerName => 'sageAnswer', # not used yet
</script>
 
  +
SageAnswerValue => 'ansList', # not used yet
</div>
 
  +
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>
 
</pre>
</td>
+
</p>
 
<td style="background-color:#ffffcc;padding:7px;">
 
 
 
<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
 
  +
You can hide various elements of the sage cell by listing them in the HideElements flag. Some options:
using Sage to write the answer <code>&lt;input&gt;</code> boxes (hidden since the student doesn't need to see them). Using
 
  +
<pre>
<code>\{ANS_NUM_TO_NAME()\}</code> ensures they are given the correct names by WeBWorK.
 
  +
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)
  +
</pre>
  +
</p>
 
</td>
 
</td>
 
</tr>
 
</tr>
   
<tr valign="top">
 
<td style="background-color:#ffffdd;border:black 1px dashed;">
 
<pre>
 
###########################################################
 
##
 
## 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
 
</pre>
 
</td>
 
 
<td style="background-color:#ffffcc;padding:7px;">
 
<p>
 
This section writes the javascript into the webpage that feeds the correct <code>&lt;div&gt;</code> to
 
the Sage Cell Server and writes the output into the question page.
 
</p>
 
</td>
 
</tr>
 
   
 
<!-- Answer evaluation section -->
 
<!-- Answer evaluation section -->
Line 200: Line 163:
 
<td style="background-color:#eeddff;border:black 1px dashed;">
 
<td style="background-color:#eeddff;border:black 1px dashed;">
 
<pre>
 
<pre>
####################################################
 
##
 
 
## Lower WeBWorK text
 
## Lower WeBWorK text
 
##
 
##
Line 210: Line 171:
   
 
BEGIN_TEXT
 
BEGIN_TEXT
When you are comfortable with the coefficients that you have chosen, press
 
  +
Determine the definite integral of
the submit button below.
 
  +
\( \sin(${a}x) \) from \(a=0\) to \(b=\pi\).
  +
 
END_TEXT
 
END_TEXT
   
 
Context()->normalStrings;
 
Context()->normalStrings;
   
#######################
 
 
# Answer Evaluation
 
# Answer Evaluation
   
 
$showPartialCorrectAnswers = 1;
 
$showPartialCorrectAnswers = 1;
  +
NAMED_ANS( sageAnswer => $ansList->cmp ); # Leave out if no Sage answer.
   
ANS( $x1ans->cmp() );
 
ANS( $x2ans->cmp() );
 
</pre>
 
<td style="background-color:#eeccff;padding:7px;">
 
<p>
 
<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>
 
</td>
 
</tr>
 
   
<!-- Solutions and hints -->
 
  +
ENDDOCUMENT();
 
<tr valign="top">
 
<td style="background-color:#ddddff;border:black 1px dashed;">
 
<pre>
 
###########################################################
 
##
 
## 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.
 
 
</pre>
 
</pre>
 
<td style="background-color:#ddddff;padding:7px;">
 
<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 list of values computed inside the Sage cell are sageAnswer => $ansList.
 
</p>
 
</p>
 
</td>
 
</td>
Line 290: Line 201:
 
</p>
 
</p>
   
  +
[[Category:Applets]]
 
[[Category:Sample Problems]]
 
[[Category:Sample Problems]]
 
[[Category:Subject Area Templates]]
 
[[Category:Subject Area Templates]]
Line 296: Line 208:
 
<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:Sage embedding]]
 
   
 
<!--
 
<!--

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.

Problem Techniques Index

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 $f = (x-(-2))(x+2)(x+4) it may be 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.

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 \( and \) to delimit latex and "$" for variables while Sage uses "$' to delimit latex. Therefore, converting each pair of Sage's latex $ delimiters averts any conflict.

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.

Templates by Subject Area


Problem Techniques Index