Annotation of loncom/homework/functionplotresponse.pm, revision 1.42

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

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>