Difference between revisions of "Sage Embedding"

From WeBWorK_wiki
Jump to navigation Jump to search
(Sage Cell from within WebWork problem)
 
(Sage Cell from within WebWork problem)
Line 79: Line 79:
 
<tr>
 
<tr>
 
<td>
 
<td>
Next you add a <div> section which contains the actual answer call and Sage code needed to implement the desired function.
+
Next you add a <pre><div></pre> 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.
 
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.

Revision as of 17:02, 15 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
###########################################################
##
##  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);

Next you add a
<div>
section which contains the actual answer call and Sage code needed to implement the desired function.

Notice, the answer call appears near the top between a

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.

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, 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.

An example of they usage is illustrated in the code fragment below.

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">

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
<b>~~@interact</b>
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)


    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>




This snippet defines the applet PointGraph. This applet was designed by Doug Ensley. The applet .swf file can be obtained here. This wiki has more information on 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 here .

The findAppletCodebase("PointGraph.swf") asks that the file PointGraph.swf 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 PointGraph.swf are defined in the site's global.conf file.

The aliases 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.

getState and setState 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.

getConfig is one way that the applet can do one-time configuration when it is first initialized in a problem. This allows one applet to be used for several different questions. The command loads the <xml> data in the configuration variable defined below, in this case determining the function used in the question.

answerBox 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.

debugMode, 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 debugMode==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

submitActionScript 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.)

FlashApplets describes this interface from the flash applets point of view.

  ###################################
  # Configure applet
  ###################################
  
  #data to set up the equation
  $applet->configuration(qq{<XML expr='$function' />});
  # initial points
  $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,
   )));

Now we configure the applet. The contents of configuration is sent to the applet when setConfig is called. In this case it defines the function the student will see. The contents of initialState is used for setState 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.

The debug switch is an alternate to the debugMode flag in the applet definition. The includeAnswerBox should be set to one if you are using the default answerBox. The reinitialize_button 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.

  BEGIN_TEXT

  $PAR
  Drag the point to the inflection point of 
  the given curve and press the submit button.
  END_TEXT

The problem text section of the file is as we'd expect.

 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]
)));

The answer checker grabs the answer from the default answerBox where the applet has placed it. The answer is coordinates of the dot "(x, y)". 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.

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