File:  [LON-CAPA] / loncom / homework / functionplotresponse.pm
Revision 1.53: download - view: text, annotated - select for diffs
Fri Jan 28 16:06:49 2011 UTC (13 years, 3 months ago) by www
Branches: MAIN
CVS tags: HEAD
Sanity check of rule boundaries

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

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