1: # LearningOnline Network with CAPA
2: # option list style responses
3: #
4: # $Id: functionplotresponse.pm,v 1.35 2010/11/12 02:16:20 www Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: package Apache::functionplotresponse;
30: use strict;
31: use Apache::response();
32: use Apache::lonlocal;
33: use Apache::lonnet;
34:
35: BEGIN {
36: &Apache::lonxml::register('Apache::functionplotresponse',('functionplotresponse','backgroundplot','spline','functionplotrule'));
37: }
38:
39: #
40: # There can be a number of applets on a page, each called ggbApplet_$id,
41: # where $id is the "_"-concatenated part and responseid
42: #
43:
44: sub geogebra_startcode {
45: my ($id)=@_;
46: return (<<ENDSTARTCODE);
47: <applet name="ggbApplet_$id" code="geogebra.GeoGebraApplet" archive="geogebra.jar"
48: codebase="/adm/geogebra/" width="714" height="447" MAYSCRIPT>
49: <param name="java_arguments" value="-Xmx512m -Djnlp.packEnabled=true"/>
50: ENDSTARTCODE
51: }
52:
53: sub geogebra_endcode {
54: return &Apache::lonhtmlcommon::java_not_enabled()."</applet>\n";
55: }
56:
57: #
58: # This is the internal GeoGebra bytecode which defines the spline functions
59: #
60: sub geogebra_spline_program {
61: return (<<ENDSPLINEPROGRAM);
62: <param name="ggbBase64" value="UEsDBBQACAAIADhQET0AAAAA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Ig3wIwwh2VTH2gGfSlFJXjrgvE60ImQk6jsPqfLhCEliHqPWpNoFthKpXS1vRgLDTn/Bq3w7iWbLJaLmMX4wz88dgkWlqSTZJGweTRny9UqWWIKUS8KYYtJzFJkZctZki5SluChf9v81XDcgrVYSkP4GcyYz1qL6ppwt3k2X5W8QZ0SrX3ine21b4N4gLb24m7DvGkX45e2ljBgEVZpD+WhUOdtyFscqF8unT/i9RT1k5JKE+0CRf31sBZh9T5O6NVr5n1m3mPgcKRXe7Ri3sOvRVi9lxRtkDYEHo1Rj1XhZ2GIA5Dcde+YG8kLwGagpG+F3YwbbJrDLVLn/6NvCpya921zpYz+E2U2veu37AC6BRm6qsXC9qo35Oi6N5TO66igFA1ug2FICHfF+oUCAlpBrWHUHUYupMtbP3TuHZxNRxFOg0GtpcW3A+OxLpZt51Kfugm3OF05/c4bMGTD8Y2xF0oqbtHLPR3T98f9iA1vzPovUEsHCEyILqxEAgAAlQQAAFBLAQIUABQACAAIADhQET1gj4YNdwsAAFgqAQASAAAAAAAAAAAAAAAAAAAAAABnZW9nZWJyYV9tYWNyby54bWxQSwECFAAUAAgACAA4UBE9TIgurEQCAACVBAAADAAAAAAAAAAAAAAAAAC3CwAAZ2VvZ2VicmEueG1sUEsFBgAAAAACAAIAegAAADUOAAAAAA=="/>
63: ENDSPLINEPROGRAM
64: }
65:
66: #
67: # The standard set of parameters inside <applet>
68: #
69: sub geogebra_default_parameters {
70: my ($id)=@_;
71: return(<<ENDDEFAULTPARAMETERS);
72: <param name="image" value="/adm/lonIcons/lonanim.gif" />
73: <param name="boxborder" value="false" />
74: <param name="centerimage" value="true" />
75: <param name="java_arguments" value="-Xmx512m" />
76: <param name="cache_archive" value="geogebra.jar, geogebra_main.jar, geogebra_gui.jar, geogebra_cas.jar, geogebra_export.jar, geogebra_properties.jar" />
77: <param name="cache_version" value="3.2.44.0, 3.2.44.0, 3.2.44.0, 3.2.44.0, 3.2.44.0, 3.2.44.0" />
78: <param name="framePossible" value="false" />
79:
80: <param name="showResetIcon" value="false" />
81: <param name="showAnimationButton" value="false" />
82: <param name="enableRightClick" value="false" />
83: <param name="errorDialogsActive" value="true" />
84: <param name="enableLabelDrags" value="false" />
85: <param name="showMenuBar" value="false" />
86: <param name="showToolBar" value="false" />
87: <param name="showToolBarHelp" value="false" />
88: <param name="showAlgebraInput" value="false" />
89: <param name="enableShiftDragZoom" value="false" />
90: <param name="allowRescaling" value="false" />
91: <param name="enableLabelDrags" value="false" />
92: <param name="ggbOnInitParam" value="applet_$id" />
93: ENDDEFAULTPARAMETERS
94: }
95:
96: #
97: # This subroutine is called by LON-CAPA at </problem>
98: # Each applet on the page will call function ggbOnInit when it is done loading
99: # This function in turn will call the respective function registered by start_init_script
100: # Which one of the registered functions is called is determined by ggbOnInitParam, which GeoGebra passes to ggbOnInit
101: #
102:
103: sub init_script {
104: if ($#Apache::functionplotresponse::callscripts>=0) {
105: my $script='';
106: foreach my $id (@Apache::functionplotresponse::callscripts) {
107: $script.="if (param=='applet_$id') { loaded_$id=true; }\n";
108: }
109: $script.="if (".join(' && ',map { "loaded_$_" } (@Apache::functionplotresponse::callscripts)).
110: ") { setTimeout('ggbInitAll()',20) }";
111: my $calls=join("\n",map { "ggbInit_$_();" } (@Apache::functionplotresponse::callscripts));
112: return (<<ENDGGBINIT);
113: <script type="text/javascript">
114: // <![CDATA[
115: // Function that each applet will call when loaded
116: // It will pass "its" parameter
117: // Set flags for when an applet is loaded, wait till all are loaded, and then some
118: function ggbOnInit(param) {
119: $script
120: }
121: function ggbInitAll() {
122: $calls
123: }
124: // ]]>
125: </script>
126: ENDGGBINIT
127: }
128: }
129:
130: #
131: # Each Geogebra applet is supposed to call this when parameters change
132: # Changes the hidden fields on the web page
133: #
134: sub update_script {
135: my ($id)=@_;
136: return (<<ENDUPDATESCRIPT);
137: <script type="text/javascript">
138: // <![CDATA[
139: function updatePointCoordinates_$id(coordinateName) {
140: var x = document.ggbApplet_$id.getXcoord(coordinateName);
141: var y = document.ggbApplet_$id.getYcoord(coordinateName);
142: document.lonhomework.elements["HWVAL_$id\_" + coordinateName + "_x"].value = x;
143: document.lonhomework.elements["HWVAL_$id\_" + coordinateName + "_y"].value = y;
144: }
145: // ]]>
146: </script>
147: ENDUPDATESCRIPT
148: }
149:
150: #
151: # Register the above update-handler for a variable
152: #
153:
154: sub update_register {
155: my ($id,$variable)=@_;
156: return "document.ggbApplet_$id.registerObjectUpdateListener('$variable','updatePointCoordinates_$id');\n";
157: }
158:
159: #
160: # Set a coordinate variable
161: #
162: sub set_coordinate {
163: my ($id,$variable,$x,$y)=@_;
164: return (<<ENDSETVARIABLE);
165: document.ggbApplet_$id.evalCommand("$variable=($x,$y)");
166: ENDSETVARIABLE
167: }
168:
169: #
170: # Input field name for a coordinate variable
171: #
172:
173: sub field_name {
174: my ($id,$variable,$name)=@_;
175: return "HWVAL_$id\_$variable\_$name";
176: }
177:
178: #
179: # Generate an input field for a coordinate variable
180: #
181:
182: sub generate_input_field {
183: my ($id,$variable,$x,$y)=@_;
184: $Apache::functionplotresponse::inputfields.=
185: "<input type='hidden' name='".&field_name($id,$variable,'x')."' value='$x' />\n".
186: "<input type='hidden' name='".&field_name($id,$variable,'y')."' value='$y' />\n";
187: }
188:
189: #
190: # Initialize a new coordinate variable at set a listener on it
191: #
192: sub new_coordinate {
193: my ($id,$variable,$x,$y)=@_;
194: if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'x')})) {
195: $x=$Apache::functionplotresponse::previous{&field_name($id,$variable,'x')};
196: }
197: if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'y')})) {
198: $y=$Apache::functionplotresponse::previous{&field_name($id,$variable,'y')};
199: }
200: &generate_input_field($id,$variable,$x,$y);
201: return &set_coordinate($id,$variable,$x,$y).&update_register($id,$variable);
202: }
203:
204: #
205: # This registers the init-function call for ggbOnInit, which LON-CAPA will place at </problem>
206: # It then starts the right headers
207: #
208: sub start_init_script {
209: my ($id)=@_;
210: # Add id to the list of ggbInit_$id functions that need to be called
211: push(@Apache::functionplotresponse::callscripts,$id);
212: # ... and open this function
213: return (<<ENDSTARTINIT);
214: <script type="text/javascript">
215: // <![CDATA[
216: // variable that will eventually be passed back to the server
217: var coordinateMap_$id = [];
218: // flag for not loaded yet
219: var loaded_$id=false;
220: // Init-function for applet
221: function ggbInit_$id() {
222: ENDSTARTINIT
223: }
224:
225: #
226: # This sets the axes inside ggbInit_$id
227: #
228:
229: sub axes_script {
230: my ($id,$xmin,$xmax,$ymin,$ymax,$xvisible,$yvisible,$gvisible)=@_;
231: return (<<ENDAXESSCRIPT);
232: // changes (xmin, xmax, ymin, ymax)
233: document.ggbApplet_$id.setCoordSystem($xmin,$xmax,$ymin,$ymax);
234:
235: // makes the (x,y) axis (in)visible
236: document.ggbApplet_$id.setAxesVisible($xvisible,$yvisible);
237: // makes the grid (in)visible
238: document.ggbApplet_$id.setGridVisible($gvisible);
239: ENDAXESSCRIPT
240: }
241:
242: sub axes_label {
243: my ($id,$xlabel,$ylabel)=@_;
244: unless ($xlabel || $ylabel) { return ''; }
245: my $return='document.ggbApplet_'.$id.'.evalCommand("topRight=Corner[3]");';
246: if ($xlabel) {
247: $return.=(<<ENDXAXISLABELSCRIPT);
248: document.ggbApplet_$id.evalCommand("Xlabel=(x(topRight)-AxisStepX[],AxisStepY[]/6)");
249: document.ggbApplet_$id.setVisible("Xlabel",false);
250: document.ggbApplet_$id.evalCommand("Text[\\"$xlabel\\", Xlabel]");
251: ENDXAXISLABELSCRIPT
252: }
253: if ($ylabel) {
254: $return.=(<<ENDYAXISLABELSCRIPT);
255: document.ggbApplet_$id.evalCommand("Ylabel=(AxisStepX[]/6,y(topRight)-AxisStepY[]/3)");
256: document.ggbApplet_$id.setVisible("Ylabel",false);
257: document.ggbApplet_$id.evalCommand("Text[\\"$ylabel\\", Ylabel]");
258: ENDYAXISLABELSCRIPT
259: }
260: return $return;
261: }
262:
263: sub plot_script {
264: my ($id,$function,$fixed)=@_;
265: if ($fixed) {
266: # Use stupid trick to nail this to a location
267: # Oddly, it seems like only one plot cannot be nailed to a location
268: # Non-nailed-down plots apparently get overwritten
269: return (<<ENDPLOTSCRIPT);
270: document.ggbApplet_$id.evalCommand("a=1");
271: document.ggbApplet_$id.setVisible("a",false);
272: // This MUST be a DEPENDENT OBJECT in order to be locked down:
273: document.ggbApplet_$id.evalCommand("y=a*($function)");
274: ENDPLOTSCRIPT
275: } else {
276: return "document.ggbApplet_$id.evalCommand('y=$function')";
277: }
278: }
279:
280: #
281: # Subroutine that generates code for spline $label based on stored information
282: #
283:
284: sub generate_spline {
285: my ($id,$label)=@_;
286: my $result='';
287: my $order=$Apache::functionplotresponse::splineorder{$label};
288: my $x=$Apache::functionplotresponse::splineinitx{$label};
289: my $y=$Apache::functionplotresponse::splineinity{$label};
290: my $sx=$Apache::functionplotresponse::splinescalex{$label};
291: my $sy=$Apache::functionplotresponse::splinescaley{$label};
292: my @coords=();
293: foreach my $i (1..$order) {
294: $result.=&new_coordinate($id,$label.'P'.$i,$x,$y);
295: $x+=$sx/(2.*($order-1));
296: push(@coords,$label.'P'.$i);
297: $result.=&new_coordinate($id,$label.'S'.$i,$x,$y+$sy);
298: $x+=$sx/(2.*($order-1));
299: push(@coords,$label.'S'.$i);
300: }
301: $result.='document.ggbApplet_'.$id.'.evalCommand("Spline'.$order.'['.join(',',@coords).']");'."\n";
302: return $result;
303: }
304: #
305: # <backgroundplot function="..." fixed="yes/no" />
306: #
307: sub start_backgroundplot {
308: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
309: my $result='';
310: my $internalid = $Apache::inputtags::part.'_'.$Apache::inputtags::response[-1];
311: my $function=&Apache::lonxml::get_param('function',$parstack,$safeeval);
312: my $fixed=(&Apache::lonxml::get_param('fixed',$parstack,$safeeval)=~/on|true|yes|1/i?1:0);
313:
314: unless ($function) { $function="0"; }
315: if ($target eq 'web') {
316: $result.=&plot_script($internalid,$function,$fixed);
317: } elsif ($target eq 'edit') {
318: $result=&Apache::edit::tag_start($target,$token,'Background Function Plot').
319: &Apache::edit::text_arg('Function:','function',
320: $token,'16').
321: &Apache::edit::select_arg('Fixed location:','fixed',
322: ['yes','no'],$token).
323: &Apache::edit::end_row();
324: } elsif ($target eq 'modified') {
325: my $constructtag=&Apache::edit::get_new_args($token,$parstack,
326: $safeeval,'function','fixed');
327: if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
328: }
329: return $result;
330: }
331:
332: sub end_backgroundplot {
333: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
334: my $result='';
335: if ($target eq 'edit') {
336: $result=&Apache::edit::end_table();
337: }
338: return $result;
339: }
340:
341: #
342: # <functionplotrule ... />
343: #
344: sub start_functionplotrule {
345: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
346: my $result='';
347: my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
348: $Apache::functionplotresponse::counter++;
349: if ($label=~/\W/) {
350: &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
351: }
352: $label=~s/\W//gs;
353: unless ($label) {
354: $label='R'.$Apache::functionplotresponse::counter;
355: } else {
356: $label='R'.$label;
357: }
358: if ($Apache::functionplotresponse::splineorder{$label}) {
359: &Apache::lonxml::error(&mt('Rule indices must be unique.'));
360: }
361:
362:
363: if ($target eq 'grade') {
364: # Simply remember - in order - for later
365: my $beginninglabel=&Apache::lonxml::get_param('xinitiallabel',$parstack,$safeeval);
366: my $endinglabel=&Apache::lonxml::get_param('xfinallabel',$parstack,$safeeval);
367: if (($beginninglabel=~/\W/) || ($endinglabel=~/W/)) {
368: &Apache::lonxml::warning(&mt('Rule labels must be alphanumeric.'));
369: }
370: $beginninglabel=~s/\W//gs;
371: $endinglabel=~s/\W//gs;
372: my $relationship=&Apache::lonxml::get_param('relationship',$parstack,$safeeval);
373: $relationship=~s/\W//gs;
374: $relationship=lc($relationship);
375: unless ($relationship=~/^(eq|ge|gt|le|lt|ne)$/) {
376: &Apache::lonxml::warning(&mt('Rule relationship not defined.'));
377: $relationship='eq';
378: }
379: my $derivative=&Apache::lonxml::get_param('derivativeorder',$parstack,$safeeval);
380: unless (($derivative==0) || ($derivative==1) || ($derivative==2)) {
381: &Apache::lonxml::warning(&mt('Rule derivative not defined.'));
382: $derivative=0;
383: }
384: push(@Apache::functionplotresponse::functionplotrules,join(':',(
385: $label,
386: $derivative,
387: &Apache::lonxml::get_param('xinitial',$parstack,$safeeval),
388: $beginninglabel,
389: &Apache::lonxml::get_param('xfinal',$parstack,$safeeval),
390: $endinglabel,
391: &Apache::lonxml::get_param('minimumlength',$parstack,$safeeval),
392: &Apache::lonxml::get_param('maximumlength',$parstack,$safeeval),
393: $relationship,
394: &Apache::lonxml::get_param('value',$parstack,$safeeval),
395: &Apache::lonxml::get_param('percenterror',$parstack,$safeeval)
396: )));
397: } elsif ($target eq 'edit') {
398: $result=&Apache::edit::tag_start($target,$token,'Function Plot Evaluation Rule').
399: &Apache::edit::text_arg('Index:','index',
400: $token,'4').' '.
401: &Apache::edit::select_arg(&mt('Function:'),'derivativeorder',
402: [['0','Function itself'],
403: ['1','First derivative'],
404: ['2','Second derivative']],$token).'<br />'.
405: &Apache::edit::text_arg('(Initial) x-value:','xinitial',
406: $token,'8').
407: &Apache::edit::select_or_text_arg('(Initial) x-value label:','xinitiallabel',
408: [['start','Start of Plot']],$token,'8').'<br />'.
409:
410: &Apache::edit::text_arg('Optional final x-value for ranges:','xfinal',
411: $token,'8').
412: &Apache::edit::select_or_text_arg('Optional final x-value label:','xfinallabel',
413: [['end','End of Plot']],$token,'8').'<br />'.
414: &Apache::edit::text_arg('Optional minimum length for range:','minimumlength',
415: $token,'8').
416: &Apache::edit::text_arg('Optional maximum length for range:','maximumlength',
417: $token,'8').'<br />'.
418: &Apache::edit::select_arg(&mt('Relationship:'),'relationship',
419: [['eq','equal'],
420: ['ne','not equal'],
421: ['ge','greater than or equal'],
422: ['gt','greater than'],
423: ['lt','less than'],
424: ['le','less than or equal']],$token).
425: $result.= &Apache::edit::select_or_text_arg('Value:','value',
426: [['undef','not defined']],$token,'8').
427: &Apache::edit::text_arg('Percent error:','percenterror',
428: $token,'8').
429: &Apache::edit::end_row();
430: } elsif ($target eq 'modified') {
431: my $constructtag=&Apache::edit::get_new_args($token,$parstack,
432: $safeeval,'index','derivativeorder',
433: 'xinitial','xinitiallabel','xfinal','xfinallabel',
434: 'minimumlength','maximumlength',
435: 'relationship','value','percenterror');
436: if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
437: }
438: return $result;
439: }
440:
441: sub end_functionplotrule {
442: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
443: my $result='';
444: if ($target eq 'edit') {
445: $result=&Apache::edit::end_table();
446: }
447: return $result;
448: }
449:
450:
451: #
452: # <spline index="..." order="1,2,3,4" initx="..." inity="..." scalex="..." scaley="..." />
453: #
454: # Unfortunately, GeoGebra seems to want all splines after everything else, so we need to store them
455: #
456: sub start_spline {
457: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
458: my $result='';
459: if ($target eq 'web') {
460: my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
461: $Apache::functionplotresponse::counter++;
462: if ($label=~/\W/) {
463: &Apache::lonxml::warning(&mt('Spline indices should only contain alphanumeric characters.'));
464: }
465: $label=~s/\W//gs;
466: unless ($label) {
467: $label='S'.$Apache::functionplotresponse::counter;
468: } else {
469: $label='S'.$label;
470: }
471: if ($Apache::functionplotresponse::splineorder{$label}) {
472: &Apache::lonxml::error(&mt('Spline indices must be unique.'));
473: }
474:
475: my $order=&Apache::lonxml::get_param('order',$parstack,$safeeval);
476: if ($order<2) { $order=2; }
477: if ($order>8) { $order=8; }
478: $Apache::functionplotresponse::splineorder{$label}=$order;
479:
480: my $x=&Apache::lonxml::get_param('initx',$parstack,$safeeval);
481: unless ($x) { $x=0; }
482: $Apache::functionplotresponse::splineinitx{$label}=$x;
483:
484: my $y=&Apache::lonxml::get_param('inity',$parstack,$safeeval);
485: unless ($y) { $y=0; }
486: $Apache::functionplotresponse::splineinity{$label}=$y;
487:
488: my $sx=&Apache::lonxml::get_param('scalex',$parstack,$safeeval);
489: unless ($sx) { $sx=$order; }
490: $Apache::functionplotresponse::splinescalex{$label}=$sx;
491:
492: my $sy=&Apache::lonxml::get_param('scaley',$parstack,$safeeval);
493: unless ($sy) { $sy=2; }
494: $Apache::functionplotresponse::splinescaley{$label}=$sy;
495: } elsif ($target eq 'edit') {
496: $result=&Apache::edit::tag_start($target,$token,'Spline').
497: &Apache::edit::text_arg('Index:','index',
498: $token,'4').' '.
499: &Apache::edit::select_arg('Order:','order',
500: ['2','3','4','5','6','7','8','9'],$token).' '.
501: &Apache::edit::text_arg('Initial x-value:','initx',
502: $token,'4').' '.
503: &Apache::edit::text_arg('Initial y-value:','inity',
504: $token,'4').' '.
505: &Apache::edit::text_arg('Scale x:','scalex',
506: $token,'4').' '.
507: &Apache::edit::text_arg('Scale y:','scaley',
508: $token,'4').
509: &Apache::edit::end_row();
510: } elsif ($target eq 'modified') {
511: my $constructtag=&Apache::edit::get_new_args($token,$parstack,
512: $safeeval,'index','order','initx','inity',
513: 'scalex','scaley');
514: if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
515: }
516: return $result;
517: }
518:
519: sub end_spline {
520: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
521: my $result='';
522: if ($target eq 'edit') {
523: $result=&Apache::edit::end_table();
524: }
525: return $result;
526: }
527:
528: sub end_init_script {
529: return (<<ENDENDINIT);
530: }
531: // ]]>
532: </script>
533: ENDENDINIT
534: }
535:
536: #
537: # Storing and restoring spline coordinates from part answers
538: #
539: sub decode_previous_answer {
540: my ($answer)=@_;
541: foreach my $coordinate (split(/\,/,$answer)) {
542: my ($key,$value)=split(/\=/,$coordinate);
543: $Apache::functionplotresponse::previous{$key}=$value;
544: }
545: }
546:
547: sub get_answer_from_form_fields {
548: my ($id)=@_;
549: my $answer='';
550: my %coords=();
551: foreach my $field (keys(%env)) {
552: if ($field=~/^form\.HWVAL\_$id/) {
553: $field=~/^form\.(.*)$/;
554: $coords{$1}=$env{$field};
555: }
556: }
557: $answer=join(',',map { $_.'='.$coords{$_} } (sort(keys(%coords))));
558: return ($answer,%coords);
559: }
560:
561: #
562: # The following functions calculate the cubic-hermite splines server-side
563: #
564:
565: sub cubic_hermite {
566: my ($t,$p1,$s1,$p2,$s2)=@_;
567: return (2.*$t*$t*$t-3.*$t*$t+1.)*$p1 + 5.*($t*$t*$t-2.*$t*$t+$t)*($s1-$p1)+
568: (-2.*$t*$t*$t+3.*$t*$t) *$p2 + 5.*($t*$t*$t-$t*$t) *($s2-$p2);
569: }
570:
571: #
572: # d/dt(...)
573: #
574:
575: sub ddt_cubic_hermite {
576: my ($t,$p1,$s1,$p2,$s2)=@_;
577: return (6.*$t*$t-6.*$t) *$p1 + 5.*(3.*$t*$t-4.*$t+1.)*($s1-$p1)+
578: (-6.*$t*$t+6.*$t)*$p2 + 5.*(3.*$t*$t-2.*$t) *($s2-$p2);
579: }
580:
581: #
582: # d^2/dt^2(...)
583: #
584:
585: sub d2dt2_cubic_hermite {
586: my ($t,$p1,$s1,$p2,$s2)=@_;
587: return (12.*$t-6.) *$p1 + 5.*(6.*$t-4.)*($s1-$p1)+
588: (-12.*$t+6.)*$p2 + 5.*(6.*$t-2.)*($s2-$p2);
589: }
590:
591: #
592: # Array index calculation
593: #
594: sub array_index {
595: my ($xmin,$xmax,$x)=@_;
596: return int(($x-$xmin)/($xmax-$xmin)*400.+0.5);
597: }
598:
599: #
600: # Populate the arrays
601: #
602:
603: sub populate_arrays {
604: my ($id,$xmin,$xmax)=@_;
605: for (my $i=0; $i<=400; $i++) {
606: $Apache::functionplotresponse::actualxval[$i]=undef;
607: $Apache::functionplotresponse::func[$i]=undef;
608: $Apache::functionplotresponse::dfuncdx[$i]=undef;
609: $Apache::functionplotresponse::d2funcd2x[$i]=undef;
610: }
611: unless ($xmax>$xmin) { return 'no_func'; }
612: # Run over all splines in response
613: foreach my $label (split(/\,/,$env{"form.HWVAL_AllSplines_$id"})) {
614: my $xiold=-1;
615: # Run over all points in spline
616: for (my $i=1; $i<$env{"form.HWVAL_SplineOrder_".$id."_".$label}; $i++) {
617: my $ni=$i+1;
618: my @xparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_x'},
619: $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_x'},
620: $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_x'},
621: $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_x'});
622: my @yparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_y'},
623: $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_y'},
624: $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_y'},
625: $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_y'});
626: # Run in small steps over spline parameter
627: for (my $t=0; $t<=1; $t+=0.0001) {
628: my $xreal=&cubic_hermite($t,@xparms);
629: my $xi=&array_index($xmin,$xmax,$xreal);
630: if ($xi<$xiold) { return 'no_func'; }
631: if (($xi>$xiold) && ($xi>=0) && ($xi<=400)) {
632: if (defined($Apache::functionplotresponse::func[$xi])) { return 'no_func'; }
633: $xiold=$xi;
634: $Apache::functionplotresponse::actualxval[$xi]=$xreal;
635: # Function value
636: my $funcval=&cubic_hermite($t,@yparms);
637: $Apache::functionplotresponse::func[$xi]=$funcval;
638: if (defined($funcval)) {
639: if ($xi<$Apache::functionplotresponse::functionplotrulelabels{'start'}) {
640: $Apache::functionplotresponse::functionplotrulelabels{'start'}=$xi;
641: }
642: if ($xi>$Apache::functionplotresponse::functionplotrulelabels{'end'}) {
643: $Apache::functionplotresponse::functionplotrulelabels{'end'}=$xi;
644: }
645: }
646: # Chain rule
647: # dy/dx=dy/dt/(dx/dt)
648: my $dxdt=&ddt_cubic_hermite($t,@xparms);
649: if ($dxdt) {
650: $Apache::functionplotresponse::dfuncdx[$xi]=&ddt_cubic_hermite($t,@yparms)/$dxdt;
651: # Second derivative
652: $Apache::functionplotresponse::d2funcdx2[$xi]=
653: ($dxdt*&d2dt2_cubic_hermite($t,@yparms)-&ddt_cubic_hermite($t,@yparms)*&d2dt2_cubic_hermite($t,@xparms))/
654: ($dxdt*$dxdt*$dxdt);
655: }
656: }
657: }
658: }
659: }
660: }
661:
662: #
663: # Implentation of <functionplotresponse>
664: #
665:
666: sub start_functionplotresponse {
667: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
668: my $result='';
669: # To remember the splines - somehow, they need to come last
670: undef %Apache::functionplotresponse::splineorder;
671: undef %Apache::functionplotresponse::splineinitx;
672: undef %Apache::functionplotresponse::splineinity;
673: undef %Apache::functionplotresponse::splinescalex;
674: undef %Apache::functionplotresponse::splinescaley;
675: # Remember input fields, etc
676: undef %Apache::functionplotresponse::previous;
677: $Apache::functionplotresponse::inputfields='';
678: $Apache::functionplotresponse::counter=0;
679: # Remember rules
680: undef @Apache::functionplotresponse::functionplotrules;
681: # Part and ID
682: my $partid=$Apache::inputtags::part;
683: my $id=&Apache::response::start_response($parstack,$safeeval);
684: # Internal ID to mark the applet and its coordinates
685: my $internalid = $partid.'_'.$id;
686: # Previous answer
687: &decode_previous_answer($Apache::lonhomework::history{"resource.$partid.$id.submission"});
688:
689: # Parameters of <functionplotresponse>
690: my $xmin=&Apache::lonxml::get_param('xmin',$parstack,$safeeval);
691: $xmin=(defined($xmin)?$xmin:-10);
692: my $xmax=&Apache::lonxml::get_param('xmax',$parstack,$safeeval);
693: $xmax=(defined($xmax)?$xmax:10);
694: my $ymin=&Apache::lonxml::get_param('ymin',$parstack,$safeeval);
695: $ymin=(defined($ymin)?$ymin:-10);
696: my $ymax=&Apache::lonxml::get_param('ymax',$parstack,$safeeval);
697: $ymax=(defined($ymax)?$ymax:10);
698: if ($xmax<=$xmin) {
699: &Apache::lonxml::warning('Maximum x-value needs to be larger than minimum value.');
700: $xmax=$xmin+20;
701: }
702: if ($ymax<=$ymin) {
703: &Apache::lonxml::warning('Maximum y-value needs to be larger than minimum value.');
704: $ymax=$ymin+20;
705: }
706: my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
707: my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
708: my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
709: my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval);
710: my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval);
711: if ($target eq 'edit') {
712: $result.=&Apache::edit::start_table($token)
713: .'<tr><td><span class="LC_nobreak">'.&mt('Function Plot Question').'</span></td>'
714: .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
715: .&Apache::edit::deletelist($target,$token)
716: .'</span></td>'
717: ."<td> "
718: .&Apache::edit::end_row()
719: .&Apache::edit::start_spanning_row()
720: ."\n";
721: $result.=&Apache::edit::text_arg('Label x-axis:','xlabel',
722: $token,'6').' '.
723: &Apache::edit::text_arg('Minimum x-value:','xmin',
724: $token,'4').' '.
725: &Apache::edit::text_arg('Maximum x-value:','xmax',
726: $token,'4').' '.
727: &Apache::edit::select_arg('x-axis visible:','xaxisvisible',
728: ['yes','no'],$token).'<br />'.
729: &Apache::edit::text_arg('Label y-axis:','ylabel',
730: $token,'6').' '.
731: &Apache::edit::text_arg('Minimum y-value:','ymin',
732: $token,'4').' '.
733: &Apache::edit::text_arg('Maximum y-value:','ymax',
734: $token,'4').' '.
735: &Apache::edit::select_arg('y-axis visible:','yaxisvisible',
736: ['yes','no'],$token).'<br />'.
737: &Apache::edit::select_arg('Grid visible:','gridvisible',
738: ['yes','no'],$token).
739: &Apache::edit::end_row().&Apache::edit::start_spanning_row();
740: } elsif ($target eq 'modified') {
741: my $constructtag=&Apache::edit::get_new_args($token,$parstack,
742: $safeeval,'xlabel','xmin','xmax','ylabel','ymin','ymax',
743: 'xaxisvisible','yaxisvisible','gridvisible');
744: if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
745:
746: } elsif ($target eq 'meta') {
747: $result=&Apache::response::meta_package_write('functionplotresponse');
748: } elsif ($target eq 'web') {
749: # paste in the update routine to receive stuff back from the applet
750: $result.=&update_script($internalid);
751: # start the initscript for this applet
752: $result.=&start_init_script($internalid);
753: # put the axis commands inside
754: $result.=&axes_script($internalid,$xmin,$xmax,$ymin,$ymax,$xaxisvisible,$yaxisvisible,$gridvisible);
755: $result.=&axes_label($internalid,$xlabel,$ylabel);
756: # init script is left open
757: } elsif (($target eq 'answer') &&
758: ($env{'form.answer_output_mode'} ne 'tex') &&
759: ($Apache::lonhomework::viewgrades == 'F')) {
760: my (undef,undef,$udom,$uname)=&Apache::lonnet::whichuser();
761: my $windowopen=&Apache::lonhtmlcommon::javascript_docopen();
762: my $start_page = &Apache::loncommon::start_page('Rules Log', undef,
763: {'only_body' => 1,
764: 'bgcolor' => '#FFFFFF',
765: 'js_ready' => 1,});
766: my $end_page = &Apache::loncommon::end_page({'js_ready' => 1,});
767: $uname =~s/\W//g;
768: $udom =~s/\W//g;
769: my $function_name =
770: join('_','LONCAPA_scriptvars',$uname,$udom,
771: $env{'form.counter'},$Apache::lonxml::curdepth);
772: my $rules_var ="<script type=\"text/javascript\">
773: // <![CDATA[
774: function $function_name() {newWindow=open('','new_W','width=500,height=500,scrollbars=1,resizable=yes');newWindow.$windowopen;newWindow.document.writeln('$start_page<pre>".
775: $Apache::functionplotresponse::ruleslog.
776: "<\\/pre>$end_page');newWindow.document.close();newWindow.focus()}
777: // ]]>
778: </script><a href=\"javascript:$function_name();void(0);\">".&mt('Rules Log')."</a><br />";
779: &Apache::lonxml::add_script_result($rules_var);
780: }
781:
782: return $result;
783: }
784:
785: sub compare_rel {
786: my ($relationship,$value,$realval,$tol)=@_;
787: # is the real value defined?
788: unless (defined($realval)) {
789: if ($relationship eq 'eq') {
790: if ($value eq 'undef') {
791: return 1;
792: } else {
793: return 0;
794: }
795: } elsif ($relationship eq 'ne') {
796: if ($value eq 'undef') {
797: return 0;
798: } else {
799: return 1;
800: }
801: } else {
802: return 0;
803: }
804: }
805:
806: # it is defined.
807: if ($relationship eq 'gt') {
808: return ($realval>$value);
809: } elsif ($relationship eq 'ge') {
810: return ($realval>$value-$tol);
811: } elsif ($relationship eq 'lt') {
812: return ($realval<$value);
813: } elsif ($relationship eq 'le') {
814: return ($realval<$value+$tol);
815: } elsif ($relationship eq 'ne') {
816: return (abs($value-$realval)>$tol);
817: } else {
818: return (abs($value-$realval)<$tol);
819: }
820: return 0;
821: }
822:
823: sub addlog {
824: my ($text)=@_;
825: $Apache::functionplotresponse::ruleslog.=$text.'<br />';
826: }
827:
828: sub actualval {
829: my ($i,$xmin,$xmax)=@_;
830: return $xmin+$i/400.*($xmax-$xmin);
831: }
832:
833: sub functionplotrulecheck {
834: my ($rule,$xmin,$xmax,$ymin,$ymax)=@_;
835:
836: my ($label,$derivative,$xinitial,$xinitiallabel,$xfinal,$xfinallabel,$minimumlength,$maximumlength,$relationship,$value,$percent)
837: =split(/\:/,$rule);
838: $percent=($percent>0?$percent:5);
839: &addlog("=================");
840: &addlog("Rule $label for ".('function itself','first derivative','second derivative')[$derivative]." $relationship $value");
841: my $li=0;
842: my $lh=400;
843:
844: # Special case: the upper boundary was not defined
845: # and needs to be set to the value where
846: # the condition is not true anymore => set flag
847:
848: my $findupper=0;
849: if (($xfinal eq '')
850: && (!defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}))
851: && ($xfinallabel)) {
852: $findupper=1;
853: }
854:
855: # if a hard value is set for the boundaries, it overrides the label
856: if (($xinitial ne '') && ($xinitiallabel ne '') && ($xinitiallabel ne 'start')) {
857: $li=&array_index($xmin,$xmax,$xinitial);
858: $Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel}=$li;
859: }
860: if (($xfinal ne '') && ($xfinallabel ne '') && ($xfinallabel ne 'end')) {
861: $lh=&array_index($xmin,$xmax,$xfinal);
862: $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$lh;
863: }
864: # if the label is defined, use it
865: if (defined($Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel})) {
866: &addlog("Using lower label $xinitiallabel");
867: $li=$Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel};
868: } else {
869: $li=&array_index($xmin,$xmax,$xinitial);
870: }
871: unless ($findupper) {
872: if (defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel})) {
873: &addlog("Using upper label $xfinallabel");
874: $lh=$Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}-1;
875: } else {
876: $lh=&array_index($xmin,$xmax,$xfinal);
877: }
878: }
879: # Basic sanity checks
880: if ($li<0) { $li=0; }
881: if ($lh>400) { $lh=400; }
882: if ($li>$lh) {
883: $lh=$li;
884: }
885:
886: &addlog("Boundaries: x=".&actualval($li,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$li]."; index $li)) to x=".
887: &actualval($lh,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$lh]."; index $lh))");
888: if ($findupper) {
889: &addlog("Looking for label $xfinallabel");
890: }
891: my $tol=$percent*($ymax-$ymin)/100;
892: if ($xmax>$xmin) {
893: if ($derivative==2) {
894: $tol=4.*$tol/($xmax-$xmin);
895: } elsif ($derivative==1) {
896: $tol=2.*$tol/($xmax-$xmin);
897: }
898: }
899: for (my $i=$li; $i<=$lh; $i++) {
900: my $val;
901: if ($derivative==2) {
902: $val=$Apache::functionplotresponse::d2funcdx2[$i];
903: } elsif ($derivative==1) {
904: $val=$Apache::functionplotresponse::dfuncdx[$i];
905: } else {
906: $val=$Apache::functionplotresponse::func[$i];
907: }
908: unless (&compare_rel($relationship,$value,$val,$tol)) {
909: &addlog("Condition not fulfilled at x=".&actualval($i,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$i]."; index $i)");
910: &addlog("Actual value ".(defined($val)?$val:'undef').", expected $value, tolerance $tol");
911: if (($findupper) && ($i>$li)) {
912: # check for minimum and maximum lengths
913: my $length=&actualval($i,$xmin,$xmax)-&actualval($li,$xmin,$xmax);
914: if ($minimumlength) {
915: if ($length<$minimumlength) {
916: &addlog("Rule $label failed, actual length $length, minimum length $minimumlength");
917: return 0;
918: }
919: }
920: if ($maximumlength) {
921: if ($length>$maximumlength) {
922: &addlog("Rule $label failed, actual length $length, maximum length $maximumlength");
923: return 0;
924: }
925: }
926: $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$i;
927: &addlog("Rule $label passed, setting label $xfinallabel");
928: return 1;
929: } else {
930: &addlog("Rule $label failed.");
931: return 0;
932: }
933: }
934: }
935: &addlog("Rule $label passed.");
936: return 1;
937: }
938:
939: sub end_functionplotresponse {
940: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
941: &Apache::response::end_response;
942:
943: my $result;
944: my $id=$Apache::inputtags::response[-1];
945: my $partid=$Apache::inputtags::part;
946: my $internalid = $partid.'_'.$id;
947:
948: if ($target eq 'edit') { $result=&Apache::edit::end_table(); }
949: if ($target eq 'grade'
950: && &Apache::response::submitted()
951: && $Apache::lonhomework::type eq 'exam') {
952:
953: &Apache::response::scored_response($partid,$id);
954:
955: } elsif ($target eq 'grade'
956: && &Apache::response::submitted()
957: && $Apache::lonhomework::type ne 'exam') {
958: my ($response,%coords)=&get_answer_from_form_fields($internalid);
959: $Apache::lonhomework::results{"resource.$partid.$id.submission"}=$response;
960: my %previous=&Apache::response::check_for_previous($response,$partid,$id);
961: #
962: # Actually grade
963: #
964: my $xmin=&Apache::lonxml::get_param('xmin',$parstack,$safeeval);
965: $xmin=(defined($xmin)?$xmin:-10);
966: my $xmax=&Apache::lonxml::get_param('xmax',$parstack,$safeeval);
967: $xmax=(defined($xmax)?$xmax:10);
968: my $ymin=&Apache::lonxml::get_param('ymin',$parstack,$safeeval);
969: $ymin=(defined($ymin)?$ymin:-10);
970: my $ymax=&Apache::lonxml::get_param('ymax',$parstack,$safeeval);
971: $ymax=(defined($ymax)?$ymax:10);
972:
973: my $ad='';
974: undef %Apache::functionplotresponse::functionplotrulelabels;
975: $Apache::functionplotresponse::ruleslog='';
976: $Apache::functionplotresponse::functionplotrulelabels{'start'}=400;
977: $Apache::functionplotresponse::functionplotrulelabels{'end'}=0;
978: if (&populate_arrays($internalid,$xmin,$xmax) eq 'no_func') {
979: $ad='NOT_FUNCTION';
980: } else {
981: &addlog("Start of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'start'},$xmin,$xmax)." (index ".
982: $Apache::functionplotresponse::functionplotrulelabels{'start'}.")");
983: &addlog("End of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'end'},$xmin,$xmax)." (index ".
984: $Apache::functionplotresponse::functionplotrulelabels{'end'}.")");
985:
986: # We have a function that we can actually grade, go through the spline rules.
987: foreach my $rule (@Apache::functionplotresponse::functionplotrules) {
988: unless (&functionplotrulecheck($rule,$xmin,$xmax,$ymin,$ymax)) {
989: $ad='INCORRECT';
990: last;
991: }
992: }
993: # If it's not wrong, it's correct
994: unless ($ad) { $ad='EXACT_ANS' };
995: }
996:
997: #
998: # Store grading info
999: #
1000: $Apache::lonhomework::results{"resource.$partid.$id.awarddetail"}=$ad;
1001: &Apache::response::handle_previous(\%previous,$ad);
1002: } elsif ($target eq 'web') {
1003: # Now is the time to render all of the stored splines
1004: foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
1005: $result.=&generate_spline($internalid,$label);
1006: }
1007: # close the init script
1008: $result.=&end_init_script();
1009: # register all splines in this response
1010: $result.='<input type="hidden" name="HWVAL_AllSplines_'.$internalid.'" value="'.
1011: join(',',keys(%Apache::functionplotresponse::splineorder)).'" />'."\n";
1012: foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
1013: $result.='<input type="hidden" name="HWVAL_SplineOrder_'.$internalid.'_'.$label.'" value="'.
1014: $Apache::functionplotresponse::splineorder{$label}.'" />'."\n";
1015: }
1016: # generate the input fields
1017: $result.=$Apache::functionplotresponse::inputfields;
1018: # actually start the <applet>-tag
1019: $result.=&geogebra_startcode($internalid);
1020: # load the spline bytecode
1021: $result.=&geogebra_spline_program();
1022: # set default parameters
1023: $result.=&geogebra_default_parameters($internalid);
1024: # close the <applet>-tag
1025: $result.=&geogebra_endcode();
1026: }
1027: return $result;
1028: }
1029:
1030: 1;
1031:
1032: __END__
1033:
1034: =head1 NAME
1035:
1036: Apache::functionplotresponse.pm;
1037:
1038: =head1 SYNOPSIS
1039:
1040: Handles tags associated with accepting function plots.
1041:
1042: This is part of the LearningOnline Network with CAPA project
1043: described at http://www.lon-capa.org.
1044:
1045: =head1 HANDLER SUBROUTINE
1046:
1047: start_functionplotresponse()
1048:
1049: =head1 OTHER SUBROUTINES
1050:
1051: =over
1052:
1053: =item end_functionplotresponse()
1054:
1055: =back
1056:
1057: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>