File:  [LON-CAPA] / loncom / homework / functionplotresponse.pm
Revision 1.63: download - view: text, annotated - select for diffs
Fri May 27 23:00:58 2011 UTC (12 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_10_0, HEAD
- Needs concatenator instead of ; (added in rev 1.47).

    1: # LearningOnline Network with CAPA
    2: # option list style responses
    3: #
    4: # $Id: functionplotresponse.pm,v 1.63 2011/05/27 23:00:58 raeburn 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="UEsDBBQACAAIAKNNfz4AAAAAAAAAAAAAAAASAAAAZ2VvZ2VicmFfbWFjcm8ueG1s7Vxtb+pGGv3c/grLH6pk21wSIITeDbcqfq3U217pVquVVrsrBxzCLtjIOAnTX78zYxtCxsDYi/EA50MyjjOM7XPs55iZ8zz3Py2mE+3Fj+bjMOjpNx+udc0PBuFwHIx6+nP8eNXVf/r07f3ID0f+Q+Rpj2E09eKe3mY9F/PxxyD8zZv685k38L8Onvyp92s48GI+2lMczz42Gq+vrx+yz38Io1FjNIo/LOZD+vnpJJj39HTjIx1u7UOvLd69eX190/j751+T4a/GwTz2goGva/S8pt4gCrXBdMhOoqd/nU3Ggd/UtTgMJzm7XH8yW+76x5ebH7Sv9OdLk7bNf+raeBAG9njis1OaP4WvvwR/0A/1vainx9Gzr2cH/CWYPcead93Tf9Y174Y2Hm2bPb1PmxZtPL2R9f39OV52fkl799PeL7wbPeicDj9goGnxOE6O7z3HT2HEtoZezPbQnv7En/pBrMVkRvfMwnEQ69rEe/An7Ew+ffvNPTtrLXz4jz+I03PO/v/oTeY+O9439/T/RjgJI40OT1kc8d8P/Lc3mT15dIuyy7tOPOJH2os3Yf9N99DhPodDf22vF4ynnHVtHvszNsANhXDm+0N6U+npCdPxZ3RAfmu9OZ1BGEbDubZIDquR9Ob6M7kdeRd+qV/Hf6YHbb3dG5PJ23O5b6Qo7cCrfwJ4NQ+IF73F/2/Amre3qkDWOcQtdhqQtfcN2WIW+XMmOBkO3sO/F1R3FrNk82JxqfW0i6b2F23xr4vWpXa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WHyLjkykoxPp2EQ6PpFOTKSLJtLFE+mSiXSLqX6eHJCpESFTQ0KmxoRMDQqZGhUyNSxkalzI1MCQqZGhUyNDJ5+VqZGhUyNDp0aGfiEysrR3O10BbNdZo8vSVYf9aJw5AW7YuPdNX6zTo8Zrpatv349uSxZ/49lf2bfAefbDF2dfodBWNj/jm7Q8P7pwwRv+BvchLxjeoXw3Cad6Wpb6sMZLqkrL73Jl9PkJ4pbe40vivapPtRXk7x0O3iFQjcwvSv3Ic71lALm8T7vS9OpcZX5SiZcPssEd+MZfYb/udNf62/FIeo427hD1C33bS21L/gU7iJ/NZdHIofGU7guFb4pu9eJy8dn0cj4YsWyzRtX21oA9qiq6tMBmVHVliQ0XX2UPF5u2Bre4NZ8HRhnbuda17cbwFp9//ZcYdGZntta3P9qPK3CX4oI5BpCnBhkCq38syb0I+k8st38AUEsHCA04kj02BQAA1BEAAFBLAQIUABQACAAIAKNNfz4bb+CNfwoAAFdEAQASAAAAAAAAAAAAAAAAAAAAAABnZW9nZWJyYV9tYWNyby54bWxQSwECFAAUAAgACACkTX8+RczeXRoAAAAYAAAAFgAAAAAAAAAAAAAAAAC/CgAAZ2VvZ2VicmFfamF2YXNjcmlwdC5qc1BLAQIUABQACAAIAKRNfz4NOJI9NgUAANQRAAAMAAAAAAAAAAAAAAAAAB0LAABnZW9nZWJyYS54bWxQSwUGAAAAAAMAAwC+AAAAjRAAAAAA"/>
   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_export.jar, geogebra_algos.jar, geogebra_javascript.jar, geogebra_properties.jar, jlatexmath.jar, jlm_cyrillic.jar, jlm_greek.jar" />
   78: 	<param name="cache_version" value="3.9.219.0, 3.9.219.0, 3.9.219.0, 3.9.219.0, 3.9.219.0, 3.9.219.0, 3.9.219.0, 3.9.219.0, 3.9.219.0, 3.9.219.0, 3.9.219.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()',200) }";
  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,$fixed)=@_;
  165:    my $mult=($fixed?'a*':'');
  166:    return (<<ENDSETVARIABLE);
  167: document.ggbApplet_$id.evalCommand("a=1");
  168: document.ggbApplet_$id.evalCommand("$variable=$mult($x,$y)");
  169: document.ggbApplet_$id.setLabelVisible("$variable",false);
  170: ENDSETVARIABLE
  171: }
  172: 
  173: #
  174: # Set a slope coordinate variable
  175: #
  176: sub set_slope_coordinate {
  177:    my ($id,$variable,$xrel,$yrel,$xmin,$xmax,$ymin,$ymax,$pointname,$fixed)=@_;
  178:    my $xvariable=$variable.'x';
  179:    my $yvariable=$variable.'y';
  180:    my $domain=$xmax-$xmin;
  181:    my $range=$ymax-$ymin;
  182:    my $xinterval=$domain/100.;
  183:    my $yinterval=$range/200.;
  184:    my $mult=($fixed?'a*':'');
  185:    return (<<ENDSETSVARIABLE);
  186: document.ggbApplet_$id.evalCommand("a=1");
  187: document.ggbApplet_$id.evalCommand("$xvariable=Slider[$xinterval,$domain,$xinterval]");
  188: document.ggbApplet_$id.setVisible("$xvariable", false);
  189: document.ggbApplet_$id.evalCommand("$xvariable=$xrel");
  190: document.ggbApplet_$id.evalCommand("$yvariable=Slider[-$range,$range,$yinterval]");
  191: document.ggbApplet_$id.setVisible("$yvariable", false);
  192: document.ggbApplet_$id.evalCommand("$yvariable=$yrel");
  193: document.ggbApplet_$id.evalCommand("$variable=$mult($xvariable+x($pointname),$yvariable+y($pointname))");
  194: document.ggbApplet_$id.setLabelVisible("$variable", false);
  195: ENDSETSVARIABLE
  196: }
  197: 
  198: #
  199: # Input field name for a coordinate variable
  200: #
  201: 
  202: sub field_name {
  203:     my ($id,$variable,$name)=@_;
  204:     return "HWVAL_$id\_$variable\_$name";
  205: }
  206: 
  207: #
  208: # Generate an input field for a coordinate variable
  209: #
  210: 
  211: sub generate_input_field {
  212:     my ($id,$variable,$x,$y)=@_;
  213:     $Apache::functionplotresponse::inputfields.=
  214:        "<input type='hidden' name='".&field_name($id,$variable,'x')."' value='$x' />\n".
  215:        "<input type='hidden' name='".&field_name($id,$variable,'y')."' value='$y' />\n";
  216: }
  217: 
  218: #
  219: # Initialize a new point coordinate variable at set a listener on it
  220: #
  221: sub new_point_coordinate {
  222:     my ($id,$variable,$x,$y,$fixed)=@_;
  223:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'x')})) {
  224:        $x=$Apache::functionplotresponse::previous{&field_name($id,$variable,'x')};
  225:     }
  226:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'y')})) {
  227:        $y=$Apache::functionplotresponse::previous{&field_name($id,$variable,'y')};
  228:     }
  229:     &generate_input_field($id,$variable,$x,$y);
  230:     return &set_point_coordinate($id,$variable,$x,$y,$fixed).&update_register($id,$variable);
  231: }
  232: 
  233: #
  234: # Initialize a new slope coordinate variable at set a listener on it
  235: #
  236: sub new_slope_coordinate {
  237:     my ($id,$variable,$x,$y,$pointname,$xp,$yp,$xmin,$xmax,$ymin,$ymax,$fixed)=@_;
  238: #
  239: # $variable: name of the slope point
  240: # $x, $y: coordinates of the slope point
  241: # $pointname: name of the associated point point
  242: # $xp $yp: coordinates of the point point
  243: #
  244:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'x')})) {
  245:        $x=$Apache::functionplotresponse::previous{&field_name($id,$variable,'x')};
  246:     }
  247:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'y')})) {
  248:        $y=$Apache::functionplotresponse::previous{&field_name($id,$variable,'y')};
  249:     }
  250:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$pointname,'x')})) {
  251:        $xp=$Apache::functionplotresponse::previous{&field_name($id,$pointname,'x')};
  252:     }
  253:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$pointname,'y')})) {
  254:        $yp=$Apache::functionplotresponse::previous{&field_name($id,$pointname,'y')};
  255:     }
  256: 
  257:     &generate_input_field($id,$variable,$x,$y);
  258:     my $xrel=$x-$xp;
  259:     my $yrel=$y-$yp;
  260:     return &set_slope_coordinate($id,$variable,$xrel,$yrel,$xmin,$xmax,$ymin,$ymax,$pointname,$fixed).&update_register($id,$variable);
  261: }
  262: 
  263: #
  264: # This registers the init-function call for ggbOnInit, which LON-CAPA will place at </problem>
  265: # It then starts the right headers
  266: #
  267: sub start_init_script {
  268:     my ($id)=@_;
  269: # Add id to the list of ggbInit_$id functions that need to be called
  270:     push(@Apache::functionplotresponse::callscripts,$id);
  271: # ... and open this function
  272:     return (<<ENDSTARTINIT);
  273: <script type="text/javascript">
  274: // <![CDATA[
  275: // variable that will eventually be passed back to the server
  276: var coordinateMap_$id = [];
  277: // flag for not loaded yet
  278: var loaded_$id=false;
  279: // Init-function for applet
  280: function ggbInit_$id() {
  281: ENDSTARTINIT
  282: }
  283: 
  284: #
  285: # This sets the axes inside ggbInit_$id
  286: #
  287: 
  288: sub axes_script {
  289:     my ($id,$xmin,$xmax,$ymin,$ymax,$xvisible,$yvisible,$gvisible)=@_;
  290:     return (<<ENDAXESSCRIPT);
  291:             // changes (xmin, xmax, ymin, ymax)
  292:             document.ggbApplet_$id.setCoordSystem($xmin,$xmax,$ymin,$ymax);
  293: 
  294:             // makes the (x,y) axis (in)visible
  295:             document.ggbApplet_$id.setAxesVisible($xvisible,$yvisible);
  296:             // makes the grid (in)visible
  297:             document.ggbApplet_$id.setGridVisible($gvisible);
  298: ENDAXESSCRIPT
  299: }
  300: 
  301: sub axes_label {
  302:     my ($id,$xmin,$xmax,$ymin,$ymax,$xlabel,$ylabel)=@_;
  303:     unless ($xlabel || $ylabel) { return ''; }
  304:     my $return='document.ggbApplet_'.$id.'.evalCommand("topRight=Corner[3]");';
  305:     if ($xlabel) {
  306:       if (($ymin<0) && ($ymax>0)) {
  307:        $return.=(<<ENDXAXISLABELSCRIPT);
  308: document.ggbApplet_$id.evalCommand("Xlabel=(x(topRight)-AxisStepX[],AxisStepY[]/6)");
  309: document.ggbApplet_$id.setVisible("Xlabel",false);
  310: document.ggbApplet_$id.evalCommand("Text[\\"$xlabel\\", Xlabel]");
  311: ENDXAXISLABELSCRIPT
  312:       } else {
  313:        $return.=(<<ENDXOFFAXISLABEL);
  314: document.ggbApplet_$id.evalCommand("LowerRight=Corner[2]");
  315: document.ggbApplet_$id.evalCommand("Text[\\"$xlabel\\", (x(LowerRight) - AxisStepX[], y(LowerRight) + AxisStepY[] / 2)]");
  316: ENDXOFFAXISLABEL
  317:       }
  318:     }
  319:     if ($ylabel) {
  320:       if (($xmin<0) && ($xmax>0)) {
  321:        $return.=(<<ENDYAXISLABELSCRIPT);
  322: document.ggbApplet_$id.evalCommand("Ylabel=(AxisStepX[]/6,y(topRight)-AxisStepY[]/3)");
  323: document.ggbApplet_$id.setVisible("Ylabel",false);
  324: document.ggbApplet_$id.evalCommand("Text[\\"$ylabel\\", Ylabel]");
  325: ENDYAXISLABELSCRIPT
  326:       } else {
  327:        $return.=(<<ENDYOFFAXISLABEL);
  328: document.ggbApplet_$id.evalCommand("UpperLeft=Corner[4]");
  329: document.ggbApplet_$id.evalCommand("Text[\\"$ylabel\\", (x(UpperLeft) + AxisStepX[] / 5, y(UpperLeft) - AxisStepY[] / 1.8)]");
  330: ENDYOFFAXISLABEL
  331:       }
  332:     }
  333:     return $return;
  334: }
  335: 
  336: #
  337: # Subroutine to produce background and answer plots
  338: #
  339: 
  340: sub plot_script {
  341:    my ($id,$function,$fixed,$label,$color,$xmin,$xmax,$thickness)=@_;
  342:    $label=~s/\W//g;
  343:    if (($label) && ($label!~/^[A-Za-z]/)) {
  344:       $label='C'.$label;
  345:    }
  346:    my $visible=0;
  347:    if ($label) {
  348:       $visible="1";
  349:    } else {
  350:       $Apache::functionplotresponse::counter++;
  351:       $label='C'.$Apache::functionplotresponse::counter;
  352:    }
  353:    my $rc=0;
  354:    my $gc=0;
  355:    my $bc=0;
  356:    if ($color) {
  357:       my ($rh,$gh,$bh)=($color=~/(..)(..)(..)/);
  358:       $rc=hex($rh);
  359:       $gc=hex($gh);
  360:       $bc=hex($bh);
  361:    }
  362:    if ($fixed) {
  363:       return "document.ggbApplet_$id.evalCommand('$label=Function[$function,$xmin,$xmax]');\n".
  364:              ($visible?'':"document.ggbApplet_$id.setLabelVisible('$label', false);\n").
  365:              ($color?"document.ggbApplet_$id.setColor('$label',$rc,$gc,$bc);\n":'').
  366:              ($thickness?"document.ggbApplet_$id.setLineThickness('$label',$thickness);\n":'');
  367:    } else {
  368:        return "document.ggbApplet_$id.evalCommand('y=$function');\n";
  369:    }
  370: }
  371: 
  372: #
  373: # Answer spline display
  374: # 
  375: # points: x,y,slope_x,slope_y
  376: 
  377: sub answer_spline_script {
  378:    my ($id,@points)=@_;
  379:    my $order=int(($#points+1)/4);
  380:    if ($order<2) { $order=2; }
  381:    if ($order>8) { $order=8; }
  382:    $Apache::functionplotresponse::counter++;
  383:    my $label='CSpline'.$Apache::functionplotresponse::counter;
  384:    my $output='document.ggbApplet_'.$id.'.evalCommand("'.$label.'=Spline'.$order.'[';
  385:    for (my $i=0;$i<=$#points;$i+=4) {
  386:       $output.="($points[$i],$points[$i+1]),($points[$i+2],$points[$i+3]),";
  387:    }
  388:    $output=~s/\,$//;
  389:    $output.=']");'."\n";
  390:    for (my $i=2; $i<2*$order; $i+=2) {
  391:        $output.='document.ggbApplet_'.$id.'.setColor("'.$label.'_'.($i>=10?'{':'').$i.($i>=10?'}':'').'",0,170,0);'."\n";
  392:    }
  393:    for (my $i=1; $i<2*$order; $i+=2) {
  394:        $output.='document.ggbApplet_'.$id.'.setVisible("'.$label.'_'.($i>=10?'{':'').$i.($i>=10?'}':'').'",false);'."\n";
  395:    }
  396: 
  397:    return $output;
  398: }
  399: 
  400: #
  401: # Subroutine that generates code for spline $label based on stored information
  402: #
  403: 
  404: sub generate_spline {
  405:    my ($id,$label,$xmin,$xmax,$ymin,$ymax,$fixed)=@_;
  406:    my $result='';
  407:    my $order=$Apache::functionplotresponse::splineorder{$label};
  408:    my $x=$Apache::functionplotresponse::splineinitx{$label};
  409:    my $y=$Apache::functionplotresponse::splineinity{$label};
  410:    my $sx=$Apache::functionplotresponse::splinescalex{$label};
  411:    my $sy=$Apache::functionplotresponse::splinescaley{$label};
  412:    my @coords=();
  413:    foreach my $i (1..$order) {
  414:        $result.=&new_point_coordinate($id,$label.'P'.$i,$x,$y,$fixed);
  415:        my $xp=$x;
  416:        $x+=$sx/(2.*($order-1));
  417:        push(@coords,$label.'P'.$i);
  418:        $result.=&new_slope_coordinate($id,$label.'S'.$i,$x,$y+$sy,$label.'P'.$i,$xp,$y,$xmin,$xmax,$ymin,$ymax,$fixed);
  419:        $x+=$sx/(2.*($order-1));
  420:        push(@coords,$label.'S'.$i);
  421:    }
  422:    $result.='document.ggbApplet_'.$id.'.evalCommand("Spline'.$order.'['.join(',',@coords).']");'."\n";
  423:    return $result;
  424: }
  425: #
  426: # <backgroundplot function="..." fixed="yes/no" />
  427: #
  428: sub start_backgroundplot {
  429:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  430:    my $result='';
  431:    my $internalid = $Apache::inputtags::part.'_'.$Apache::inputtags::response[-1];
  432:    my $function=&Apache::lonxml::get_param('function',$parstack,$safeeval);
  433:    my $xinitial=&Apache::lonxml::get_param('xinitial',$parstack,$safeeval);
  434:    my $xfinal=&Apache::lonxml::get_param('xfinal',$parstack,$safeeval);
  435:    my $label=&Apache::lonxml::get_param('label',$parstack,$safeeval);
  436:    my $color=&Apache::lonxml::get_param('color',$parstack,$safeeval);
  437:    $color=~s/[^a-fA-F0-9]//gs;
  438:    unless (length($color)==6) { $color=''; }
  439:    my $fixed=(&Apache::lonxml::get_param('fixed',$parstack,$safeeval)=~/on|true|yes|1/i?1:0);
  440:  
  441:    unless ($function) { $function="0"; }
  442:    if ($target eq 'web') {
  443:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-3);
  444:       unless (defined($xinitial)) { $xinitial=$xmin; }
  445:       unless (defined($xfinal)) { $xfinal=$xmax; }
  446:       $result.=&plot_script($internalid,$function,$fixed,$label,$color,$xinitial,$xfinal);
  447:    } elsif ($target eq 'edit') {
  448:         $result=&Apache::edit::tag_start($target,$token,'Background Function Plot').
  449:              &Apache::edit::text_arg('Function:','function',
  450:                                      $token,'16').
  451:              &Apache::edit::text_arg('Initial x-value (optional):','xinitial',
  452:                                      $token,'8').
  453:              &Apache::edit::text_arg('Final x-value (optional):','xfinal',
  454:                                      $token,'8').
  455:              &Apache::edit::text_arg('Label on Plot:','label',
  456:                                      $token,'8').
  457:              &Apache::edit::text_arg('Color (hex code):','color',
  458:                                      $token,'8').
  459:              &Apache::edit::select_arg('Fixed location:','fixed',
  460:                                   ['yes','no'],$token).
  461:              &Apache::edit::end_row();
  462:   } elsif ($target eq 'modified') {
  463:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  464:                                                  $safeeval,'function','label','xinitial','xfinal','color','fixed');
  465:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
  466:   }
  467:   return $result;
  468: }
  469: 
  470: sub end_backgroundplot {
  471:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  472:    my $result='';
  473:    if ($target eq 'edit') {
  474:        $result=&Apache::edit::end_table();
  475:    }
  476:    return $result;
  477: }
  478: 
  479: #
  480: # <functionplotrule ... />
  481: #
  482: sub start_functionplotrule {
  483:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  484:    my $result='';
  485:    my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
  486:    $Apache::functionplotresponse::counter++;
  487:    if ($label=~/\W/) {
  488:       &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
  489:    }
  490:    $label=~s/\W//gs;
  491:    unless ($label) {
  492:       $label='R'.$Apache::functionplotresponse::counter;
  493:    } else {
  494:       $label='R'.$label;
  495:    }
  496:    if ($Apache::functionplotresponse::splineorder{$label}) {
  497:        &Apache::lonxml::error(&mt('Rule indices must be unique.'));
  498:    }
  499: 
  500: 
  501:    if ($target eq 'grade') {
  502: # Simply remember - in order - for later
  503:       my $beginninglabel=&Apache::lonxml::get_param('xinitiallabel',$parstack,$safeeval);
  504:       my $endinglabel=&Apache::lonxml::get_param('xfinallabel',$parstack,$safeeval);
  505:       if (($beginninglabel=~/\W/) || ($endinglabel=~/W/)) {
  506:           &Apache::lonxml::warning(&mt('Rule labels must be alphanumeric.'));
  507:       }
  508:       $beginninglabel=~s/\W//gs;
  509:       $endinglabel=~s/\W//gs;
  510:       my $relationship=&Apache::lonxml::get_param('relationship',$parstack,$safeeval);
  511:       $relationship=~s/\W//gs;
  512:       $relationship=lc($relationship);
  513:       unless ($relationship=~/^(eq|ge|gt|le|lt|ne)$/) {
  514:           &Apache::lonxml::warning(&mt('Rule relationship not defined.'));
  515:           $relationship='eq';
  516:       }
  517:       my $derivative=&Apache::lonxml::get_param('derivativeorder',$parstack,$safeeval);
  518:       unless (($derivative==-1) || ($derivative==0) || ($derivative==1) || ($derivative==2)) {
  519:          &Apache::lonxml::warning(&mt('Rule derivative not defined.'));
  520:          $derivative=0;
  521:       }
  522:       push(@Apache::functionplotresponse::functionplotrules,join(':',(
  523:            $label,
  524:            $derivative,
  525:            &Apache::lonxml::get_param('xinitial',$parstack,$safeeval),
  526:            $beginninglabel,
  527:            &Apache::lonxml::get_param('xfinal',$parstack,$safeeval),
  528:            $endinglabel,
  529:            &Apache::lonxml::get_param('minimumlength',$parstack,$safeeval),
  530:            &Apache::lonxml::get_param('maximumlength',$parstack,$safeeval),
  531:            $relationship,
  532:            &Apache::lonxml::get_param('value',$parstack,$safeeval),
  533:            &Apache::lonxml::get_param('percenterror',$parstack,$safeeval)
  534:           )));
  535:    } elsif ($target eq 'edit') {
  536:         $result=&Apache::edit::tag_start($target,$token,'Function Plot Evaluation Rule').
  537:              &Apache::edit::text_arg('Index/Name:','index',
  538:                                      $token,'10').'&nbsp;'.
  539:              &Apache::edit::select_arg(&mt('Function:'),'derivativeorder',
  540:                                   [['0','Function itself'],
  541:                                    ['1','First derivative'],
  542:                                    ['2','Second derivative'],
  543:                                    ['-1','Integral']],$token).'<br />'.
  544:              &Apache::edit::text_arg('Initial x-value:','xinitial',
  545:                                       $token,'8').
  546:              &Apache::edit::select_or_text_arg('Initial x-value label:','xinitiallabel',
  547:                                                [['start','Start of Plot'],
  548:                                                 ['end','End of Plot']],$token,'8').'<br />'.
  549: 
  550:              &Apache::edit::text_arg('Final x-value (optional):','xfinal',
  551:                                       $token,'8').
  552:              &Apache::edit::select_or_text_arg('Final x-value label (optional):','xfinallabel',
  553:                                                [['end','End of Plot']],$token,'8').'<br />'.
  554:              &Apache::edit::text_arg('Minimum length for range (optional):','minimumlength',
  555:                                      $token,'8').
  556:              &Apache::edit::text_arg('Maximum length for range (optional):','maximumlength',
  557:                                      $token,'8').'<br />'.
  558:              &Apache::edit::select_or_text_arg(&mt('Relationship:'),'relationship',
  559:                                   [['eq','equal'],
  560:                                    ['ne','not equal'],
  561:                                    ['ge','greater than or equal'],
  562:                                    ['gt','greater than'],
  563:                                    ['lt','less than'],
  564:                                    ['le','less than or equal']],$token).
  565:              $result.= &Apache::edit::select_or_text_arg('Value:','value',
  566:                                                [['undef','not defined']],$token,'8').
  567:              &Apache::edit::text_arg('Percent error:','percenterror',
  568:                                      $token,'8').
  569:              &Apache::edit::end_row();
  570:   } elsif ($target eq 'modified') {
  571:     if (($env{'form.'.&Apache::edit::html_element_name('xinitial')} ne '') && ($env{'form.'.&Apache::edit::html_element_name('xinitiallabel')} eq 'start')) {
  572:        $env{'form.'.&Apache::edit::html_element_name('xinitiallabel')}='';
  573:     }
  574:     if (($env{'form.'.&Apache::edit::html_element_name('xfinal')} ne '') && ($env{'form.'.&Apache::edit::html_element_name('xfinallabel')} eq 'end')) {
  575:        $env{'form.'.&Apache::edit::html_element_name('xfinallabel')}='';
  576:     }
  577:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  578:                                                  $safeeval,'index','derivativeorder',
  579:                                                            'xinitial','xinitiallabel','xfinal','xfinallabel',
  580:                                                            'minimumlength','maximumlength',
  581:                                                            'relationship','value','percenterror');
  582:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
  583:    }
  584:    return $result;
  585: }
  586: 
  587: sub end_functionplotrule {
  588:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  589:    my $result='';
  590:    if ($target eq 'edit') {
  591:        $result=&Apache::edit::end_table();
  592:    }
  593:    return $result;
  594: }
  595: 
  596: 
  597: #
  598: # <spline index="..." order="1,2,3,4" initx="..." inity="..." scalex="..." scaley="..." />
  599: #
  600: # Unfortunately, GeoGebra seems to want all splines after everything else, so we need to store them
  601: #
  602: sub start_spline {
  603:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  604:    my $result='';
  605:    if ($target eq 'web') {
  606:       my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
  607:       $Apache::functionplotresponse::counter++;
  608:       if ($label=~/\W/) {
  609:          &Apache::lonxml::warning(&mt('Spline indices should only contain alphanumeric characters.'));
  610:       }
  611:       $label=~s/\W//gs;
  612:       unless ($label) { 
  613:          $label='S'.$Apache::functionplotresponse::counter; 
  614:       } else {
  615:          $label='S'.$label;
  616:       }
  617:       if ($Apache::functionplotresponse::splineorder{$label}) {
  618:          &Apache::lonxml::error(&mt('Spline indices must be unique.'));
  619:       }
  620: 
  621:       my $order=&Apache::lonxml::get_param('order',$parstack,$safeeval);
  622:       if ($order<2) { $order=2; }
  623:       if ($order>8) { $order=8; }
  624:       $Apache::functionplotresponse::splineorder{$label}=$order;
  625: 
  626:       my $x=&Apache::lonxml::get_param('initx',$parstack,$safeeval);
  627:       unless ($x) { $x=0; }
  628:       $Apache::functionplotresponse::splineinitx{$label}=$x;
  629: 
  630:       my $y=&Apache::lonxml::get_param('inity',$parstack,$safeeval);
  631:       unless ($y) { $y=0; }
  632:       $Apache::functionplotresponse::splineinity{$label}=$y;
  633: 
  634:       my $sx=&Apache::lonxml::get_param('scalex',$parstack,$safeeval);
  635:       unless ($sx) { $sx=$order; }
  636:       $Apache::functionplotresponse::splinescalex{$label}=$sx;
  637: 
  638:       my $sy=&Apache::lonxml::get_param('scaley',$parstack,$safeeval);
  639:       unless ($sy) { $sy=2; }
  640:       $Apache::functionplotresponse::splinescaley{$label}=$sy;
  641:    } elsif ($target eq 'edit') {
  642:         $result=&Apache::edit::tag_start($target,$token,'Spline').
  643:              &Apache::edit::text_arg('Index:','index',
  644:                                      $token,'4').'&nbsp;'.
  645:              &Apache::edit::select_arg('Order:','order',
  646:                                   ['2','3','4','5','6','7','8'],$token).'&nbsp;'.
  647:              &Apache::edit::text_arg('Initial x-value:','initx',
  648:                                      $token,'4').'&nbsp;'.
  649:              &Apache::edit::text_arg('Initial y-value:','inity',
  650:                                      $token,'4').'&nbsp;'.
  651:              &Apache::edit::text_arg('Scale x:','scalex',
  652:                                      $token,'4').'&nbsp;'.
  653:              &Apache::edit::text_arg('Scale y:','scaley',
  654:                                      $token,'4').
  655:              &Apache::edit::end_row();
  656:   } elsif ($target eq 'modified') {
  657:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  658:                                                  $safeeval,'index','order','initx','inity',
  659:                                                            'scalex','scaley');
  660:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
  661:   }
  662:   return $result;
  663: }
  664: 
  665: sub end_spline {
  666:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  667:    my $result='';
  668:    if ($target eq 'edit') {
  669:        $result=&Apache::edit::end_table();
  670:    }
  671:    return $result;
  672: }
  673:  
  674: sub end_init_script {
  675:     return (<<ENDENDINIT);
  676: }
  677: // ]]>
  678: </script>
  679: ENDENDINIT
  680: }
  681: 
  682: #
  683: # Storing and restoring spline coordinates from part answers
  684: #
  685: sub decode_previous_answer {
  686:    my ($answer)=@_;
  687:    foreach my $coordinate (split(/\,/,$answer)) {
  688:       my ($key,$value)=split(/\=/,$coordinate);
  689:       $Apache::functionplotresponse::previous{$key}=$value;
  690:    }
  691: }
  692: 
  693: sub get_answer_from_form_fields {
  694:    my ($id)=@_;
  695:    my $answer='';
  696:    my %coords=();
  697:    foreach my $field (keys(%env)) {
  698:       if ($field=~/^form\.HWVAL\_$id/) {
  699:          $field=~/^form\.(.*)$/;
  700:          $coords{$1}=$env{$field};
  701:       }
  702:    }
  703:    $answer=join(',',map { $_.'='.$coords{$_} } (sort(keys(%coords))));
  704:    return ($answer,%coords);
  705: }
  706: 
  707: #
  708: # The following functions calculate the cubic-hermite splines server-side
  709: #
  710: 
  711: sub cubic_hermite {
  712:    my ($t,$p1,$s1,$p2,$s2)=@_;
  713:    return (2.*$t*$t*$t-3.*$t*$t+1.)*$p1 + 3.*($t*$t*$t-2.*$t*$t+$t)*($s1-$p1)+
  714:           (-2.*$t*$t*$t+3.*$t*$t)  *$p2 + 3.*($t*$t*$t-$t*$t)      *($s2-$p2);
  715: }
  716: 
  717: #
  718: # d/dt(...)
  719: # 
  720: 
  721: sub ddt_cubic_hermite {
  722:    my ($t,$p1,$s1,$p2,$s2)=@_;
  723:    return (6.*$t*$t-6.*$t) *$p1 + 3.*(3.*$t*$t-4.*$t+1.)*($s1-$p1)+
  724:           (-6.*$t*$t+6.*$t)*$p2 + 3.*(3.*$t*$t-2.*$t)   *($s2-$p2);
  725: }
  726: 
  727: #
  728: # d^2/dt^2(...)
  729: #
  730: 
  731: sub d2dt2_cubic_hermite {
  732:    my ($t,$p1,$s1,$p2,$s2)=@_;
  733:    return (12.*$t-6.) *$p1 + 3.*(6.*$t-4.)*($s1-$p1)+
  734:           (-12.*$t+6.)*$p2 + 3.*(6.*$t-2.)*($s2-$p2);
  735: }
  736: 
  737: #
  738: # Array index calculation
  739: #
  740: sub array_index {
  741:    my ($xmin,$xmax,$x)=@_;
  742:    if ($x ne '') {
  743:       return int(($x-$xmin)/($xmax-$xmin)*400.+0.5);
  744:    } else {
  745:       return undef;
  746:    }
  747: }
  748: 
  749: #
  750: # Populate the arrays
  751: #
  752: 
  753: sub populate_arrays {
  754:     my ($id,$xmin,$xmax)=@_;
  755:     for (my $i=0; $i<=400; $i++) {
  756:        $Apache::functionplotresponse::actualxval[$i]=undef;
  757:        $Apache::functionplotresponse::func[$i]=undef;
  758:        $Apache::functionplotresponse::dfuncdx[$i]=undef;
  759:        $Apache::functionplotresponse::d2funcd2x[$i]=undef;
  760:     }
  761:     unless ($xmax>$xmin) { return 'no_func'; }
  762: # Run over all splines in response
  763:     foreach my $label (split(/\,/,$env{"form.HWVAL_AllSplines_$id"})) {
  764:         my $xiold=-1;
  765: # Run over all points in spline
  766:         for (my $i=1; $i<$env{"form.HWVAL_SplineOrder_".$id."_".$label}; $i++) {
  767:             my $ni=$i+1;
  768:             my @xparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_x'},
  769:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_x'},
  770:                         $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_x'},
  771:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_x'});
  772:             my @yparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_y'},
  773:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_y'},
  774:                         $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_y'},
  775:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_y'});
  776: # Run in small steps over spline parameter
  777:             for (my $t=0; $t<=1; $t+=0.0001) {
  778:                 my $xreal=&cubic_hermite($t,@xparms);
  779:                 my $xi=&array_index($xmin,$xmax,$xreal);
  780:                 if ($xi<$xiold) { return 'no_func'; }
  781:                 if (($xi>$xiold) && ($xi>=0) && ($xi<=400)) {
  782:                    if (defined($Apache::functionplotresponse::func[$xi])) { return 'no_func'; }
  783:                    $xiold=$xi;
  784:                    $Apache::functionplotresponse::actualxval[$xi]=$xreal;
  785: # Function value
  786:                    my $funcval=&cubic_hermite($t,@yparms);
  787:                    $Apache::functionplotresponse::func[$xi]=$funcval;
  788:                    if (defined($funcval)) {
  789:                       if ($xi<$Apache::functionplotresponse::functionplotrulelabels{'start'}) {
  790:                          $Apache::functionplotresponse::functionplotrulelabels{'start'}=$xi;
  791:                       }
  792:                       if ($xi>$Apache::functionplotresponse::functionplotrulelabels{'end'}) {
  793:                          $Apache::functionplotresponse::functionplotrulelabels{'end'}=$xi;
  794:                       }
  795:                    }
  796: # Chain rule
  797: # dy/dx=dy/dt/(dx/dt)
  798:                    my $dxdt=&ddt_cubic_hermite($t,@xparms);
  799:                    if ($dxdt) {
  800:                       $Apache::functionplotresponse::dfuncdx[$xi]=&ddt_cubic_hermite($t,@yparms)/$dxdt;
  801: # Second derivative
  802:                       $Apache::functionplotresponse::d2funcdx2[$xi]=
  803:                          ($dxdt*&d2dt2_cubic_hermite($t,@yparms)-&ddt_cubic_hermite($t,@yparms)*&d2dt2_cubic_hermite($t,@xparms))/
  804:                          ($dxdt*$dxdt*$dxdt);
  805:                    }
  806:                 }
  807:             }
  808:         }
  809:     }
  810: }
  811: 
  812: #
  813: # Implementation of <functionplotresponse>
  814: #
  815: 
  816: sub start_functionplotresponse {
  817:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  818:   my $result='';
  819: # To remember the splines - somehow, they need to come last
  820:   undef %Apache::functionplotresponse::splineorder;
  821:   undef %Apache::functionplotresponse::splineinitx;
  822:   undef %Apache::functionplotresponse::splineinity;
  823:   undef %Apache::functionplotresponse::splinescalex;
  824:   undef %Apache::functionplotresponse::splinescaley;
  825: # Remember input fields, etc
  826:   undef %Apache::functionplotresponse::previous;
  827:   $Apache::functionplotresponse::inputfields='';
  828:   $Apache::functionplotresponse::counter=0;
  829: # Remember rules
  830:   undef @Apache::functionplotresponse::functionplotrules;
  831: # Remember failed rules
  832:   if ($target eq 'grade') {
  833:      undef @Apache::functionplotresponse::failedrules;
  834:   }
  835: # Delete previous awards
  836:   undef $Apache::functionplotresponse::awarddetail;
  837: # Part and ID
  838:   my $partid=$Apache::inputtags::part;
  839:   my $id=&Apache::response::start_response($parstack,$safeeval);
  840: # Internal ID to mark the applet and its coordinates
  841:   my $internalid = $partid.'_'.$id;
  842: # Previous answer
  843:   &decode_previous_answer($Apache::lonhomework::history{"resource.$partid.$id.submission"});
  844: 
  845: # Parameters of <functionplotresponse>
  846:   my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval);
  847:   my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
  848:   my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
  849:   my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
  850:   my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval);
  851:   my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval);
  852:   if ($target eq 'edit') {
  853:     $result.=&Apache::edit::start_table($token)
  854:        .'<tr><td><span class="LC_nobreak">'.&mt('Function Plot Question').'</span></td>'
  855:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
  856:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'
  857:        .&Apache::edit::insertlist($target,$token).'&nbsp;&nbsp;&nbsp;'
  858:        .&Apache::loncommon::help_open_topic('Function_Plot_Response_Question','Function Plot Responses')
  859:        .'</span></td>'
  860:        ."<td>&nbsp;"
  861:        .&Apache::edit::end_row()
  862:        .&Apache::edit::start_spanning_row()
  863:        ."\n";
  864:     $result.=&Apache::edit::text_arg('Label x-axis:','xlabel',
  865:                                      $token,'6').'&nbsp;'.
  866:              &Apache::edit::text_arg('Minimum x-value:','xmin',
  867:                                      $token,'4').'&nbsp;'.
  868:              &Apache::edit::text_arg('Maximum x-value:','xmax',
  869:                                      $token,'4').'&nbsp;'.
  870:              &Apache::edit::select_arg('x-axis visible:','xaxisvisible',
  871:                                   ['yes','no'],$token).'<br />'.
  872:              &Apache::edit::text_arg('Label y-axis:','ylabel',
  873:                                      $token,'6').'&nbsp;'.
  874:              &Apache::edit::text_arg('Minimum y-value:','ymin',
  875:                                      $token,'4').'&nbsp;'.
  876:              &Apache::edit::text_arg('Maximum y-value:','ymax',
  877:                                      $token,'4').'&nbsp;'.
  878:              &Apache::edit::select_arg('y-axis visible:','yaxisvisible',
  879:                                   ['yes','no'],$token).'<br />'.
  880:              &Apache::edit::select_arg('Grid visible:','gridvisible',
  881:                                   ['yes','no'],$token).'<br />'.
  882:              &Apache::edit::text_arg('Background plot(s) for answer (function(x):xmin:xmax,function(x):xmin:xmax,x1:y1:sx1:sy1:x2:y2:sx2:sy2,...):',
  883:                                          'answerdisplay',$token,'50').
  884:              &Apache::edit::end_row().&Apache::edit::start_spanning_row();
  885:   } elsif ($target eq 'modified') {
  886:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  887:                                                  $safeeval,'xlabel','xmin','xmax','ylabel','ymin','ymax',
  888:                                                            'xaxisvisible','yaxisvisible','gridvisible','answerdisplay');
  889:     if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
  890: 
  891:   } elsif ($target eq 'meta') {
  892:        $result=&Apache::response::meta_package_write('functionplotresponse');
  893:   } elsif (($target eq 'answer') &&
  894:             ($env{'form.answer_output_mode'} ne 'tex') &&
  895:             ($Apache::lonhomework::viewgrades == 'F')) {
  896:       my (undef,undef,$udom,$uname)=&Apache::lonnet::whichuser();
  897:       my $windowopen=&Apache::lonhtmlcommon::javascript_docopen();
  898:       my $start_page = &Apache::loncommon::start_page('Rules Log', undef,
  899:                                                {'only_body' => 1,
  900:                                                 'bgcolor'   => '#FFFFFF',
  901:                                                 'js_ready'  => 1,});
  902:       my $end_page = &Apache::loncommon::end_page({'js_ready' => 1,});
  903:       $uname =~s/\W//g;
  904:       $udom  =~s/\W//g;
  905:       my $function_name =
  906:                 join('_','LONCAPA_scriptvars',$uname,$udom,
  907:                      $env{'form.counter'},$Apache::lonxml::curdepth);
  908:       my $rules_var ="<script type=\"text/javascript\">
  909: // <![CDATA[
  910:     function $function_name() {newWindow=open('','new_W','width=500,height=500,scrollbars=1,resizable=yes');newWindow.$windowopen;newWindow.document.writeln('$start_page<pre>".
  911:     $Apache::functionplotresponse::ruleslog.
  912:     "<\\/pre>$end_page');newWindow.document.close();newWindow.focus()}
  913: // ]]>
  914: </script><a href=\"javascript:$function_name();void(0);\">".&mt('Rules Log')."</a><br />";
  915:             &Apache::lonxml::add_script_result($rules_var);
  916:         }
  917: 
  918:   return $result;
  919: }
  920: 
  921: sub compare_rel {
  922:    my ($relationship,$value,$realval,$tol)=@_;
  923: # is the real value undefined?
  924:    unless (defined($realval)) {
  925: # the real value is not defined
  926:       if ($relationship eq 'eq') {
  927:          if ($value eq 'undef') {
  928:             return 1;
  929:          } else {
  930:             return 0;
  931:          }
  932:       } elsif ($relationship eq 'ne') {
  933:          if ($value eq 'undef') {
  934:             return 0;
  935:          } else {
  936:             return 1;
  937:          }
  938:       } else {
  939:          return 0;
  940:       }
  941:    }
  942: 
  943: # is the expected value undefined?
  944:    if ($value eq 'undef') {
  945: # but by now we know that the real value is defined
  946:       return 0;
  947:    }
  948: 
  949: # both are defined.
  950:    if ($relationship eq 'gt') {
  951:       return ($realval>$value);
  952:    } elsif ($relationship eq 'ge') {
  953:       return ($realval>$value-$tol);
  954:    } elsif ($relationship eq 'lt') {
  955:       return ($realval<$value);
  956:    } elsif ($relationship eq 'le') {
  957:       return ($realval<$value+$tol);
  958:    } elsif ($relationship eq 'ne') {
  959:       return (abs($value-$realval)>$tol);
  960:    } else {
  961:       return (abs($value-$realval)<$tol);
  962:    }
  963:    return 0;
  964: }
  965: 
  966: sub addlog {
  967:    my ($text)=@_;
  968:    $Apache::functionplotresponse::ruleslog.=$text.'<br />';
  969: }
  970: 
  971: sub actualval {
  972:    my ($i,$xmin,$xmax)=@_;
  973:    return $xmin+$i/400.*($xmax-$xmin);
  974: }
  975:  
  976: sub functionplotrulecheck {
  977:    my ($rule,$xmin,$xmax,$ymin,$ymax)=@_;
  978: 
  979:    my ($label,$derivative,$xinitial,$xinitiallabel,$xfinal,$xfinallabel,$minimumlength,$maximumlength,$relationship,$value,$percent)
  980:       =split(/\:/,$rule);
  981:    $percent=($percent>0?$percent:5);
  982:    &addlog("=================");
  983:    &addlog("Rule $label for ".($derivative<0?'integral':('function itself','first derivative','second derivative')[$derivative])." $relationship $value");
  984:    if ((defined($minimumlength)) || (defined($maximumlength))) {
  985:       &addlog("Minimumlength $minimumlength Maximumlength $maximumlength");
  986:    }
  987:    my $li=0;
  988:    my $lh=400;
  989: 
  990: # Special case: the upper boundary was not defined
  991: # and needs to be set to the value where
  992: # the condition is not true anymore => set flag
  993: 
  994:    my $findupper=0;
  995:    if (($xfinal eq '')
  996:     && (!defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}))
  997:     && ($xfinallabel)) {
  998:        $findupper=1;
  999:    }
 1000: 
 1001: # if a hard value is set for the boundaries, it overrides the label
 1002:    if (($xinitial ne '') && ($xinitiallabel ne '') && ($xinitiallabel ne 'start')) {
 1003:       $li=&array_index($xmin,$xmax,$xinitial);
 1004:       $Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel}=$li;
 1005:    }
 1006:    if (($xfinal ne '') && ($xfinallabel ne '') && ($xfinallabel ne 'end')) {
 1007:       $lh=&array_index($xmin,$xmax,$xfinal);
 1008:       $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$lh;
 1009:    }
 1010: # if the label is defined, use it
 1011:    if (defined($Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel})) {
 1012:       &addlog("Using lower label $xinitiallabel");
 1013:       $li=$Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel};
 1014:    } else {
 1015:       $li=&array_index($xmin,$xmax,$xinitial);
 1016:    }
 1017:    unless ($findupper) {
 1018:       if (defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel})) {
 1019:          &addlog("Using upper label $xfinallabel");
 1020:          $lh=$Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}-1;
 1021:       } else {
 1022:          $lh=&array_index($xmin,$xmax,$xfinal);
 1023:       }
 1024:    }
 1025: # Basic sanity checks
 1026:    if ($li<0) { $li=0; }
 1027:    if ($lh>400) { $lh=400; }
 1028:    if (($li>$lh) || (!defined($lh))) {
 1029:        $lh=$li;
 1030:    }
 1031: 
 1032:    &addlog("Boundaries: x=".&actualval($li,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$li]."; index $li)) to x=".
 1033:                             &actualval($lh,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$lh]."; index $lh))");
 1034:    if ($findupper) {
 1035:       &addlog("Looking for label $xfinallabel");
 1036:    }
 1037:    my $tol=$percent*($ymax-$ymin)/100;
 1038:    if ($xmax>$xmin) {
 1039:       if ($derivative==2) {
 1040:          $tol=4.*$tol/($xmax-$xmin);
 1041:       } elsif ($derivative==1) {
 1042:          $tol=2.*$tol/($xmax-$xmin);
 1043:       } elsif ($derivative==-1) {
 1044:          $tol=$tol*($xmax-$xmin)/2.;
 1045:       }
 1046:    }
 1047:    my $integral=0;
 1048:    my $binwidth=($xmax-$xmin)/400.;
 1049:    if (($derivative<0) && (!$findupper)) {
 1050: # definite integral, calculate over whole length
 1051:      &addlog("Calculating definite integral");
 1052:      for (my $i=$li; $i<=$lh; $i++) {
 1053:         $integral+=$Apache::functionplotresponse::func[$i]*$binwidth;
 1054:      }
 1055:      unless (&compare_rel($relationship,$value,$integral,$tol)) {
 1056:         &addlog("Actual integral ".(defined($integral)?$integral:'undef').", expected $value, tolerance $tol");
 1057:         &addlog("Rule $label failed.");
 1058:         my $hintlabel=$label;
 1059:         $hintlabel=~s/^R//;
 1060:         push(@Apache::functionplotresponse::failedrules,$hintlabel);
 1061:         &addlog("Set hint condition $hintlabel");
 1062:         return 0;
 1063:      } 
 1064:    } else {
 1065:      for (my $i=$li; $i<=$lh; $i++) {
 1066:         my $val;
 1067:         if ($derivative==2) {
 1068:            $val=$Apache::functionplotresponse::d2funcdx2[$i];
 1069:         } elsif ($derivative==1) {
 1070:            $val=$Apache::functionplotresponse::dfuncdx[$i];
 1071:         } elsif ($derivative==-1) {
 1072:            $integral+=$Apache::functionplotresponse::func[$i]*$binwidth;
 1073:            $val=$integral;      
 1074:         } else {
 1075:            $val=$Apache::functionplotresponse::func[$i];
 1076:         }
 1077:         unless (&compare_rel($relationship,$value,$val,$tol)) { 
 1078:            &addlog("Actual value ".(defined($val)?$val:'undef').", expected $value, tolerance $tol");
 1079:            &addlog("Condition not fulfilled at x=".&actualval($i,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$i]."; index $i)");
 1080:            if (($findupper) && ($i>$li)) {
 1081: # Check lengths
 1082:               unless (&checklength($i,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)) { return 0; }
 1083: # Successfully found a new label, set it
 1084:               $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$i;
 1085:               &addlog("Rule $label passed, setting label $xfinallabel");
 1086:               return 1;
 1087:            } else {
 1088:               &addlog("Rule $label failed.");
 1089:               &setfailed($label);
 1090:               return 0; 
 1091:            }
 1092:         }
 1093:      }
 1094:    }
 1095: # Corner case where this makes sense: using start or stop as defined labels
 1096:    unless (&checklength($lh,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)) { return 0; }
 1097:    &addlog("Rule $label passed.");
 1098:    return 1;
 1099: }
 1100: 
 1101: #
 1102: # check for minimum and maximum lengths
 1103: #
 1104: 
 1105: sub checklength {
 1106:     my ($i,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)=@_;
 1107:     unless (($minimumlength) || ($maximumlength)) { return 1; }
 1108:     my $length=&actualval($i,$xmin,$xmax)-&actualval($li,$xmin,$xmax);
 1109:     if ($minimumlength) {
 1110:        if ($length<$minimumlength) {
 1111:           &addlog("Rule $label failed, actual length $length, minimum length $minimumlength");
 1112:           &setfailed($label);
 1113:           return 0;
 1114:        }
 1115:     }
 1116:     if ($maximumlength) {
 1117:        if ($length>$maximumlength) {
 1118:           &addlog("Rule $label failed, actual length $length, maximum length $maximumlength");
 1119:           &setfailed($label);
 1120:           return 0;
 1121:        }
 1122:     }
 1123:     return 1;
 1124: }
 1125: 
 1126: sub setfailed {
 1127:    my ($label)=@_;
 1128:    my $hintlabel=$label;
 1129:    $hintlabel=~s/^R//;
 1130:    push(@Apache::functionplotresponse::failedrules,$hintlabel);
 1131:    &addlog("Set hint condition $hintlabel");
 1132: }
 1133: 
 1134: sub start_functionplotruleset {
 1135:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1136:    if ($target eq 'edit') {
 1137:       return &Apache::edit::start_table($token).
 1138:         '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Rule Set').'</span></td>'
 1139:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
 1140:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'.
 1141:         &Apache::edit::insertlist($target,$token).'&nbsp;&nbsp;&nbsp;'
 1142:        .&Apache::loncommon::help_open_topic('Function_Plot_Response_Rule_Set','Function Plot Rules')
 1143:        .'</span></td>'
 1144:        ."<td>&nbsp;"
 1145:        .&Apache::edit::end_row()
 1146:        .&Apache::edit::start_spanning_row()
 1147:        ."\n";
 1148:    }
 1149: }
 1150: 
 1151: sub end_functionplotruleset {
 1152:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 1153:     my $id=$Apache::inputtags::response[-1];
 1154:     my $partid=$Apache::inputtags::part;
 1155:     my $internalid = $partid.'_'.$id;
 1156: 
 1157:     if ($target eq 'edit' ) {
 1158:         return &Apache::edit::end_table();
 1159:     }  elsif ($target eq 'grade'
 1160:          && &Apache::response::submitted()
 1161:          && $Apache::lonhomework::type ne 'exam') {
 1162: #
 1163: # Actually grade
 1164: #
 1165:     my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
 1166: 
 1167:         my $ad='';
 1168:         undef  %Apache::functionplotresponse::functionplotrulelabels;
 1169:         $Apache::functionplotresponse::ruleslog='';
 1170:         $Apache::functionplotresponse::functionplotrulelabels{'start'}=400;
 1171:         $Apache::functionplotresponse::functionplotrulelabels{'end'}=0;
 1172:         if (&populate_arrays($internalid,$xmin,$xmax) eq 'no_func') {
 1173:            $ad='NOT_FUNCTION';
 1174:         } else {
 1175:            &addlog("Start of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'start'},$xmin,$xmax)." (index ".
 1176:                                         $Apache::functionplotresponse::functionplotrulelabels{'start'}.")");
 1177:            &addlog("End of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'end'},$xmin,$xmax)." (index ".
 1178:                                         $Apache::functionplotresponse::functionplotrulelabels{'end'}.")");
 1179: 
 1180: # We have a function that we can actually grade, go through the spline rules.
 1181:            foreach my $rule (@Apache::functionplotresponse::functionplotrules) {
 1182:               unless (&functionplotrulecheck($rule,$xmin,$xmax,$ymin,$ymax)) {
 1183:                  $ad='INCORRECT';
 1184:                  last;
 1185:               }
 1186:            }
 1187: # If it's not wrong, it's correct 
 1188:            unless ($ad) { $ad='EXACT_ANS' };
 1189:         }
 1190:         &addlog("Set hint conditions: ".join(",",@Apache::functionplotresponse::failedrules));
 1191:         &addlog("Assigned award detail: $ad");
 1192: # Store for later to be assigned at end_functionplotresponse
 1193:         $Apache::functionplotresponse::awarddetail=$ad;
 1194:      }
 1195: }
 1196: 
 1197: 
 1198: sub end_functionplotresponse {
 1199:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1200:   &Apache::response::end_response;
 1201: 
 1202:   my $result;
 1203:   my $id=$Apache::inputtags::response[-1];
 1204:   my $partid=$Apache::inputtags::part;
 1205:   my $internalid = $partid.'_'.$id;
 1206: 
 1207:     if ($target eq 'edit') { $result=&Apache::edit::end_table(); }
 1208:     if ($target eq 'grade'
 1209:          && &Apache::response::submitted()
 1210:          && $Apache::lonhomework::type eq 'exam') {
 1211: 
 1212:         &Apache::response::scored_response($partid,$id);
 1213: 
 1214:     } elsif ($target eq 'grade'
 1215:          && &Apache::response::submitted()
 1216:          && $Apache::lonhomework::type ne 'exam') {
 1217:         my ($response,%coords)=&get_answer_from_form_fields($internalid);
 1218:         $Apache::lonhomework::results{"resource.$partid.$id.submission"}=$response;
 1219:         my %previous=&Apache::response::check_for_previous($response,$partid,$id);
 1220: #
 1221: # Assign grade
 1222: #
 1223:         my $ad=$Apache::functionplotresponse::awarddetail;
 1224: #
 1225: # Store grading info
 1226: #
 1227:         $Apache::lonhomework::results{"resource.$partid.$id.awarddetail"}=$ad;
 1228:         &Apache::response::handle_previous(\%previous,$ad);
 1229:    } elsif ($target eq 'web') {
 1230:         undef @Apache::functionplotresponse::failedrules;
 1231:    }
 1232:    return $result;
 1233: }
 1234: 
 1235: sub end_functionplotelements {
 1236:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 1237:   my $result='';
 1238:   my $id=$Apache::inputtags::response[-1];
 1239:   my $partid=$Apache::inputtags::part;
 1240:   my $internalid = $partid.'_'.$id;
 1241:   if ($target eq 'edit' ) {
 1242:      $result=&Apache::edit::end_table();
 1243:   } elsif ($target eq 'web') {
 1244:      my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
 1245: 
 1246: # Are we in show answer mode?
 1247:      my $showanswer=&Apache::response::show_answer();
 1248:      if ($showanswer) {
 1249: # Render answerdisplay
 1250:         my $answerdisplay=&Apache::lonxml::get_param('answerdisplay',$parstack,$safeeval,-2);
 1251:         if ($answerdisplay=~/\S/s) {
 1252:            foreach my $plot (split(/\s*\,\s*/,$answerdisplay)) {
 1253:               my @components=split(/\s*\:\s*/,$plot);
 1254:               if ($#components<3) {
 1255: # Just a simple plot
 1256:                  my ($func,$xl,$xh)=@components;
 1257:                  if ((!defined($xl)) || ($xl eq '')) { $xl=$xmin; }
 1258:                  if ((!defined($xh)) || ($xh eq '')) { $xh=$xmax; }
 1259:                  $result.=&plot_script($internalid,$func,1,'','00aa00',$xl,$xh,6);
 1260:               } else {
 1261: # This is a spline
 1262:                  $result.=&answer_spline_script($internalid,@components);
 1263:               }
 1264:            }
 1265:         }
 1266:      }
 1267:      my $fixed=0;
 1268:      if (($showanswer) || (&Apache::response::check_status()>=2)) { $fixed=1; }
 1269: # Now is the time to render all of the stored splines
 1270:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
 1271:         $result.=&generate_spline($internalid,$label,$xmin,$xmax,$ymin,$ymax,$fixed);
 1272:      }
 1273: # close the init script
 1274:      $result.=&end_init_script();
 1275: # register all splines in this response 
 1276:      $result.='<input type="hidden" name="HWVAL_AllSplines_'.$internalid.'" value="'.
 1277:                  join(',',keys(%Apache::functionplotresponse::splineorder)).'" />'."\n";
 1278:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
 1279:         $result.='<input type="hidden" name="HWVAL_SplineOrder_'.$internalid.'_'.$label.'" value="'.
 1280:                  $Apache::functionplotresponse::splineorder{$label}.'" />'."\n";
 1281:      }
 1282: # generate the input fields
 1283:      $result.=$Apache::functionplotresponse::inputfields;
 1284: # actually start the <applet>-tag
 1285:      $result.=&geogebra_startcode($internalid);
 1286: # load the spline bytecode
 1287:      $result.=&geogebra_spline_program();
 1288: # set default parameters
 1289:      $result.=&geogebra_default_parameters($internalid);
 1290: # close the <applet>-tag
 1291:      $result.=&geogebra_endcode();
 1292:   }
 1293:   return $result;
 1294: }
 1295: 
 1296: sub boundaries {
 1297:    my ($parstack,$safeeval,$level)=@_;
 1298:    my $xmin=&Apache::lonxml::get_param('xmin',$parstack,$safeeval,$level);
 1299:    $xmin=(defined($xmin)?$xmin:-10);
 1300:    my $xmax=&Apache::lonxml::get_param('xmax',$parstack,$safeeval,$level);
 1301:    $xmax=(defined($xmax)?$xmax:10);
 1302:    my $ymin=&Apache::lonxml::get_param('ymin',$parstack,$safeeval,$level);
 1303:    $ymin=(defined($ymin)?$ymin:-10);
 1304:    my $ymax=&Apache::lonxml::get_param('ymax',$parstack,$safeeval,$level);
 1305:    $ymax=(defined($ymax)?$ymax:10);
 1306:    if ($xmax<=$xmin) {
 1307:       $xmax=$xmin+20;
 1308:    }
 1309:    if ($ymax<=$ymin) {
 1310:       $ymax=$ymin+20;
 1311:    }
 1312:    return ($xmin,$xmax,$ymin,$ymax);
 1313: }
 1314: 
 1315: sub start_functionplotelements {
 1316:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1317:    my $result='';
 1318:    my $id=$Apache::inputtags::response[-1];
 1319:    my $partid=$Apache::inputtags::part;
 1320:    my $internalid = $partid.'_'.$id;
 1321: 
 1322:    if ($target eq 'edit') {
 1323:       return &Apache::edit::start_table($token).
 1324:         '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Elements').'</span></td>'
 1325:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
 1326:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'.
 1327:         &Apache::edit::insertlist($target,$token).'&nbsp;&nbsp;&nbsp;'
 1328:        .&Apache::loncommon::help_open_topic('Function_Plot_Response_Elements','Function Plot Elements')
 1329:        .'</span></td>'
 1330:        ."<td>&nbsp;"
 1331:        .&Apache::edit::end_row()
 1332:        .&Apache::edit::start_spanning_row()
 1333:        ."\n";
 1334:    } elsif ($target eq 'web') {
 1335:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
 1336:       my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
 1337:       my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
 1338:       my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
 1339:       my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval,-2);
 1340:       my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval,-2);
 1341: 
 1342: 
 1343: # paste in the update routine to receive stuff back from the applet
 1344:      $result.=&update_script($internalid);
 1345: # start the initscript for this applet
 1346:      $result.=&start_init_script($internalid);
 1347: # put the axis commands inside
 1348:      $result.=&axes_script($internalid,$xmin,$xmax,$ymin,$ymax,$xaxisvisible,$yaxisvisible,$gridvisible);
 1349:      $result.=&axes_label($internalid,$xmin,$xmax,$ymin,$ymax,$xlabel,$ylabel);
 1350: # init script is left open
 1351:   }
 1352:   return $result;
 1353: }
 1354: 
 1355: 1;
 1356: 
 1357: __END__
 1358:  
 1359: =head1 NAME
 1360: 
 1361: Apache::functionplotresponse.pm;
 1362: 
 1363: =head1 SYNOPSIS
 1364: 
 1365: Handles tags associated with accepting function plots.
 1366: 
 1367: This is part of the LearningOnline Network with CAPA project
 1368: described at http://www.lon-capa.org.
 1369: 
 1370: =head1 HANDLER SUBROUTINE
 1371: 
 1372: start_functionplotresponse()
 1373: 
 1374: =head1 OTHER SUBROUTINES
 1375: 
 1376: =over
 1377: 
 1378: =item end_functionplotresponse()
 1379: 
 1380: =back
 1381: 
 1382: =cut

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