File:  [LON-CAPA] / loncom / homework / functionplotresponse.pm
Revision 1.40: download - view: text, annotated - select for diffs
Fri Nov 19 17:20:44 2010 UTC (13 years, 7 months ago) by www
Branches: MAIN
CVS tags: HEAD
New interface code

    1: # LearningOnline Network with CAPA
    2: # option list style responses
    3: #
    4: # $Id: functionplotresponse.pm,v 1.40 2010/11/19 17:20:44 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="ggbBase64" value="UEsDBBQACAAIADhQET0AAAAAAAAAAAAAAAASAAAAZ2VvZ2VicmFfbWFjcm8ueG1s7Z1bb+PGGYavk19BMDfexkvP+QCsEqzOuWi7gIveBG1By7RXrSwJsqyY+fWdGZLS2pQtzdqWSPoDApOSqCH5vSTnmdH7bj79en8zCVbJ4nY8m7ZCHKEwSKaj2eV4et0K75ZXH1X46y8/frpOZtfJxSIOrmaLm3jZCmlEQvP+TTxazILRzeXf4pukFZ7PJ+NpQsJgOZtNtrw1TCbz9Vu/f8Gn5/j0Czk9J/8Kg/FoNu2PJ+YrYXD7dfbHb9N/mG+040UrXC7ukvXefpvO75ZBjFrh5zCIsVnEZklaYdssqFnE4Vmx7d/vluuNV9nW7VW29ee228zs9NY0P1qa8w+W42W2//hu+XW2sGuX8dK+Y7ZMJslNMl0Gy3Ru3pnPxtNlGEzii2Rij+SXH3/4ZI86mF38Nxkt82MuPr+KJ7eJ3d8Pn8znndlktghM86bY1+7vhfsbT+ZfY7NmRHCbTuI0WQSreGI/zd8xzf11dpk8eDeejo0m9gRul8ncNoBNCedJcpkrmh2yWZmbJp2y3xzQaDZbXN4G962QRBwhKpEginGFJA2DtBWyiDPNJOVYEiwFEmHwZ9au+7orxPn4z/yQqKvqWV6sHWVrN6JsLMIIESqJ4EIiJiXP6yYoUoQIoYggFPHXq5u54l9cOML58UtHIkW4FJJQIqhQQrrK8UhizqRCmHPCNCeveMU1pXIsYlIrIYS57jBhiOWV4+ZdLZCWGEtMsGfl7ueL5NZ2BUU54ov/3Jse4X6erZ7cfwhawQmJUPCX4P7fJzRCH4KPAS1eE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C5OHNkOH/vrO7YT2EXqrQdw/Gb8/ObL2eO5keQI2gjV5jSazCiBtlSVaOuc9nb3OaWP64esBlVDoTnZKd1wm9N4wqjDe7F++JSZvToRLr3Lq4BTTndcGqDEdBp4ZfYA9gPO+7OQguvLz+IPlNbcDIHkue16vMXqHrGyqTbCjNupv7CTwn4TR1GBJlKVOV0kKB2/XkFbUXKZ0/ksICyn7M6IUOyse6XFm2qtc7+R7xAhxIg3wIwwh2VTH2gGfSlFJXjrgvE60ImQk6jsPqfLhCEliHqPWpNoFthKpXS1vRgLDTn/Bq3w7iWbLJaLmMX4wz88dgkWlqSTZJGweTRny9UqWWIKUS8KYYtJzFJkZctZki5SluChf9v81XDcgrVYSkP4GcyYz1qL6ppwt3k2X5W8QZ0SrX3ine21b4N4gLb24m7DvGkX45e2ljBgEVZpD+WhUOdtyFscqF8unT/i9RT1k5JKE+0CRf31sBZh9T5O6NVr5n1m3mPgcKRXe7Ri3sOvRVi9lxRtkDYEHo1Rj1XhZ2GIA5Dcde+YG8kLwGagpG+F3YwbbJrDLVLn/6NvCpya921zpYz+E2U2veu37AC6BRm6qsXC9qo35Oi6N5TO66igFA1ug2FICHfF+oUCAlpBrWHUHUYupMtbP3TuHZxNRxFOg0GtpcW3A+OxLpZt51Kfugm3OF05/c4bMGTD8Y2xF0oqbtHLPR3T98f9iA1vzPovUEsHCEyILqxEAgAAlQQAAFBLAQIUABQACAAIADhQET1gj4YNdwsAAFgqAQASAAAAAAAAAAAAAAAAAAAAAABnZW9nZWJyYV9tYWNyby54bWxQSwECFAAUAAgACAA4UBE9TIgurEQCAACVBAAADAAAAAAAAAAAAAAAAAC3CwAAZ2VvZ2VicmEueG1sUEsFBgAAAAACAAIAegAAADUOAAAAAA=="/>
   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,$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: 
  318: sub plot_script {
  319:    my ($id,$function,$fixed)=@_;
  320:    if ($fixed) {
  321: # Use stupid trick to nail this to a location
  322: # Oddly, it seems like only one plot cannot be nailed to a location
  323: # Non-nailed-down plots apparently get overwritten
  324:       return (<<ENDPLOTSCRIPT);
  325:             document.ggbApplet_$id.evalCommand("a=1");
  326:             document.ggbApplet_$id.setVisible("a",false);
  327:             // This MUST be a DEPENDENT OBJECT in order to be locked down:
  328:             document.ggbApplet_$id.evalCommand("y=a*($function)");
  329: ENDPLOTSCRIPT
  330:    } else {
  331:        return "document.ggbApplet_$id.evalCommand('y=$function')";
  332:    }
  333: }
  334: 
  335: #
  336: # Subroutine that generates code for spline $label based on stored information
  337: #
  338: 
  339: sub generate_spline {
  340:    my ($id,$label,$xmin,$xmax,$ymin,$ymax)=@_;
  341:    my $result='';
  342:    my $order=$Apache::functionplotresponse::splineorder{$label};
  343:    my $x=$Apache::functionplotresponse::splineinitx{$label};
  344:    my $y=$Apache::functionplotresponse::splineinity{$label};
  345:    my $sx=$Apache::functionplotresponse::splinescalex{$label};
  346:    my $sy=$Apache::functionplotresponse::splinescaley{$label};
  347:    my @coords=();
  348:    foreach my $i (1..$order) {
  349:        $result.=&new_point_coordinate($id,$label.'P'.$i,$x,$y);
  350:        my $xp=$x;
  351:        $x+=$sx/(2.*($order-1));
  352:        push(@coords,$label.'P'.$i);
  353:        $result.=&new_slope_coordinate($id,$label.'S'.$i,$x,$y+$sy,$label.'P'.$i,$xp,$y,$xmin,$xmax,$ymin,$ymax);
  354:        $x+=$sx/(2.*($order-1));
  355:        push(@coords,$label.'S'.$i);
  356:    }
  357:    $result.='document.ggbApplet_'.$id.'.evalCommand("Spline'.$order.'['.join(',',@coords).']");'."\n";
  358:    return $result;
  359: }
  360: #
  361: # <backgroundplot function="..." fixed="yes/no" />
  362: #
  363: sub start_backgroundplot {
  364:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  365:    my $result='';
  366:    my $internalid = $Apache::inputtags::part.'_'.$Apache::inputtags::response[-1];
  367:    my $function=&Apache::lonxml::get_param('function',$parstack,$safeeval);
  368:    my $fixed=(&Apache::lonxml::get_param('fixed',$parstack,$safeeval)=~/on|true|yes|1/i?1:0);
  369:  
  370:    unless ($function) { $function="0"; }
  371:    if ($target eq 'web') {
  372:       $result.=&plot_script($internalid,$function,$fixed);
  373:    } elsif ($target eq 'edit') {
  374:         $result=&Apache::edit::tag_start($target,$token,'Background Function Plot').
  375:              &Apache::edit::text_arg('Function:','function',
  376:                                      $token,'16').
  377:              &Apache::edit::select_arg('Fixed location:','fixed',
  378:                                   ['yes','no'],$token).
  379:              &Apache::edit::end_row();
  380:   } elsif ($target eq 'modified') {
  381:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  382:                                                  $safeeval,'function','fixed');
  383:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
  384:   }
  385:   return $result;
  386: }
  387: 
  388: sub end_backgroundplot {
  389:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  390:    my $result='';
  391:    if ($target eq 'edit') {
  392:        $result=&Apache::edit::end_table();
  393:    }
  394:    return $result;
  395: }
  396: 
  397: #
  398: # <functionplotrule ... />
  399: #
  400: sub start_functionplotrule {
  401:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  402:    my $result='';
  403:    my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
  404:    $Apache::functionplotresponse::counter++;
  405:    if ($label=~/\W/) {
  406:       &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
  407:    }
  408:    $label=~s/\W//gs;
  409:    unless ($label) {
  410:       $label='R'.$Apache::functionplotresponse::counter;
  411:    } else {
  412:       $label='R'.$label;
  413:    }
  414:    if ($Apache::functionplotresponse::splineorder{$label}) {
  415:        &Apache::lonxml::error(&mt('Rule indices must be unique.'));
  416:    }
  417: 
  418: 
  419:    if ($target eq 'grade') {
  420: # Simply remember - in order - for later
  421:       my $beginninglabel=&Apache::lonxml::get_param('xinitiallabel',$parstack,$safeeval);
  422:       my $endinglabel=&Apache::lonxml::get_param('xfinallabel',$parstack,$safeeval);
  423:       if (($beginninglabel=~/\W/) || ($endinglabel=~/W/)) {
  424:           &Apache::lonxml::warning(&mt('Rule labels must be alphanumeric.'));
  425:       }
  426:       $beginninglabel=~s/\W//gs;
  427:       $endinglabel=~s/\W//gs;
  428:       my $relationship=&Apache::lonxml::get_param('relationship',$parstack,$safeeval);
  429:       $relationship=~s/\W//gs;
  430:       $relationship=lc($relationship);
  431:       unless ($relationship=~/^(eq|ge|gt|le|lt|ne)$/) {
  432:           &Apache::lonxml::warning(&mt('Rule relationship not defined.'));
  433:           $relationship='eq';
  434:       }
  435:       my $derivative=&Apache::lonxml::get_param('derivativeorder',$parstack,$safeeval);
  436:       unless (($derivative==0) || ($derivative==1) || ($derivative==2)) {
  437:          &Apache::lonxml::warning(&mt('Rule derivative not defined.'));
  438:          $derivative=0;
  439:       }
  440:       push(@Apache::functionplotresponse::functionplotrules,join(':',(
  441:            $label,
  442:            $derivative,
  443:            &Apache::lonxml::get_param('xinitial',$parstack,$safeeval),
  444:            $beginninglabel,
  445:            &Apache::lonxml::get_param('xfinal',$parstack,$safeeval),
  446:            $endinglabel,
  447:            &Apache::lonxml::get_param('minimumlength',$parstack,$safeeval),
  448:            &Apache::lonxml::get_param('maximumlength',$parstack,$safeeval),
  449:            $relationship,
  450:            &Apache::lonxml::get_param('value',$parstack,$safeeval),
  451:            &Apache::lonxml::get_param('percenterror',$parstack,$safeeval)
  452:           )));
  453:    } elsif ($target eq 'edit') {
  454:         $result=&Apache::edit::tag_start($target,$token,'Function Plot Evaluation Rule').
  455:              &Apache::edit::text_arg('Index/Name:','index',
  456:                                      $token,'10').'&nbsp;'.
  457:              &Apache::edit::select_arg(&mt('Function:'),'derivativeorder',
  458:                                   [['0','Function itself'],
  459:                                    ['1','First derivative'],
  460:                                    ['2','Second derivative']],$token).'<br />'.
  461:              &Apache::edit::text_arg('(Initial) x-value:','xinitial',
  462:                                       $token,'8').
  463:              &Apache::edit::select_or_text_arg('(Initial) x-value label:','xinitiallabel',
  464:                                                [['start','Start of Plot']],$token,'8').'<br />'.
  465: 
  466:              &Apache::edit::text_arg('Optional final x-value for ranges:','xfinal',
  467:                                       $token,'8').
  468:              &Apache::edit::select_or_text_arg('Optional final x-value label:','xfinallabel',
  469:                                                [['end','End of Plot']],$token,'8').'<br />'.
  470:              &Apache::edit::text_arg('Optional minimum length for range:','minimumlength',
  471:                                      $token,'8').
  472:              &Apache::edit::text_arg('Optional maximum length for range:','maximumlength',
  473:                                      $token,'8').'<br />'.
  474:              &Apache::edit::select_or_text_arg(&mt('Relationship:'),'relationship',
  475:                                   [['eq','equal'],
  476:                                    ['ne','not equal'],
  477:                                    ['ge','greater than or equal'],
  478:                                    ['gt','greater than'],
  479:                                    ['lt','less than'],
  480:                                    ['le','less than or equal']],$token).
  481:              $result.= &Apache::edit::select_or_text_arg('Value:','value',
  482:                                                [['undef','not defined']],$token,'8').
  483:              &Apache::edit::text_arg('Percent error:','percenterror',
  484:                                      $token,'8').
  485:              &Apache::edit::end_row();
  486:   } elsif ($target eq 'modified') {
  487:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  488:                                                  $safeeval,'index','derivativeorder',
  489:                                                            'xinitial','xinitiallabel','xfinal','xfinallabel',
  490:                                                            'minimumlength','maximumlength',
  491:                                                            'relationship','value','percenterror');
  492:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
  493:    }
  494:    return $result;
  495: }
  496: 
  497: sub end_functionplotrule {
  498:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  499:    my $result='';
  500:    if ($target eq 'edit') {
  501:        $result=&Apache::edit::end_table();
  502:    }
  503:    return $result;
  504: }
  505: 
  506: 
  507: #
  508: # <spline index="..." order="1,2,3,4" initx="..." inity="..." scalex="..." scaley="..." />
  509: #
  510: # Unfortunately, GeoGebra seems to want all splines after everything else, so we need to store them
  511: #
  512: sub start_spline {
  513:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  514:    my $result='';
  515:    if ($target eq 'web') {
  516:       my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
  517:       $Apache::functionplotresponse::counter++;
  518:       if ($label=~/\W/) {
  519:          &Apache::lonxml::warning(&mt('Spline indices should only contain alphanumeric characters.'));
  520:       }
  521:       $label=~s/\W//gs;
  522:       unless ($label) { 
  523:          $label='S'.$Apache::functionplotresponse::counter; 
  524:       } else {
  525:          $label='S'.$label;
  526:       }
  527:       if ($Apache::functionplotresponse::splineorder{$label}) {
  528:          &Apache::lonxml::error(&mt('Spline indices must be unique.'));
  529:       }
  530: 
  531:       my $order=&Apache::lonxml::get_param('order',$parstack,$safeeval);
  532:       if ($order<2) { $order=2; }
  533:       if ($order>8) { $order=8; }
  534:       $Apache::functionplotresponse::splineorder{$label}=$order;
  535: 
  536:       my $x=&Apache::lonxml::get_param('initx',$parstack,$safeeval);
  537:       unless ($x) { $x=0; }
  538:       $Apache::functionplotresponse::splineinitx{$label}=$x;
  539: 
  540:       my $y=&Apache::lonxml::get_param('inity',$parstack,$safeeval);
  541:       unless ($y) { $y=0; }
  542:       $Apache::functionplotresponse::splineinity{$label}=$y;
  543: 
  544:       my $sx=&Apache::lonxml::get_param('scalex',$parstack,$safeeval);
  545:       unless ($sx) { $sx=$order; }
  546:       $Apache::functionplotresponse::splinescalex{$label}=$sx;
  547: 
  548:       my $sy=&Apache::lonxml::get_param('scaley',$parstack,$safeeval);
  549:       unless ($sy) { $sy=2; }
  550:       $Apache::functionplotresponse::splinescaley{$label}=$sy;
  551:    } elsif ($target eq 'edit') {
  552:         $result=&Apache::edit::tag_start($target,$token,'Spline').
  553:              &Apache::edit::text_arg('Index:','index',
  554:                                      $token,'4').'&nbsp;'.
  555:              &Apache::edit::select_arg('Order:','order',
  556:                                   ['2','3','4','5','6','7','8','9'],$token).'&nbsp;'.
  557:              &Apache::edit::text_arg('Initial x-value:','initx',
  558:                                      $token,'4').'&nbsp;'.
  559:              &Apache::edit::text_arg('Initial y-value:','inity',
  560:                                      $token,'4').'&nbsp;'.
  561:              &Apache::edit::text_arg('Scale x:','scalex',
  562:                                      $token,'4').'&nbsp;'.
  563:              &Apache::edit::text_arg('Scale y:','scaley',
  564:                                      $token,'4').
  565:              &Apache::edit::end_row();
  566:   } elsif ($target eq 'modified') {
  567:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  568:                                                  $safeeval,'index','order','initx','inity',
  569:                                                            'scalex','scaley');
  570:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
  571:   }
  572:   return $result;
  573: }
  574: 
  575: sub end_spline {
  576:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  577:    my $result='';
  578:    if ($target eq 'edit') {
  579:        $result=&Apache::edit::end_table();
  580:    }
  581:    return $result;
  582: }
  583:  
  584: sub end_init_script {
  585:     return (<<ENDENDINIT);
  586: }
  587: // ]]>
  588: </script>
  589: ENDENDINIT
  590: }
  591: 
  592: #
  593: # Storing and restoring spline coordinates from part answers
  594: #
  595: sub decode_previous_answer {
  596:    my ($answer)=@_;
  597:    foreach my $coordinate (split(/\,/,$answer)) {
  598:       my ($key,$value)=split(/\=/,$coordinate);
  599:       $Apache::functionplotresponse::previous{$key}=$value;
  600:    }
  601: }
  602: 
  603: sub get_answer_from_form_fields {
  604:    my ($id)=@_;
  605:    my $answer='';
  606:    my %coords=();
  607:    foreach my $field (keys(%env)) {
  608:       if ($field=~/^form\.HWVAL\_$id/) {
  609:          $field=~/^form\.(.*)$/;
  610:          $coords{$1}=$env{$field};
  611:       }
  612:    }
  613:    $answer=join(',',map { $_.'='.$coords{$_} } (sort(keys(%coords))));
  614:    return ($answer,%coords);
  615: }
  616: 
  617: #
  618: # The following functions calculate the cubic-hermite splines server-side
  619: #
  620: 
  621: sub cubic_hermite {
  622:    my ($t,$p1,$s1,$p2,$s2)=@_;
  623:    return (2.*$t*$t*$t-3.*$t*$t+1.)*$p1 + 5.*($t*$t*$t-2.*$t*$t+$t)*($s1-$p1)+
  624:           (-2.*$t*$t*$t+3.*$t*$t)  *$p2 + 5.*($t*$t*$t-$t*$t)      *($s2-$p2);
  625: }
  626: 
  627: #
  628: # d/dt(...)
  629: # 
  630: 
  631: sub ddt_cubic_hermite {
  632:    my ($t,$p1,$s1,$p2,$s2)=@_;
  633:    return (6.*$t*$t-6.*$t) *$p1 + 5.*(3.*$t*$t-4.*$t+1.)*($s1-$p1)+
  634:           (-6.*$t*$t+6.*$t)*$p2 + 5.*(3.*$t*$t-2.*$t)   *($s2-$p2);
  635: }
  636: 
  637: #
  638: # d^2/dt^2(...)
  639: #
  640: 
  641: sub d2dt2_cubic_hermite {
  642:    my ($t,$p1,$s1,$p2,$s2)=@_;
  643:    return (12.*$t-6.) *$p1 + 5.*(6.*$t-4.)*($s1-$p1)+
  644:           (-12.*$t+6.)*$p2 + 5.*(6.*$t-2.)*($s2-$p2);
  645: }
  646: 
  647: #
  648: # Array index calculation
  649: #
  650: sub array_index {
  651:    my ($xmin,$xmax,$x)=@_;
  652:    if ($x ne '') {
  653:       return int(($x-$xmin)/($xmax-$xmin)*400.+0.5);
  654:    } else {
  655:       return undef;
  656:    }
  657: }
  658: 
  659: #
  660: # Populate the arrays
  661: #
  662: 
  663: sub populate_arrays {
  664:     my ($id,$xmin,$xmax)=@_;
  665:     for (my $i=0; $i<=400; $i++) {
  666:        $Apache::functionplotresponse::actualxval[$i]=undef;
  667:        $Apache::functionplotresponse::func[$i]=undef;
  668:        $Apache::functionplotresponse::dfuncdx[$i]=undef;
  669:        $Apache::functionplotresponse::d2funcd2x[$i]=undef;
  670:     }
  671:     unless ($xmax>$xmin) { return 'no_func'; }
  672: # Run over all splines in response
  673:     foreach my $label (split(/\,/,$env{"form.HWVAL_AllSplines_$id"})) {
  674:         my $xiold=-1;
  675: # Run over all points in spline
  676:         for (my $i=1; $i<$env{"form.HWVAL_SplineOrder_".$id."_".$label}; $i++) {
  677:             my $ni=$i+1;
  678:             my @xparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_x'},
  679:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_x'},
  680:                         $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_x'},
  681:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_x'});
  682:             my @yparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_y'},
  683:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_y'},
  684:                         $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_y'},
  685:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_y'});
  686: # Run in small steps over spline parameter
  687:             for (my $t=0; $t<=1; $t+=0.0001) {
  688:                 my $xreal=&cubic_hermite($t,@xparms);
  689:                 my $xi=&array_index($xmin,$xmax,$xreal);
  690:                 if ($xi<$xiold) { return 'no_func'; }
  691:                 if (($xi>$xiold) && ($xi>=0) && ($xi<=400)) {
  692:                    if (defined($Apache::functionplotresponse::func[$xi])) { return 'no_func'; }
  693:                    $xiold=$xi;
  694:                    $Apache::functionplotresponse::actualxval[$xi]=$xreal;
  695: # Function value
  696:                    my $funcval=&cubic_hermite($t,@yparms);
  697:                    $Apache::functionplotresponse::func[$xi]=$funcval;
  698:                    if (defined($funcval)) {
  699:                       if ($xi<$Apache::functionplotresponse::functionplotrulelabels{'start'}) {
  700:                          $Apache::functionplotresponse::functionplotrulelabels{'start'}=$xi;
  701:                       }
  702:                       if ($xi>$Apache::functionplotresponse::functionplotrulelabels{'end'}) {
  703:                          $Apache::functionplotresponse::functionplotrulelabels{'end'}=$xi;
  704:                       }
  705:                    }
  706: # Chain rule
  707: # dy/dx=dy/dt/(dx/dt)
  708:                    my $dxdt=&ddt_cubic_hermite($t,@xparms);
  709:                    if ($dxdt) {
  710:                       $Apache::functionplotresponse::dfuncdx[$xi]=&ddt_cubic_hermite($t,@yparms)/$dxdt;
  711: # Second derivative
  712:                       $Apache::functionplotresponse::d2funcdx2[$xi]=
  713:                          ($dxdt*&d2dt2_cubic_hermite($t,@yparms)-&ddt_cubic_hermite($t,@yparms)*&d2dt2_cubic_hermite($t,@xparms))/
  714:                          ($dxdt*$dxdt*$dxdt);
  715:                    }
  716:                 }
  717:             }
  718:         }
  719:     }
  720: }
  721: 
  722: #
  723: # Implementation of <functionplotresponse>
  724: #
  725: 
  726: sub start_functionplotresponse {
  727:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  728:   my $result='';
  729: # To remember the splines - somehow, they need to come last
  730:   undef %Apache::functionplotresponse::splineorder;
  731:   undef %Apache::functionplotresponse::splineinitx;
  732:   undef %Apache::functionplotresponse::splineinity;
  733:   undef %Apache::functionplotresponse::splinescalex;
  734:   undef %Apache::functionplotresponse::splinescaley;
  735: # Remember input fields, etc
  736:   undef %Apache::functionplotresponse::previous;
  737:   $Apache::functionplotresponse::inputfields='';
  738:   $Apache::functionplotresponse::counter=0;
  739: # Remember rules
  740:   undef @Apache::functionplotresponse::functionplotrules;
  741: # Remember failed rules
  742:   if ($target eq 'grade') {
  743:      undef @Apache::functionplotresponse::failedrules;
  744:   }
  745: # Delete previous awards
  746:   undef $Apache::functionplotresponse::awarddetail;
  747: # Part and ID
  748:   my $partid=$Apache::inputtags::part;
  749:   my $id=&Apache::response::start_response($parstack,$safeeval);
  750: # Internal ID to mark the applet and its coordinates
  751:   my $internalid = $partid.'_'.$id;
  752: # Previous answer
  753:   &decode_previous_answer($Apache::lonhomework::history{"resource.$partid.$id.submission"});
  754: 
  755: # Parameters of <functionplotresponse>
  756:   my $xmin=&Apache::lonxml::get_param('xmin',$parstack,$safeeval);
  757:   $xmin=(defined($xmin)?$xmin:-10);
  758:   my $xmax=&Apache::lonxml::get_param('xmax',$parstack,$safeeval);
  759:   $xmax=(defined($xmax)?$xmax:10);
  760:   my $ymin=&Apache::lonxml::get_param('ymin',$parstack,$safeeval);
  761:   $ymin=(defined($ymin)?$ymin:-10);
  762:   my $ymax=&Apache::lonxml::get_param('ymax',$parstack,$safeeval);
  763:   $ymax=(defined($ymax)?$ymax:10);
  764:   if ($xmax<=$xmin) {
  765:      &Apache::lonxml::warning('Maximum x-value needs to be larger than minimum value.');
  766:      $xmax=$xmin+20;
  767:   }
  768:   if ($ymax<=$ymin) {
  769:      &Apache::lonxml::warning('Maximum y-value needs to be larger than minimum value.');
  770:      $ymax=$ymin+20;
  771:   }
  772:   my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
  773:   my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
  774:   my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
  775:   my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval);
  776:   my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval);
  777:   if ($target eq 'edit') {
  778:     $result.=&Apache::edit::start_table($token)
  779:        .'<tr><td><span class="LC_nobreak">'.&mt('Function Plot Question').'</span></td>'
  780:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
  781:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'
  782:        .&Apache::edit::insertlist($target,$token)
  783:        .'</span></td>'
  784:        ."<td>&nbsp;"
  785:        .&Apache::edit::end_row()
  786:        .&Apache::edit::start_spanning_row()
  787:        ."\n";
  788:     $result.=&Apache::edit::text_arg('Label x-axis:','xlabel',
  789:                                      $token,'6').'&nbsp;'.
  790:              &Apache::edit::text_arg('Minimum x-value:','xmin',
  791:                                      $token,'4').'&nbsp;'.
  792:              &Apache::edit::text_arg('Maximum x-value:','xmax',
  793:                                      $token,'4').'&nbsp;'.
  794:              &Apache::edit::select_arg('x-axis visible:','xaxisvisible',
  795:                                   ['yes','no'],$token).'<br />'.
  796:              &Apache::edit::text_arg('Label y-axis:','ylabel',
  797:                                      $token,'6').'&nbsp;'.
  798:              &Apache::edit::text_arg('Minimum y-value:','ymin',
  799:                                      $token,'4').'&nbsp;'.
  800:              &Apache::edit::text_arg('Maximum y-value:','ymax',
  801:                                      $token,'4').'&nbsp;'.
  802:              &Apache::edit::select_arg('y-axis visible:','yaxisvisible',
  803:                                   ['yes','no'],$token).'<br />'.
  804:              &Apache::edit::select_arg('Grid visible:','gridvisible',
  805:                                   ['yes','no'],$token).
  806:              &Apache::edit::end_row().&Apache::edit::start_spanning_row();
  807:   } elsif ($target eq 'modified') {
  808:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  809:                                                  $safeeval,'xlabel','xmin','xmax','ylabel','ymin','ymax',
  810:                                                            'xaxisvisible','yaxisvisible','gridvisible');
  811:     if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
  812: 
  813:   } elsif ($target eq 'meta') {
  814:        $result=&Apache::response::meta_package_write('functionplotresponse');
  815:   } elsif (($target eq 'answer') &&
  816:             ($env{'form.answer_output_mode'} ne 'tex') &&
  817:             ($Apache::lonhomework::viewgrades == 'F')) {
  818:       my (undef,undef,$udom,$uname)=&Apache::lonnet::whichuser();
  819:       my $windowopen=&Apache::lonhtmlcommon::javascript_docopen();
  820:       my $start_page = &Apache::loncommon::start_page('Rules Log', undef,
  821:                                                {'only_body' => 1,
  822:                                                 'bgcolor'   => '#FFFFFF',
  823:                                                 'js_ready'  => 1,});
  824:       my $end_page = &Apache::loncommon::end_page({'js_ready' => 1,});
  825:       $uname =~s/\W//g;
  826:       $udom  =~s/\W//g;
  827:       my $function_name =
  828:                 join('_','LONCAPA_scriptvars',$uname,$udom,
  829:                      $env{'form.counter'},$Apache::lonxml::curdepth);
  830:       my $rules_var ="<script type=\"text/javascript\">
  831: // <![CDATA[
  832:     function $function_name() {newWindow=open('','new_W','width=500,height=500,scrollbars=1,resizable=yes');newWindow.$windowopen;newWindow.document.writeln('$start_page<pre>".
  833:     $Apache::functionplotresponse::ruleslog.
  834:     "<\\/pre>$end_page');newWindow.document.close();newWindow.focus()}
  835: // ]]>
  836: </script><a href=\"javascript:$function_name();void(0);\">".&mt('Rules Log')."</a><br />";
  837:             &Apache::lonxml::add_script_result($rules_var);
  838:         }
  839: 
  840:   return $result;
  841: }
  842: 
  843: sub compare_rel {
  844:    my ($relationship,$value,$realval,$tol)=@_;
  845: # is the real value undefined?
  846:    unless (defined($realval)) {
  847: # the real value is not defined
  848:       if ($relationship eq 'eq') {
  849:          if ($value eq 'undef') {
  850:             return 1;
  851:          } else {
  852:             return 0;
  853:          }
  854:       } elsif ($relationship eq 'ne') {
  855:          if ($value eq 'undef') {
  856:             return 0;
  857:          } else {
  858:             return 1;
  859:          }
  860:       } else {
  861:          return 0;
  862:       }
  863:    }
  864: 
  865: # is the expected value undefined?
  866:    if ($value eq 'undef') {
  867: # but by now we know that the real value is defined
  868:       return 0;
  869:    }
  870: 
  871: # both are defined.
  872:    if ($relationship eq 'gt') {
  873:       return ($realval>$value);
  874:    } elsif ($relationship eq 'ge') {
  875:       return ($realval>$value-$tol);
  876:    } elsif ($relationship eq 'lt') {
  877:       return ($realval<$value);
  878:    } elsif ($relationship eq 'le') {
  879:       return ($realval<$value+$tol);
  880:    } elsif ($relationship eq 'ne') {
  881:       return (abs($value-$realval)>$tol);
  882:    } else {
  883:       return (abs($value-$realval)<$tol);
  884:    }
  885:    return 0;
  886: }
  887: 
  888: sub addlog {
  889:    my ($text)=@_;
  890:    $Apache::functionplotresponse::ruleslog.=$text.'<br />';
  891: }
  892: 
  893: sub actualval {
  894:    my ($i,$xmin,$xmax)=@_;
  895:    return $xmin+$i/400.*($xmax-$xmin);
  896: }
  897:  
  898: sub functionplotrulecheck {
  899:    my ($rule,$xmin,$xmax,$ymin,$ymax)=@_;
  900: 
  901:    my ($label,$derivative,$xinitial,$xinitiallabel,$xfinal,$xfinallabel,$minimumlength,$maximumlength,$relationship,$value,$percent)
  902:       =split(/\:/,$rule);
  903:    $percent=($percent>0?$percent:5);
  904:    &addlog("=================");
  905:    &addlog("Rule $label for ".('function itself','first derivative','second derivative')[$derivative]." $relationship $value");
  906:    my $li=0;
  907:    my $lh=400;
  908: 
  909: # Special case: the upper boundary was not defined
  910: # and needs to be set to the value where
  911: # the condition is not true anymore => set flag
  912: 
  913:    my $findupper=0;
  914:    if (($xfinal eq '')
  915:     && (!defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}))
  916:     && ($xfinallabel)) {
  917:        $findupper=1;
  918:    }
  919: 
  920: # if a hard value is set for the boundaries, it overrides the label
  921:    if (($xinitial ne '') && ($xinitiallabel ne '') && ($xinitiallabel ne 'start')) {
  922:       $li=&array_index($xmin,$xmax,$xinitial);
  923:       $Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel}=$li;
  924:    }
  925:    if (($xfinal ne '') && ($xfinallabel ne '') && ($xfinallabel ne 'end')) {
  926:       $lh=&array_index($xmin,$xmax,$xfinal);
  927:       $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$lh;
  928:    }
  929: # if the label is defined, use it
  930:    if (defined($Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel})) {
  931:       &addlog("Using lower label $xinitiallabel");
  932:       $li=$Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel};
  933:    } else {
  934:       $li=&array_index($xmin,$xmax,$xinitial);
  935:    }
  936:    unless ($findupper) {
  937:       if (defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel})) {
  938:          &addlog("Using upper label $xfinallabel");
  939:          $lh=$Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}-1;
  940:       } else {
  941:          $lh=&array_index($xmin,$xmax,$xfinal);
  942:       }
  943:    }
  944: # Basic sanity checks
  945:    if ($li<0) { $li=0; }
  946:    if ($lh>400) { $lh=400; }
  947:    if (($li>$lh) || (!defined($lh))) {
  948:        $lh=$li;
  949:    }
  950: 
  951:    &addlog("Boundaries: x=".&actualval($li,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$li]."; index $li)) to x=".
  952:                             &actualval($lh,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$lh]."; index $lh))");
  953:    if ($findupper) {
  954:       &addlog("Looking for label $xfinallabel");
  955:    }
  956:    my $tol=$percent*($ymax-$ymin)/100;
  957:    if ($xmax>$xmin) {
  958:       if ($derivative==2) {
  959:          $tol=4.*$tol/($xmax-$xmin);
  960:       } elsif ($derivative==1) {
  961:          $tol=2.*$tol/($xmax-$xmin);
  962:       }
  963:    }
  964:    for (my $i=$li; $i<=$lh; $i++) {
  965:         my $val;
  966:         if ($derivative==2) {
  967:            $val=$Apache::functionplotresponse::d2funcdx2[$i];
  968:         } elsif ($derivative==1) {
  969:            $val=$Apache::functionplotresponse::dfuncdx[$i];
  970:         } else {
  971:            $val=$Apache::functionplotresponse::func[$i];
  972:         }
  973:         unless (&compare_rel($relationship,$value,$val,$tol)) { 
  974:            &addlog("Actual value ".(defined($val)?$val:'undef').", expected $value, tolerance $tol");
  975:            &addlog("Condition not fulfilled at x=".&actualval($i,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$i]."; index $i)");
  976:            if (($findupper) && ($i>$li)) {
  977: # check for minimum and maximum lengths
  978:               my $length=&actualval($i,$xmin,$xmax)-&actualval($li,$xmin,$xmax);
  979:               if ($minimumlength) {
  980:                  if ($length<$minimumlength) {
  981:                     &addlog("Rule $label failed, actual length $length, minimum length $minimumlength");
  982:                     return 0;
  983:                  }
  984:               }
  985:               if ($maximumlength) {
  986:                  if ($length>$maximumlength) {
  987:                     &addlog("Rule $label failed, actual length $length, maximum length $maximumlength");
  988:                     return 0;
  989:                  }
  990:               }
  991:               $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$i;
  992:               &addlog("Rule $label passed, setting label $xfinallabel");
  993:               return 1;
  994:            } else {
  995:               &addlog("Rule $label failed.");
  996:               my $hintlabel=$label;
  997:               $hintlabel=~s/^R//;
  998:               push(@Apache::functionplotresponse::failedrules,$hintlabel);
  999:               &addlog("Set hint condition $hintlabel");
 1000:               return 0; 
 1001:            }
 1002:         }
 1003:    }
 1004:    &addlog("Rule $label passed.");
 1005:    return 1;
 1006: }
 1007: 
 1008: sub start_functionplotruleset {
 1009:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1010:    if ($target eq 'edit') {
 1011:       return &Apache::edit::start_table($token).
 1012:         '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Rule Set').'</span></td>'
 1013:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
 1014:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'.
 1015:         &Apache::edit::insertlist($target,$token)
 1016:        .'</span></td>'
 1017:        ."<td>&nbsp;"
 1018:        .&Apache::edit::end_row()
 1019:        .&Apache::edit::start_spanning_row()
 1020:        ."\n";
 1021:    }
 1022: }
 1023: 
 1024: sub end_functionplotruleset {
 1025:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 1026:     my $id=$Apache::inputtags::response[-1];
 1027:     my $partid=$Apache::inputtags::part;
 1028:     my $internalid = $partid.'_'.$id;
 1029: 
 1030:     if ($target eq 'edit' ) {
 1031:         return &Apache::edit::end_table();
 1032:     }  elsif ($target eq 'grade'
 1033:          && &Apache::response::submitted()
 1034:          && $Apache::lonhomework::type ne 'exam') {
 1035: #
 1036: # Actually grade
 1037: #
 1038:         my $xmin=&Apache::lonxml::get_param('xmin',$parstack,$safeeval,-2);
 1039:         $xmin=(defined($xmin)?$xmin:-10);
 1040:         my $xmax=&Apache::lonxml::get_param('xmax',$parstack,$safeeval,-2);
 1041:         $xmax=(defined($xmax)?$xmax:10);
 1042:         my $ymin=&Apache::lonxml::get_param('ymin',$parstack,$safeeval,-2);
 1043:         $ymin=(defined($ymin)?$ymin:-10);
 1044:         my $ymax=&Apache::lonxml::get_param('ymax',$parstack,$safeeval,-2);
 1045:         $ymax=(defined($ymax)?$ymax:10);
 1046: 
 1047:         my $ad='';
 1048:         undef  %Apache::functionplotresponse::functionplotrulelabels;
 1049:         $Apache::functionplotresponse::ruleslog='';
 1050:         $Apache::functionplotresponse::functionplotrulelabels{'start'}=400;
 1051:         $Apache::functionplotresponse::functionplotrulelabels{'end'}=0;
 1052:         if (&populate_arrays($internalid,$xmin,$xmax) eq 'no_func') {
 1053:            $ad='NOT_FUNCTION';
 1054:         } else {
 1055:            &addlog("Start of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'start'},$xmin,$xmax)." (index ".
 1056:                                         $Apache::functionplotresponse::functionplotrulelabels{'start'}.")");
 1057:            &addlog("End of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'end'},$xmin,$xmax)." (index ".
 1058:                                         $Apache::functionplotresponse::functionplotrulelabels{'end'}.")");
 1059: 
 1060: # We have a function that we can actually grade, go through the spline rules.
 1061:            foreach my $rule (@Apache::functionplotresponse::functionplotrules) {
 1062:               unless (&functionplotrulecheck($rule,$xmin,$xmax,$ymin,$ymax)) {
 1063:                  $ad='INCORRECT';
 1064:                  last;
 1065:               }
 1066:            }
 1067: # If it's not wrong, it's correct 
 1068:            unless ($ad) { $ad='EXACT_ANS' };
 1069:         }
 1070:         &addlog("Set hint conditions: ".join(",",@Apache::functionplotresponse::failedrules));
 1071:         &addlog("Assigned award detail: $ad");
 1072: # Store for later to be assigned at end_functionplotresponse
 1073:         $Apache::functionplotresponse::awarddetail=$ad;
 1074:      }
 1075: }
 1076: 
 1077: 
 1078: sub end_functionplotresponse {
 1079:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1080:   &Apache::response::end_response;
 1081: 
 1082:   my $result;
 1083:   my $id=$Apache::inputtags::response[-1];
 1084:   my $partid=$Apache::inputtags::part;
 1085:   my $internalid = $partid.'_'.$id;
 1086: 
 1087:     if ($target eq 'edit') { $result=&Apache::edit::end_table(); }
 1088:     if ($target eq 'grade'
 1089:          && &Apache::response::submitted()
 1090:          && $Apache::lonhomework::type eq 'exam') {
 1091: 
 1092:         &Apache::response::scored_response($partid,$id);
 1093: 
 1094:     } elsif ($target eq 'grade'
 1095:          && &Apache::response::submitted()
 1096:          && $Apache::lonhomework::type ne 'exam') {
 1097:         my ($response,%coords)=&get_answer_from_form_fields($internalid);
 1098:         $Apache::lonhomework::results{"resource.$partid.$id.submission"}=$response;
 1099:         my %previous=&Apache::response::check_for_previous($response,$partid,$id);
 1100: #
 1101: # Assign grade
 1102: #
 1103:         my $ad=$Apache::functionplotresponse::awarddetail;
 1104: #
 1105: # Store grading info
 1106: #
 1107:         $Apache::lonhomework::results{"resource.$partid.$id.awarddetail"}=$ad;
 1108:         &Apache::response::handle_previous(\%previous,$ad);
 1109:    } elsif ($target eq 'web') {
 1110:         undef @Apache::functionplotresponse::failedrules;
 1111:    }
 1112:    return $result;
 1113: }
 1114: 
 1115: sub end_functionplotelements {
 1116:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 1117:   my $result='';
 1118:   my $id=$Apache::inputtags::response[-1];
 1119:   my $partid=$Apache::inputtags::part;
 1120:   my $internalid = $partid.'_'.$id;
 1121:   if ($target eq 'edit' ) {
 1122:      $result=&Apache::edit::end_table();
 1123:   } elsif ($target eq 'web') {
 1124: # Now is the time to render all of the stored splines
 1125:       my $xmin=&Apache::lonxml::get_param('xmin',$parstack,$safeeval,-2);
 1126:       $xmin=(defined($xmin)?$xmin:-10);
 1127:       my $xmax=&Apache::lonxml::get_param('xmax',$parstack,$safeeval,-2);
 1128:       $xmax=(defined($xmax)?$xmax:10);
 1129:       my $ymin=&Apache::lonxml::get_param('ymin',$parstack,$safeeval,-2);
 1130:       $ymin=(defined($ymin)?$ymin:-10);
 1131:       my $ymax=&Apache::lonxml::get_param('ymax',$parstack,$safeeval,-2);
 1132:       $ymax=(defined($ymax)?$ymax:10);
 1133:       if ($xmax<=$xmin) {
 1134:         $xmax=$xmin+20;
 1135:       }
 1136:       if ($ymax<=$ymin) {
 1137:          $ymax=$ymin+20;
 1138:       }
 1139:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
 1140:         $result.=&generate_spline($internalid,$label,$xmin,$xmax,$ymin,$ymax);
 1141:      }
 1142: # close the init script
 1143:      $result.=&end_init_script();
 1144: # register all splines in this response 
 1145:      $result.='<input type="hidden" name="HWVAL_AllSplines_'.$internalid.'" value="'.
 1146:                  join(',',keys(%Apache::functionplotresponse::splineorder)).'" />'."\n";
 1147:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
 1148:         $result.='<input type="hidden" name="HWVAL_SplineOrder_'.$internalid.'_'.$label.'" value="'.
 1149:                  $Apache::functionplotresponse::splineorder{$label}.'" />'."\n";
 1150:      }
 1151: # generate the input fields
 1152:      $result.=$Apache::functionplotresponse::inputfields;
 1153: # actually start the <applet>-tag
 1154:      $result.=&geogebra_startcode($internalid);
 1155: # load the spline bytecode
 1156:      $result.=&geogebra_spline_program();
 1157: # set default parameters
 1158:      $result.=&geogebra_default_parameters($internalid);
 1159: # close the <applet>-tag
 1160:      $result.=&geogebra_endcode();
 1161:   }
 1162:   return $result;
 1163: }
 1164: 
 1165: sub start_functionplotelements {
 1166:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1167:    my $result='';
 1168:    my $id=$Apache::inputtags::response[-1];
 1169:    my $partid=$Apache::inputtags::part;
 1170:    my $internalid = $partid.'_'.$id;
 1171: 
 1172:    if ($target eq 'edit') {
 1173:       return &Apache::edit::start_table($token).
 1174:         '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Elements').'</span></td>'
 1175:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
 1176:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'.
 1177:         &Apache::edit::insertlist($target,$token)
 1178:        .'</span></td>'
 1179:        ."<td>&nbsp;"
 1180:        .&Apache::edit::end_row()
 1181:        .&Apache::edit::start_spanning_row()
 1182:        ."\n";
 1183:    } elsif ($target eq 'web') {
 1184:       my $xmin=&Apache::lonxml::get_param('xmin',$parstack,$safeeval,-2);
 1185:       $xmin=(defined($xmin)?$xmin:-10);
 1186:       my $xmax=&Apache::lonxml::get_param('xmax',$parstack,$safeeval,-2);
 1187:       $xmax=(defined($xmax)?$xmax:10);
 1188:       my $ymin=&Apache::lonxml::get_param('ymin',$parstack,$safeeval,-2);
 1189:       $ymin=(defined($ymin)?$ymin:-10);
 1190:       my $ymax=&Apache::lonxml::get_param('ymax',$parstack,$safeeval,-2);
 1191:       $ymax=(defined($ymax)?$ymax:10);
 1192:       if ($xmax<=$xmin) {
 1193:         $xmax=$xmin+20;
 1194:       }
 1195:       if ($ymax<=$ymin) {
 1196:          $ymax=$ymin+20;
 1197:       }
 1198:       my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
 1199:       my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
 1200:       my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
 1201:       my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval,-2);
 1202:       my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval,-2);
 1203: 
 1204: 
 1205: # paste in the update routine to receive stuff back from the applet
 1206:      $result.=&update_script($internalid);
 1207: # start the initscript for this applet
 1208:      $result.=&start_init_script($internalid);
 1209: # put the axis commands inside
 1210:      $result.=&axes_script($internalid,$xmin,$xmax,$ymin,$ymax,$xaxisvisible,$yaxisvisible,$gridvisible);
 1211:      $result.=&axes_label($internalid,$xlabel,$ylabel);
 1212: # init script is left open
 1213:   }
 1214:   return $result;
 1215: }
 1216: 
 1217: 1;
 1218: 
 1219: __END__
 1220:  
 1221: =head1 NAME
 1222: 
 1223: Apache::functionplotresponse.pm;
 1224: 
 1225: =head1 SYNOPSIS
 1226: 
 1227: Handles tags associated with accepting function plots.
 1228: 
 1229: This is part of the LearningOnline Network with CAPA project
 1230: described at http://www.lon-capa.org.
 1231: 
 1232: =head1 HANDLER SUBROUTINE
 1233: 
 1234: start_functionplotresponse()
 1235: 
 1236: =head1 OTHER SUBROUTINES
 1237: 
 1238: =over
 1239: 
 1240: =item end_functionplotresponse()
 1241: 
 1242: =back
 1243: 
 1244: =cut

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