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