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

1.1       www         1: # LearningOnline Network with CAPA
                      2: # option list style responses
                      3: #
1.33    ! www         4: # $Id: functionplotresponse.pm,v 1.32 2010/11/10 22:53:32 www Exp $
1.1       www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
                     28: 
                     29: package Apache::functionplotresponse;
                     30: use strict;
                     31: use Apache::response();
                     32: use Apache::lonlocal;
                     33: use Apache::lonnet;
                     34: 
                     35: BEGIN {
1.25      www        36:   &Apache::lonxml::register('Apache::functionplotresponse',('functionplotresponse','backgroundplot','spline','functionplotrule'));
1.1       www        37: }
                     38: 
1.5       www        39: #
                     40: # There can be a number of applets on a page, each called ggbApplet_$id, 
                     41: # where $id is the "_"-concatenated part and responseid
                     42: #
                     43: 
1.1       www        44: sub geogebra_startcode {
1.3       www        45:     my ($id)=@_;
1.1       www        46:     return (<<ENDSTARTCODE);
1.3       www        47: <applet name="ggbApplet_$id" code="geogebra.GeoGebraApplet" archive="geogebra.jar"
1.1       www        48:          codebase="/adm/geogebra/"  width="714" height="447" MAYSCRIPT>
                     49:        <param name="java_arguments" value="-Xmx512m -Djnlp.packEnabled=true"/>
                     50: ENDSTARTCODE
                     51: }
                     52: 
                     53: sub geogebra_endcode {
1.2       www        54:     return &Apache::lonhtmlcommon::java_not_enabled()."</applet>\n";
                     55: }
                     56: 
1.5       www        57: #
                     58: # This is the internal GeoGebra bytecode which defines the spline functions
                     59: #
1.2       www        60: sub geogebra_spline_program {
                     61:     return (<<ENDSPLINEPROGRAM);
                     62: <param name="ggbBase64" value="UEsDBBQACAAIADhQET0AAAAAAAAAAAAAAAASAAAAZ2VvZ2VicmFfbWFjcm8ueG1s7Z1bb+PGGYavk19BMDfexkvP+QCsEqzOuWi7gIveBG1By7RXrSwJsqyY+fWdGZLS2pQtzdqWSPoDApOSqCH5vSTnmdH7bj79en8zCVbJ4nY8m7ZCHKEwSKaj2eV4et0K75ZXH1X46y8/frpOZtfJxSIOrmaLm3jZCmlEQvP+TTxazILRzeXf4pukFZ7PJ+NpQsJgOZtNtrw1TCbz9Vu/f8Gn5/j0Czk9J/8Kg/FoNu2PJ+YrYXD7dfbHb9N/mG+040UrXC7ukvXefpvO75ZBjFrh5zCIsVnEZklaYdssqFnE4Vmx7d/vluuNV9nW7VW29ee228zs9NY0P1qa8w+W42W2//hu+XW2sGuX8dK+Y7ZMJslNMl0Gy3Ru3pnPxtNlGEzii2Rij+SXH3/4ZI86mF38Nxkt82MuPr+KJ7eJ3d8Pn8znndlktghM86bY1+7vhfsbT+ZfY7NmRHCbTuI0WQSreGI/zd8xzf11dpk8eDeejo0m9gRul8ncNoBNCedJcpkrmh2yWZmbJp2y3xzQaDZbXN4G962QRBwhKpEginGFJA2DtBWyiDPNJOVYEiwFEmHwZ9au+7orxPn4z/yQqKvqWV6sHWVrN6JsLMIIESqJ4EIiJiXP6yYoUoQIoYggFPHXq5u54l9cOML58UtHIkW4FJJQIqhQQrrK8UhizqRCmHPCNCeveMU1pXIsYlIrIYS57jBhiOWV4+ZdLZCWGEtMsGfl7ueL5NZ2BUU54ov/3Jse4X6erZ7cfwhawQmJUPCX4P7fJzRCH4KPAS1e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CC5OHNkOH/vrO7YT2EXqrQdw/Gb8/ObL2eO5keQI2gjV5jSazCiBtlSVaOuc9nb3OaWP64esBlVDoTnZKd1wm9N4wqjDe7F++JSZvToRLr3Lq4BTTndcGqDEdBp4ZfYA9gPO+7OQguvLz+IPlNbcDIHkue16vMXqHrGyqTbCjNupv7CTwn4TR1GBJlKVOV0kKB2/XkFbUXKZ0/ksICyn7M6IUOyse6XFm2qtc7+R7xAhxIg3wIwwh2VTH2gGfSlFJXjrgvE60ImQk6jsPqfLhCEliHqPWpNoFthKpXS1vRgLDTn/Bq3w7iWbLJaLmMX4wz88dgkWlqSTZJGweTRny9UqWWIKUS8KYYtJzFJkZctZki5SluChf9v81XDcgrVYSkP4GcyYz1qL6ppwt3k2X5W8QZ0SrX3ine21b4N4gLb24m7DvGkX45e2ljBgEVZpD+WhUOdtyFscqF8unT/i9RT1k5JKE+0CRf31sBZh9T5O6NVr5n1m3mPgcKRXe7Ri3sOvRVi9lxRtkDYEHo1Rj1XhZ2GIA5Dcde+YG8kLwGagpG+F3YwbbJrDLVLn/6NvCpya921zpYz+E2U2veu37AC6BRm6qsXC9qo35Oi6N5TO66igFA1ug2FICHfF+oUCAlpBrWHUHUYupMtbP3TuHZxNRxFOg0GtpcW3A+OxLpZt51Kfugm3OF05/c4bMGTD8Y2xF0oqbtHLPR3T98f9iA1vzPovUEsHCEyILqxEAgAAlQQAAFBLAQIUABQACAAIADhQET1gj4YNdwsAAFgqAQASAAAAAAAAAAAAAAAAAAAAAABnZW9nZWJyYV9tYWNyby54bWxQSwECFAAUAAgACAA4UBE9TIgurEQCAACVBAAADAAAAAAAAAAAAAAAAAC3CwAAZ2VvZ2VicmEueG1sUEsFBgAAAAACAAIAegAAADUOAAAAAA=="/>
                     63: ENDSPLINEPROGRAM
                     64: }
                     65: 
1.5       www        66: #
                     67: # The standard set of parameters inside <applet>
                     68: #
1.2       www        69: sub geogebra_default_parameters {
1.3       www        70:    my ($id)=@_;
1.2       www        71:    return(<<ENDDEFAULTPARAMETERS);
                     72:         <param name="image" value="/adm/lonIcons/lonanim.gif"  />
                     73:         <param name="boxborder" value="false"  />
                     74:         <param name="centerimage" value="true"  />
                     75:         <param name="java_arguments" value="-Xmx512m" />
                     76:         <param name="cache_archive" value="geogebra.jar, geogebra_main.jar, geogebra_gui.jar, geogebra_cas.jar, geogebra_export.jar, geogebra_properties.jar" />
                     77:         <param name="cache_version" value="3.2.44.0, 3.2.44.0, 3.2.44.0, 3.2.44.0, 3.2.44.0, 3.2.44.0" />
                     78:         <param name="framePossible" value="false" />
                     79: 
                     80:         <param name="showResetIcon" value="false" />
                     81:         <param name="showAnimationButton" value="false" />
                     82:         <param name="enableRightClick" value="false" />
                     83:         <param name="errorDialogsActive" value="true" />
                     84:         <param name="enableLabelDrags" value="false" />
                     85:         <param name="showMenuBar" value="false" />
                     86:         <param name="showToolBar" value="false" />
                     87:         <param name="showToolBarHelp" value="false" />
                     88:         <param name="showAlgebraInput" value="false" />
                     89:         <param name="enableShiftDragZoom" value="false" />
                     90:         <param name="allowRescaling" value="false" />
                     91:         <param name="enableLabelDrags" value="false" />
1.3       www        92:         <param name="ggbOnInitParam" value="applet_$id" />
1.2       www        93: ENDDEFAULTPARAMETERS
1.1       www        94: }
                     95: 
1.5       www        96: #
                     97: # This subroutine is called by LON-CAPA at </problem>
                     98: # Each applet on the page will call function ggbOnInit when it is done loading
                     99: # This function in turn will call the respective function registered by start_init_script
                    100: # Which one of the registered functions is called is determined by ggbOnInitParam, which GeoGebra passes to ggbOnInit
                    101: #
                    102: 
1.3       www       103: sub init_script {
1.16      www       104:    if ($#Apache::functionplotresponse::callscripts>=0) {
                    105:       my $script='';
                    106:       foreach my $id (@Apache::functionplotresponse::callscripts) {
                    107:           $script.="if (param=='applet_$id') { loaded_$id=true; }\n";
                    108:       }
                    109:       $script.="if (".join(' && ',map { "loaded_$_" } (@Apache::functionplotresponse::callscripts)).
1.17      www       110:                ") { setTimeout('ggbInitAll()',20) }";
1.16      www       111:       my $calls=join("\n",map { "ggbInit_$_();" } (@Apache::functionplotresponse::callscripts)); 
1.3       www       112:       return (<<ENDGGBINIT);
                    113: <script type="text/javascript">
                    114: // <![CDATA[
1.16      www       115: // Function that each applet will call when loaded
                    116: // It will pass "its" parameter
                    117: // Set flags for when an applet is loaded, wait till all are loaded, and then some
1.3       www       118: function ggbOnInit(param) {
1.16      www       119: $script
                    120: }
                    121: function ggbInitAll() {
1.17      www       122: $calls
1.3       www       123: }
                    124: // ]]>
                    125: </script>
                    126: ENDGGBINIT
                    127:    }
                    128: }
                    129: 
1.5       www       130: #
                    131: # Each Geogebra applet is supposed to call this when parameters change
1.10      www       132: # Changes the hidden fields on the web page
1.5       www       133: #
                    134: sub update_script {
                    135:     my ($id)=@_;
                    136:     return (<<ENDUPDATESCRIPT);
                    137: <script type="text/javascript">
                    138: // <![CDATA[
                    139: function updatePointCoordinates_$id(coordinateName) {
                    140:             var x = document.ggbApplet_$id.getXcoord(coordinateName);
                    141:             var y = document.ggbApplet_$id.getYcoord(coordinateName);
1.9       www       142:             document.lonhomework.elements["HWVAL_$id\_" + coordinateName + "_x"].value = x;
                    143:             document.lonhomework.elements["HWVAL_$id\_" + coordinateName + "_y"].value = y;
1.5       www       144:         }
                    145: // ]]>
                    146: </script>
                    147: ENDUPDATESCRIPT
                    148: }
                    149: 
                    150: #
                    151: # Register the above update-handler for a variable
                    152: #
                    153: 
                    154: sub update_register {
                    155:    my ($id,$variable)=@_;
1.6       www       156:    return "document.ggbApplet_$id.registerObjectUpdateListener('$variable','updatePointCoordinates_$id');\n";
                    157: }
                    158: 
                    159: #
                    160: # Set a coordinate variable
                    161: #
                    162: sub set_coordinate {
                    163:    my ($id,$variable,$x,$y)=@_;
                    164:    return (<<ENDSETVARIABLE);
1.9       www       165: document.ggbApplet_$id.evalCommand("$variable=($x,$y)");
1.6       www       166: ENDSETVARIABLE
                    167: }
                    168: 
                    169: #
1.9       www       170: # Input field name for a coordinate variable
                    171: #
                    172: 
                    173: sub field_name {
                    174:     my ($id,$variable,$name)=@_;
                    175:     return "HWVAL_$id\_$variable\_$name";
                    176: }
                    177: 
                    178: #
                    179: # Generate an input field for a coordinate variable
                    180: #
                    181: 
                    182: sub generate_input_field {
                    183:     my ($id,$variable,$x,$y)=@_;
                    184:     $Apache::functionplotresponse::inputfields.=
                    185:        "<input type='hidden' name='".&field_name($id,$variable,'x')."' value='$x' />\n".
                    186:        "<input type='hidden' name='".&field_name($id,$variable,'y')."' value='$y' />\n";
                    187: }
                    188: 
                    189: #
1.6       www       190: # Initialize a new coordinate variable at set a listener on it
                    191: #
                    192: sub new_coordinate {
                    193:     my ($id,$variable,$x,$y)=@_;
1.11      www       194:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'x')})) {
1.10      www       195:        $x=$Apache::functionplotresponse::previous{&field_name($id,$variable,'x')};
                    196:     }
1.11      www       197:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'y')})) {
1.10      www       198:        $y=$Apache::functionplotresponse::previous{&field_name($id,$variable,'y')};
                    199:     }
1.9       www       200:     &generate_input_field($id,$variable,$x,$y);
1.6       www       201:     return &set_coordinate($id,$variable,$x,$y).&update_register($id,$variable);
1.5       www       202: }
                    203: 
                    204: #
                    205: # This registers the init-function call for ggbOnInit, which LON-CAPA will place at </problem>
                    206: # It then starts the right headers
                    207: #
1.3       www       208: sub start_init_script {
                    209:     my ($id)=@_;
1.16      www       210: # Add id to the list of ggbInit_$id functions that need to be called
                    211:     push(@Apache::functionplotresponse::callscripts,$id);
1.5       www       212: # ... and open this function
1.3       www       213:     return (<<ENDSTARTINIT);
                    214: <script type="text/javascript">
                    215: // <![CDATA[
1.5       www       216: // variable that will eventually be passed back to the server
                    217: var coordinateMap_$id = [];
1.16      www       218: // flag for not loaded yet
                    219: var loaded_$id=false;
1.5       www       220: // Init-function for applet
1.3       www       221: function ggbInit_$id() {
                    222: ENDSTARTINIT
                    223: }
                    224: 
1.5       www       225: #
                    226: # This sets the axes inside ggbInit_$id
                    227: #
                    228: 
1.4       www       229: sub axes_script {
                    230:     my ($id,$xmin,$xmax,$ymin,$ymax,$xvisible,$yvisible,$gvisible)=@_;
                    231:     return (<<ENDAXESSCRIPT);
                    232:             // changes (xmin, xmax, ymin, ymax)
                    233:             document.ggbApplet_$id.setCoordSystem($xmin,$xmax,$ymin,$ymax);
                    234: 
                    235:             // makes the (x,y) axis (in)visible
                    236:             document.ggbApplet_$id.setAxesVisible($xvisible,$yvisible);
                    237:             // makes the grid (in)visible
                    238:             document.ggbApplet_$id.setGridVisible($gvisible);
                    239: ENDAXESSCRIPT
                    240: }
                    241: 
1.14      www       242: sub axes_label {
                    243:     my ($id,$xlabel,$ylabel)=@_;
                    244:     unless ($xlabel || $ylabel) { return ''; }
                    245:     my $return='document.ggbApplet_'.$id.'.evalCommand("topRight=Corner[3]");';
                    246:     if ($xlabel) {
                    247:        $return.=(<<ENDXAXISLABELSCRIPT);
                    248: document.ggbApplet_$id.evalCommand("Xlabel=(x(topRight)-AxisStepX[],AxisStepY[]/6)");
                    249: document.ggbApplet_$id.setVisible("Xlabel",false);
                    250: document.ggbApplet_$id.evalCommand("Text[\\"$xlabel\\", Xlabel]");
                    251: ENDXAXISLABELSCRIPT
                    252:     }
                    253:     if ($ylabel) {
                    254:        $return.=(<<ENDYAXISLABELSCRIPT);
                    255: document.ggbApplet_$id.evalCommand("Ylabel=(AxisStepX[]/6,y(topRight)-AxisStepY[]/3)");
                    256: document.ggbApplet_$id.setVisible("Ylabel",false);
                    257: document.ggbApplet_$id.evalCommand("Text[\\"$ylabel\\", Ylabel]");
                    258: ENDYAXISLABELSCRIPT
                    259:     }
                    260:     return $return;
                    261: }
                    262: 
1.4       www       263: sub plot_script {
1.6       www       264:    my ($id,$function,$fixed)=@_;
                    265:    if ($fixed) {
                    266: # Use stupid trick to nail this to a location
1.14      www       267: # Oddly, it seems like only one plot cannot be nailed to a location
                    268: # Non-nailed-down plots apparently get overwritten
1.6       www       269:       return (<<ENDPLOTSCRIPT);
                    270:             document.ggbApplet_$id.evalCommand("a=1");
                    271:             document.ggbApplet_$id.setVisible("a",false);
                    272:             // This MUST be a DEPENDENT OBJECT in order to be locked down:
                    273:             document.ggbApplet_$id.evalCommand("y=a*($function)");
1.4       www       274: ENDPLOTSCRIPT
1.6       www       275:    } else {
                    276:        return "document.ggbApplet_$id.evalCommand('y=$function')";
                    277:    }
1.4       www       278: }
                    279: 
1.5       www       280: #
1.7       www       281: # Subroutine that generates code for spline $label based on stored information
1.6       www       282: #
                    283: 
                    284: sub generate_spline {
                    285:    my ($id,$label)=@_;
                    286:    my $result='';
1.7       www       287:    my $order=$Apache::functionplotresponse::splineorder{$label};
                    288:    my $x=$Apache::functionplotresponse::splineinitx{$label};
                    289:    my $y=$Apache::functionplotresponse::splineinity{$label};
                    290:    my $sx=$Apache::functionplotresponse::splinescalex{$label};
                    291:    my $sy=$Apache::functionplotresponse::splinescaley{$label};
                    292:    my @coords=();
                    293:    foreach my $i (1..$order) {
                    294:        $result.=&new_coordinate($id,$label.'P'.$i,$x,$y);
1.8       www       295:        $x+=$sx/(2.*($order-1));
1.7       www       296:        push(@coords,$label.'P'.$i);
                    297:        $result.=&new_coordinate($id,$label.'S'.$i,$x,$y+$sy);
1.8       www       298:        $x+=$sx/(2.*($order-1));
1.7       www       299:        push(@coords,$label.'S'.$i);
                    300:    }
                    301:    $result.='document.ggbApplet_'.$id.'.evalCommand("Spline'.$order.'['.join(',',@coords).']");'."\n";
1.6       www       302:    return $result;
                    303: }
                    304: #
                    305: # <backgroundplot function="..." fixed="yes/no" />
1.5       www       306: #
1.4       www       307: sub start_backgroundplot {
                    308:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    309:    my $result='';
                    310:    my $internalid = $Apache::inputtags::part.'_'.$Apache::inputtags::response[-1];
                    311:    my $function=&Apache::lonxml::get_param('function',$parstack,$safeeval);
1.6       www       312:    my $fixed=(&Apache::lonxml::get_param('fixed',$parstack,$safeeval)=~/on|true|yes|1/i?1:0);
                    313:  
1.4       www       314:    unless ($function) { $function="0"; }
                    315:    if ($target eq 'web') {
1.6       www       316:       $result.=&plot_script($internalid,$function,$fixed);
1.13      www       317:    } elsif ($target eq 'edit') {
                    318:         $result=&Apache::edit::tag_start($target,$token,'Background Function Plot').
                    319:              &Apache::edit::text_arg('Function:','function',
                    320:                                      $token,'16').
                    321:              &Apache::edit::select_arg('Fixed location:','fixed',
                    322:                                   ['yes','no'],$token).
                    323:              &Apache::edit::end_row();
                    324:   } elsif ($target eq 'modified') {
                    325:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
                    326:                                                  $safeeval,'function','fixed');
                    327:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
                    328:   }
                    329:   return $result;
1.4       www       330: }
                    331: 
                    332: sub end_backgroundplot {
1.13      www       333:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    334:    my $result='';
                    335:    if ($target eq 'edit') {
                    336:        $result=&Apache::edit::end_table();
                    337:    }
                    338:    return $result;
1.6       www       339: }
                    340: 
                    341: #
1.25      www       342: # <functionplotrule ... />
1.12      www       343: #
1.25      www       344: sub start_functionplotrule {
1.12      www       345:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    346:    my $result='';
1.24      www       347:    my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
                    348:    $Apache::functionplotresponse::counter++;
                    349:    if ($label=~/\W/) {
1.25      www       350:       &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
1.24      www       351:    }
                    352:    $label=~s/\W//gs;
                    353:    unless ($label) {
                    354:       $label='R'.$Apache::functionplotresponse::counter;
                    355:    } else {
                    356:       $label='R'.$label;
                    357:    }
                    358:    if ($Apache::functionplotresponse::splineorder{$label}) {
1.25      www       359:        &Apache::lonxml::error(&mt('Rule indices must be unique.'));
1.24      www       360:    }
                    361: 
                    362: 
                    363:    if ($target eq 'grade') {
                    364: # Simply remember - in order - for later
1.25      www       365:       my $beginninglabel=&Apache::lonxml::get_param('xinitiallabel',$parstack,$safeeval);
                    366:       my $endinglabel=&Apache::lonxml::get_param('xfinallabel',$parstack,$safeeval);
1.24      www       367:       if (($beginninglabel=~/\W/) || ($endinglabel=~/W/)) {
1.25      www       368:           &Apache::lonxml::warning(&mt('Rule labels must be alphanumeric.'));
1.24      www       369:       }
                    370:       $beginninglabel=~s/\W//gs;
                    371:       $endinglabel=~s/\W//gs;
                    372:       my $relationship=&Apache::lonxml::get_param('relationship',$parstack,$safeeval);
                    373:       $relationship=~s/\W//gs;
                    374:       $relationship=lc($relationship);
                    375:       unless ($relationship=~/^(eq|ge|gt|le|lt|ne)$/) {
1.25      www       376:           &Apache::lonxml::warning(&mt('Rule relationship not defined.'));
1.24      www       377:           $relationship='eq';
                    378:       }
                    379:       my $derivative=&Apache::lonxml::get_param('derivative',$parstack,$safeeval);
                    380:       unless (($derivative==0) || ($derivative==1) || ($derivative==2)) {
1.25      www       381:          &Apache::lonxml::warning(&mt('Rule derivative not defined.'));
1.24      www       382:          $derivative=0;
                    383:       }
1.25      www       384:       push(@Apache::functionplotresponse::functionplotrules,join(':',(
1.24      www       385:            $label,
                    386:            $derivative,
1.25      www       387:            &Apache::lonxml::get_param('xinitial',$parstack,$safeeval),
1.24      www       388:            $beginninglabel,
1.25      www       389:            &Apache::lonxml::get_param('xfinal',$parstack,$safeeval),
1.24      www       390:            $endinglabel,
                    391:            $relationship,
1.33    ! www       392:            &Apache::lonxml::get_param('value',$parstack,$safeeval),
        !           393:            &Apache::lonxml::get_param('percenterror',$parstack,$safeeval)
1.24      www       394:           )));
                    395:    } elsif ($target eq 'edit') {
1.29      www       396:         $result=&Apache::edit::tag_start($target,$token,'Function Plot Evaluation Rule').
                    397:              &Apache::edit::text_arg('Index:','index',
                    398:                                      $token,'4').'&nbsp;'.
                    399:              &Apache::edit::select_arg(&mt('Function:'),'derivative',
                    400:                                   [['0','Function itself'],
                    401:                                    ['1','First derivative'],
1.32      www       402:                                    ['2','Second derivative']],$token).'<br />'.
1.30      www       403: 
1.29      www       404:              &Apache::edit::text_arg('(Initial) x-value:','xinitial',
1.30      www       405:                                       $token,'4').
                    406:              &Apache::edit::select_or_text_arg('(Initial) x-value label:','xinitiallabel',
1.32      www       407:                                                [['start','Start of Plot']],$token,'8').'<br />'.
1.30      www       408: 
                    409:              &Apache::edit::text_arg('Optional final x-value for ranges:','xfinal',
                    410:                                       $token,'4').
                    411:              &Apache::edit::select_or_text_arg('Optional final x-value label:','xfinallabel',
1.32      www       412:                                                [['end','End of Plot']],$token,'8').'<br />'.
1.30      www       413: 
1.29      www       414:              &Apache::edit::select_arg(&mt('Relationship:'),'relationship',
                    415:                                   [['eq','equal'],
                    416:                                    ['ne','not equal'],
                    417:                                    ['ge','greater than or equal'],
                    418:                                    ['gt','greater than'],
                    419:                                    ['lt','less than'],
                    420:                                    ['le','less than or equal']],$token).
                    421:              $result.= &Apache::edit::select_or_text_arg('Value:','value',
                    422:                                                [['undef','not defined']],$token,'4').
                    423:              &Apache::edit::text_arg('Percent error:','percenterror',
                    424:                                      $token,'4').
                    425:              &Apache::edit::end_row();
                    426:   } elsif ($target eq 'modified') {
                    427:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.30      www       428:                                                  $safeeval,'index','derivative','xinitial','xinitiallabel','xfinal','xfinallabel','relationship',
1.29      www       429:                                                            'value','percenterror');
                    430:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
1.13      www       431:    }
1.12      www       432:    return $result;
                    433: }
                    434: 
1.25      www       435: sub end_functionplotrule {
1.13      www       436:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    437:    my $result='';
                    438:    if ($target eq 'edit') {
                    439:        $result=&Apache::edit::end_table();
                    440:    }
                    441:    return $result;
1.12      www       442: }
                    443: 
                    444: 
                    445: #
1.23      www       446: # <spline index="..." order="1,2,3,4" initx="..." inity="..." scalex="..." scaley="..." />
1.6       www       447: #
                    448: # Unfortunately, GeoGebra seems to want all splines after everything else, so we need to store them
                    449: #
                    450: sub start_spline {
                    451:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1.13      www       452:    my $result='';
                    453:    if ($target eq 'web') {
1.23      www       454:       my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
1.13      www       455:       $Apache::functionplotresponse::counter++;
                    456:       if ($label=~/\W/) {
1.23      www       457:          &Apache::lonxml::warning(&mt('Spline indices should only contain alphanumeric characters.'));
1.13      www       458:       }
                    459:       $label=~s/\W//gs;
1.23      www       460:       unless ($label) { 
                    461:          $label='S'.$Apache::functionplotresponse::counter; 
                    462:       } else {
                    463:          $label='S'.$label;
                    464:       }
1.13      www       465:       if ($Apache::functionplotresponse::splineorder{$label}) {
1.23      www       466:          &Apache::lonxml::error(&mt('Spline indices must be unique.'));
1.13      www       467:       }
                    468: 
                    469:       my $order=&Apache::lonxml::get_param('order',$parstack,$safeeval);
                    470:       if ($order<2) { $order=2; }
                    471:       if ($order>8) { $order=8; }
                    472:       $Apache::functionplotresponse::splineorder{$label}=$order;
                    473: 
                    474:       my $x=&Apache::lonxml::get_param('initx',$parstack,$safeeval);
                    475:       unless ($x) { $x=0; }
                    476:       $Apache::functionplotresponse::splineinitx{$label}=$x;
                    477: 
                    478:       my $y=&Apache::lonxml::get_param('inity',$parstack,$safeeval);
                    479:       unless ($y) { $y=0; }
                    480:       $Apache::functionplotresponse::splineinity{$label}=$y;
                    481: 
                    482:       my $sx=&Apache::lonxml::get_param('scalex',$parstack,$safeeval);
                    483:       unless ($sx) { $sx=$order; }
                    484:       $Apache::functionplotresponse::splinescalex{$label}=$sx;
                    485: 
                    486:       my $sy=&Apache::lonxml::get_param('scaley',$parstack,$safeeval);
                    487:       unless ($sy) { $sy=2; }
                    488:       $Apache::functionplotresponse::splinescaley{$label}=$sy;
                    489:    } elsif ($target eq 'edit') {
                    490:         $result=&Apache::edit::tag_start($target,$token,'Spline').
1.23      www       491:              &Apache::edit::text_arg('Index:','index',
1.14      www       492:                                      $token,'4').'&nbsp;'.
1.13      www       493:              &Apache::edit::select_arg('Order:','order',
1.14      www       494:                                   ['2','3','4','5','6','7','8','9'],$token).'&nbsp;'.
1.13      www       495:              &Apache::edit::text_arg('Initial x-value:','initx',
1.14      www       496:                                      $token,'4').'&nbsp;'.
1.13      www       497:              &Apache::edit::text_arg('Initial y-value:','inity',
1.14      www       498:                                      $token,'4').'&nbsp;'.
1.13      www       499:              &Apache::edit::text_arg('Scale x:','scalex',
1.14      www       500:                                      $token,'4').'&nbsp;'.
1.13      www       501:              &Apache::edit::text_arg('Scale y:','scaley',
                    502:                                      $token,'4').
                    503:              &Apache::edit::end_row();
                    504:   } elsif ($target eq 'modified') {
                    505:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.23      www       506:                                                  $safeeval,'index','order','initx','inity',
1.13      www       507:                                                            'scalex','scaley');
                    508:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
                    509:   }
                    510:   return $result;
1.6       www       511: }
                    512: 
                    513: sub end_spline {
1.13      www       514:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    515:    my $result='';
                    516:    if ($target eq 'edit') {
                    517:        $result=&Apache::edit::end_table();
                    518:    }
                    519:    return $result;
1.4       www       520: }
                    521:  
1.3       www       522: sub end_init_script {
                    523:     return (<<ENDENDINIT);
                    524: }
                    525: // ]]>
                    526: </script>
                    527: ENDENDINIT
                    528: }
                    529: 
1.10      www       530: #
                    531: # Storing and restoring spline coordinates from part answers
                    532: #
                    533: sub decode_previous_answer {
                    534:    my ($answer)=@_;
                    535:    foreach my $coordinate (split(/\,/,$answer)) {
                    536:       my ($key,$value)=split(/\=/,$coordinate);
                    537:       $Apache::functionplotresponse::previous{$key}=$value;
                    538:    }
                    539: }
                    540: 
                    541: sub get_answer_from_form_fields {
                    542:    my ($id)=@_;
                    543:    my $answer='';
                    544:    my %coords=();
                    545:    foreach my $field (keys(%env)) {
                    546:       if ($field=~/^form\.HWVAL\_$id/) {
                    547:          $field=~/^form\.(.*)$/;
                    548:          $coords{$1}=$env{$field};
                    549:       }
                    550:    }
                    551:    $answer=join(',',map { $_.'='.$coords{$_} } (sort(keys(%coords))));
                    552:    return ($answer,%coords);
                    553: }
                    554: 
1.15      www       555: #
                    556: # The following functions calculate the cubic-hermite splines server-side
                    557: #
                    558: 
                    559: sub cubic_hermite {
                    560:    my ($t,$p1,$s1,$p2,$s2)=@_;
                    561:    return (2.*$t*$t*$t-3.*$t*$t+1.)*$p1 + 5.*($t*$t*$t-2.*$t*$t+$t)*($s1-$p1)+
                    562:           (-2.*$t*$t*$t+3.*$t*$t)  *$p2 + 5.*($t*$t*$t-$t*$t)      *($s2-$p2);
                    563: }
                    564: 
                    565: #
                    566: # d/dt(...)
                    567: # 
                    568: 
                    569: sub ddt_cubic_hermite {
                    570:    my ($t,$p1,$s1,$p2,$s2)=@_;
                    571:    return (6.*$t*$t-6.*$t) *$p1 + 5.*(3.*$t*$t-4.*$t+1.)*($s1-$p1)+
                    572:           (-6.*$t*$t+6.*$t)*$p2 + 5.*(3.*$t*$t-2.*$t)   *($s2-$p2);
                    573: }
                    574: 
                    575: #
                    576: # d^2/dt^2(...)
                    577: #
                    578: 
                    579: sub d2dt2_cubic_hermite {
                    580:    my ($t,$p1,$s1,$p2,$s2)=@_;
                    581:    return (12.*$t-6.) *$p1 + 5.*(6.*$t-4.)*($s1-$p1)+
                    582:           (-12.*$t+6.)*$p2 + 5.*(6.*$t-2.)*($s2-$p2);
                    583: }
                    584: 
                    585: #
1.18      www       586: # Array index calculation
                    587: #
                    588: sub array_index {
                    589:    my ($xmin,$xmax,$x)=@_;
1.26      www       590:    return int(($x-$xmin)/($xmax-$xmin)*400.+0.5);
1.20      www       591: }
                    592: 
                    593: #
1.18      www       594: # Populate the arrays
                    595: #
                    596: 
                    597: sub populate_arrays {
                    598:     my ($id,$xmin,$xmax)=@_;
1.26      www       599:     for (my $i=0; $i<=400; $i++) {
1.19      www       600:        $Apache::functionplotresponse::func[$i]=undef;
1.22      www       601:        $Apache::functionplotresponse::dfuncdx[$i]=undef;
1.19      www       602:        $Apache::functionplotresponse::d2funcd2x[$i]=undef;
1.18      www       603:     }
1.19      www       604:     unless ($xmax>$xmin) { return 'no_func'; }
1.18      www       605: # Run over all splines in response
                    606:     foreach my $label (split(/\,/,$env{"form.HWVAL_AllSplines_$id"})) {
1.19      www       607:         my $xiold=-1;
1.18      www       608: # Run over all points in spline
1.19      www       609:         for (my $i=1; $i<$env{"form.HWVAL_SplineOrder_".$id."_".$label}; $i++) {
1.18      www       610:             my $ni=$i+1;
                    611:             my @xparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_x'},
                    612:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_x'},
                    613:                         $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_x'},
                    614:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_x'});
                    615:             my @yparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_y'},
                    616:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_y'},
                    617:                         $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_y'},
                    618:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_y'});
                    619: # Run in small steps over spline parameter
1.26      www       620:             for (my $t=0; $t<=1; $t+=0.0001) {
1.18      www       621:                 my $xi=&array_index($xmin,$xmax,&cubic_hermite($t,@xparms));
1.19      www       622:                 if ($xi<$xiold) { return 'no_func'; }
1.26      www       623:                 if (($xi>$xiold) && ($xi>=0) && ($xi<=400)) {
1.19      www       624:                    if (defined($Apache::functionplotresponse::func[$xi])) { return 'no_func'; }
1.18      www       625:                    $xiold=$xi;
1.22      www       626: # Function value
1.30      www       627:                    my $funcval=&cubic_hermite($t,@yparms);
                    628:                    $Apache::functionplotresponse::func[$xi]=$funcval;
                    629:                    if (defined($funcval)) {
                    630:                       if ($xi<$Apache::functionplotresponse::functionplotrulelabels{'start'}) {
                    631:                          $Apache::functionplotresponse::functionplotrulelabels{'start'}=$xi;
                    632:                       }
                    633:                       if ($xi>$Apache::functionplotresponse::functionplotrulelabels{'end'}) {
                    634:                          $Apache::functionplotresponse::functionplotrulelabels{'end'}=$xi;
                    635:                       }
                    636:                    }
1.28      www       637: # Chain rule
1.22      www       638: # dy/dx=dy/dt/(dx/dt)
                    639:                    my $dxdt=&ddt_cubic_hermite($t,@xparms);
                    640:                    if ($dxdt) {
                    641:                       $Apache::functionplotresponse::dfuncdx[$xi]=&ddt_cubic_hermite($t,@yparms)/$dxdt;
                    642:                    }
1.28      www       643: # Faa di Bruno
                    644: # d^2y/dx^2=(d^2y/dt^2)/(dx/dt)^2+(dy/dt)/(d^2x/dt^2)
1.22      www       645:                    my $d2xdt2=&d2dt2_cubic_hermite($t,@xparms);
1.28      www       646:                    if (($dxdt) && ($d2xdt2)) {
                    647:                       $Apache::functionplotresponse::d2funcdx2[$xi]=
                    648:                          &d2dt2_cubic_hermite($t,@yparms)/($dxdt*$dxdt)
                    649:                         +&ddt_cubic_hermite($t,@yparms)/$d2xdt2;
1.22      www       650:                    }
1.18      www       651:                 }
                    652:             }
                    653:         }
                    654:     }
                    655: }
                    656: 
                    657: #
1.15      www       658: # Implentation of <functionplotresponse>
                    659: #
                    660: 
1.1       www       661: sub start_functionplotresponse {
                    662:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    663:   my $result='';
1.6       www       664: # To remember the splines - somehow, they need to come last
                    665:   undef %Apache::functionplotresponse::splineorder;
                    666:   undef %Apache::functionplotresponse::splineinitx;
                    667:   undef %Apache::functionplotresponse::splineinity;
                    668:   undef %Apache::functionplotresponse::splinescalex;
                    669:   undef %Apache::functionplotresponse::splinescaley;
1.10      www       670: # Remember input fields, etc
                    671:   undef %Apache::functionplotresponse::previous;
1.9       www       672:   $Apache::functionplotresponse::inputfields='';
1.6       www       673:   $Apache::functionplotresponse::counter=0;
1.24      www       674: # Remember rules
1.25      www       675:   undef @Apache::functionplotresponse::functionplotrules;
1.10      www       676: # Part and ID
                    677:   my $partid=$Apache::inputtags::part;
                    678:   my $id=&Apache::response::start_response($parstack,$safeeval);
1.6       www       679: # Internal ID to mark the applet and its coordinates
1.10      www       680:   my $internalid = $partid.'_'.$id;
                    681: # Previous answer
                    682:   &decode_previous_answer($Apache::lonhomework::history{"resource.$partid.$id.submission"});
                    683: 
1.6       www       684: # Parameters of <functionplotresponse>
1.3       www       685:   my $xmin=&Apache::lonxml::get_param('xmin',$parstack,$safeeval);
1.18      www       686:   $xmin=(defined($xmin)?$xmin:-10);
1.3       www       687:   my $xmax=&Apache::lonxml::get_param('xmax',$parstack,$safeeval);
1.18      www       688:   $xmax=(defined($xmax)?$xmax:10);
1.3       www       689:   my $ymin=&Apache::lonxml::get_param('ymin',$parstack,$safeeval);
1.18      www       690:   $ymin=(defined($ymin)?$ymin:-10);
1.3       www       691:   my $ymax=&Apache::lonxml::get_param('ymax',$parstack,$safeeval);
1.18      www       692:   $ymax=(defined($ymax)?$ymax:10);
1.25      www       693:   if ($xmax<=$xmin) {
                    694:      &Apache::lonxml::warning('Maximum x-value needs to be larger than minimum value.');
                    695:      $xmax=$xmin+20;
                    696:   }
                    697:   if ($ymax<=$ymin) {
                    698:      &Apache::lonxml::warning('Maximum y-value needs to be larger than minimum value.');
                    699:      $ymax=$ymin+20;
                    700:   }
1.6       www       701:   my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
                    702:   my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
                    703:   my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
1.14      www       704:   my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval);
                    705:   my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval);
1.12      www       706:   if ($target eq 'edit') {
                    707:     $result.=&Apache::edit::start_table($token)
                    708:        .'<tr><td><span class="LC_nobreak">'.&mt('Function Plot Question').'</span></td>'
                    709:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
                    710:        .&Apache::edit::deletelist($target,$token)
                    711:        .'</span></td>'
                    712:        ."<td>&nbsp;"
                    713:        .&Apache::edit::end_row()
                    714:        .&Apache::edit::start_spanning_row()
                    715:        ."\n";
1.14      www       716:     $result.=&Apache::edit::text_arg('Label x-axis:','xlabel',
                    717:                                      $token,'6').'&nbsp;'.
                    718:              &Apache::edit::text_arg('Minimum x-value:','xmin',
                    719:                                      $token,'4').'&nbsp;'.
1.12      www       720:              &Apache::edit::text_arg('Maximum x-value:','xmax',
1.14      www       721:                                      $token,'4').'&nbsp;'.
1.12      www       722:              &Apache::edit::select_arg('x-axis visible:','xaxisvisible',
1.32      www       723:                                   ['yes','no'],$token).'<br />'.
1.14      www       724:              &Apache::edit::text_arg('Label y-axis:','ylabel',
                    725:                                      $token,'6').'&nbsp;'.
1.12      www       726:              &Apache::edit::text_arg('Minimum y-value:','ymin',
1.14      www       727:                                      $token,'4').'&nbsp;'.
1.12      www       728:              &Apache::edit::text_arg('Maximum y-value:','ymax',
1.14      www       729:                                      $token,'4').'&nbsp;'.
1.12      www       730:              &Apache::edit::select_arg('y-axis visible:','yaxisvisible',
1.32      www       731:                                   ['yes','no'],$token).'<br />'.
1.12      www       732:              &Apache::edit::select_arg('Grid visible:','gridvisible',
                    733:                                   ['yes','no'],$token).
                    734:              &Apache::edit::end_row().&Apache::edit::start_spanning_row();
                    735:   } elsif ($target eq 'modified') {
                    736:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.14      www       737:                                                  $safeeval,'xlabel','xmin','xmax','ylabel','ymin','ymax',
1.12      www       738:                                                            'xaxisvisible','yaxisvisible','gridvisible');
                    739:     if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
1.3       www       740: 
1.12      www       741:   } elsif ($target eq 'meta') {
1.10      www       742:        $result=&Apache::response::meta_package_write('functionplotresponse');
1.12      www       743:   } elsif ($target eq 'web') {
1.5       www       744: # paste in the update routine to receive stuff back from the applet
                    745:      $result.=&update_script($internalid);
                    746: # start the initscript for this applet
1.3       www       747:      $result.=&start_init_script($internalid);
1.5       www       748: # put the axis commands inside
1.4       www       749:      $result.=&axes_script($internalid,$xmin,$xmax,$ymin,$ymax,$xaxisvisible,$yaxisvisible,$gridvisible);
1.14      www       750:      $result.=&axes_label($internalid,$xlabel,$ylabel);
1.5       www       751: # init script is left open
1.1       www       752:   }
                    753:   return $result;
                    754: }
                    755: 
1.25      www       756: sub compare_rel {
1.26      www       757:    my ($relationship,$value,$realval,$tol)=@_;
                    758: # is the real value defined?
                    759:    unless (defined($realval)) {
                    760:       if ($relationship eq 'eq') {
                    761:          if ($value eq 'undef') {
                    762:             return 1;
                    763:          } else {
                    764:             return 0;
                    765:          }
                    766:       } elsif ($relationship eq 'ne') {
                    767:          if ($value eq 'undef') {
                    768:             return 0;
                    769:          } else {
                    770:             return 1;
                    771:          }
                    772:       } else {
                    773:          return 0;
                    774:       }
                    775:    }
                    776: 
                    777: # it is defined.
                    778:    if ($relationship eq 'gt') {
                    779:       return ($realval>$value);
                    780:    } elsif ($relationship eq 'ge') {
                    781:       return ($realval>$value-$tol);
                    782:    } elsif ($relationship eq 'lt') {
                    783:       return ($realval<$value);
                    784:    } elsif ($relationship eq 'le') {
                    785:       return ($realval<$value+$tol);
                    786:    } elsif ($relationship eq 'ne') {
                    787:       return (abs($value-$realval)>$tol);
                    788:    } else {
                    789:       return (abs($value-$realval)<$tol);
                    790:    }
1.25      www       791:    return 0;
                    792: }
                    793: 
                    794: sub functionplotrulecheck {
1.33    ! www       795:    my ($rule,$xmin,$xmax,$ymin,$ymax)=@_;
        !           796: 
        !           797: #   &Apache::lonnet::logthis("Rule $rule $xmin $xmax $ymin $ymax");
        !           798: 
        !           799:    my ($label,$derivative,$xinitial,$xinitiallabel,$xfinal,$xfinallabel,$relationship,$value,$percent)
1.25      www       800:       =split(/\:/,$rule);
1.33    ! www       801:    $percent=($percent>0?$percent:5);
1.30      www       802: 
                    803:    my $li=0;
                    804:    my $lh=400;
                    805: 
1.31      www       806: # Special case: the upper boundary was not defined
                    807: # and needs to be set to the value where
                    808: # the condition is not true anymore => set flag
                    809: 
                    810:    my $findupper=0;
                    811:    if (($xfinal eq '')
                    812:     && (!defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}))
                    813:     && ($xfinallabel)) {
                    814:        $findupper=1;
                    815:    }
                    816: 
1.25      www       817: # if a hard value is set for the boundaries, it overrides the label
1.30      www       818:    if (($xinitial ne '') && ($xinitiallabel ne '') && ($xinitiallabel ne 'start')) {
                    819:       $li=&array_index($xmin,$xmax,$xinitial);
                    820:       $Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel}=$li;
                    821:    }
                    822:    if (($xfinal ne '') && ($xfinallabel ne '') && ($xfinallabel ne 'end')) {
                    823:       $lh=&array_index($xmin,$xmax,$xfinal);
                    824:       $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$lh;
1.25      www       825:    }
1.31      www       826: # if the label is defined, use it
1.25      www       827:    if (defined($Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel})) {
1.30      www       828:       $li=$Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel};
                    829:    } else {
                    830:       $li=&array_index($xmin,$xmax,$xinitial);
1.25      www       831:    }
1.31      www       832:    unless ($findupper) {
                    833:       if (defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel})) {
1.33    ! www       834:          $lh=$Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}-1;
1.31      www       835:       } else {
                    836:          $lh=&array_index($xmin,$xmax,$xfinal);
                    837:       }
1.25      www       838:    }
                    839: # Basic sanity checks
1.30      www       840:    if ($li<0) { $li=0; }
                    841:    if ($lh>400) { $lh=400; }
                    842:    if ($li>$lh) {
                    843:        $lh=$li;
1.25      www       844:    }
1.31      www       845: 
1.32      www       846: #   &Apache::lonnet::logthis("Init $xinitial=$li Final $xfinal=$lh Findupper: $findupper");
1.33    ! www       847:    my $tol=$percent*($ymax-$ymin)/100;
        !           848:    if ($xmax>$xmin) {
        !           849:       if ($derivative==2) {
        !           850:          $tol=4.*$tol/($xmax-$xmin);
        !           851:       } elsif ($derivative==1) {
        !           852:          $tol=2.*$tol/($xmax-$xmin);
        !           853:       }
1.27      www       854:    }
                    855:    for (my $i=$li; $i<=$lh; $i++) {
1.25      www       856:         my $val;
                    857:         if ($derivative==2) {
1.27      www       858:            $val=$Apache::functionplotresponse::d2funcdx2[$i];
1.25      www       859:         } elsif ($derivative==1) {
1.27      www       860:            $val=$Apache::functionplotresponse::dfuncdx[$i];
1.25      www       861:         } else {
1.27      www       862:            $val=$Apache::functionplotresponse::func[$i];
1.25      www       863:         }
1.31      www       864:         unless (&compare_rel($relationship,$value,$val,$tol)) { 
1.33    ! www       865: #           &Apache::lonnet::logthis("Condition false $findupper at $i with $val tol:$tol from $value");
1.31      www       866:            if (($findupper) && ($i>$li)) {
                    867:               $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$i;
1.32      www       868: #              &Apache::lonnet::logthis("Setting $xfinallabel to $i");
1.31      www       869:               return 1;
                    870:            } else {
                    871:               return 0; 
                    872:            }
                    873:         }
1.25      www       874:    }
1.27      www       875:    return 1;
1.24      www       876: }
                    877: 
1.1       www       878: sub end_functionplotresponse {
                    879:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    880:   &Apache::response::end_response;
1.3       www       881: 
1.1       www       882:   my $result;
1.10      www       883:   my $id=$Apache::inputtags::response[-1];
                    884:   my $partid=$Apache::inputtags::part;
                    885:   my $internalid = $partid.'_'.$id;
1.3       www       886: 
1.12      www       887:     if ($target eq 'edit') { $result=&Apache::edit::end_table(); }
1.10      www       888:     if ($target eq 'grade'
                    889:          && &Apache::response::submitted()
                    890:          && $Apache::lonhomework::type eq 'exam') {
                    891: 
1.27      www       892:         &Apache::response::scored_response($partid,$id);
1.10      www       893: 
                    894:     } elsif ($target eq 'grade'
                    895:          && &Apache::response::submitted()
                    896:          && $Apache::lonhomework::type ne 'exam') {
                    897:         my ($response,%coords)=&get_answer_from_form_fields($internalid);
                    898:         $Apache::lonhomework::results{"resource.$partid.$id.submission"}=$response;
1.12      www       899:         my %previous=&Apache::response::check_for_previous($response,$partid,$id);
                    900: #
                    901: # Actually grade
                    902: #
1.18      www       903:         my $xmin=&Apache::lonxml::get_param('xmin',$parstack,$safeeval);
                    904:         $xmin=(defined($xmin)?$xmin:-10);
                    905:         my $xmax=&Apache::lonxml::get_param('xmax',$parstack,$safeeval);
                    906:         $xmax=(defined($xmax)?$xmax:10);
1.25      www       907:         my $ymin=&Apache::lonxml::get_param('ymin',$parstack,$safeeval);
                    908:         $ymin=(defined($ymin)?$ymin:-10);
                    909:         my $ymax=&Apache::lonxml::get_param('ymax',$parstack,$safeeval);
                    910:         $ymax=(defined($ymax)?$ymax:10);
1.27      www       911: 
1.24      www       912:         my $ad='';
1.30      www       913:         undef  %Apache::functionplotresponse::functionplotrulelabels;
                    914:         $Apache::functionplotresponse::functionplotrulelabels{'start'}=400;
                    915:         $Apache::functionplotresponse::functionplotrulelabels{'end'}=0;
1.18      www       916:         if (&populate_arrays($internalid,$xmin,$xmax) eq 'no_func') {
1.21      www       917:            $ad='NOT_FUNCTION';
1.18      www       918:         } else {
1.24      www       919: # We have a function that we can actually grade, go through the spline rules.
1.25      www       920:            foreach my $rule (@Apache::functionplotresponse::functionplotrules) {
1.33    ! www       921:               unless (&functionplotrulecheck($rule,$xmin,$xmax,$ymin,$ymax)) {
1.24      www       922:                  $ad='INCORRECT';
                    923:                  last;
                    924:               }
                    925:            }
                    926: # If it's not wrong, it's correct 
                    927:            unless ($ad) { $ad='EXACT_ANS' };
1.18      www       928:         }
1.20      www       929: 
1.12      www       930: #
                    931: # Store grading info
                    932: #
                    933:         $Apache::lonhomework::results{"resource.$partid.$id.awarddetail"}=$ad;
                    934:         &Apache::response::handle_previous(\%previous,$ad);
1.10      www       935:    } elsif ($target eq 'web') {
1.6       www       936: # Now is the time to render all of the stored splines
                    937:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
                    938:         $result.=&generate_spline($internalid,$label);
                    939:      }
1.5       www       940: # close the init script
1.3       www       941:      $result.=&end_init_script();
1.17      www       942: # register all splines in this response 
                    943:      $result.='<input type="hidden" name="HWVAL_AllSplines_'.$internalid.'" value="'.
                    944:                  join(',',keys(%Apache::functionplotresponse::splineorder)).'" />'."\n";
                    945:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
                    946:         $result.='<input type="hidden" name="HWVAL_SplineOrder_'.$internalid.'_'.$label.'" value="'.
                    947:                  $Apache::functionplotresponse::splineorder{$label}.'" />'."\n";
                    948:      }
1.9       www       949: # generate the input fields
                    950:      $result.=$Apache::functionplotresponse::inputfields;
1.5       www       951: # actually start the <applet>-tag
1.3       www       952:      $result.=&geogebra_startcode($internalid);
1.5       www       953: # load the spline bytecode
1.3       www       954:      $result.=&geogebra_spline_program();
1.5       www       955: # set default parameters
1.3       www       956:      $result.=&geogebra_default_parameters($internalid);
1.5       www       957: # close the <applet>-tag
1.1       www       958:      $result.=&geogebra_endcode();
                    959:   }
                    960:   return $result;
                    961: }
                    962: 
                    963: 1;
                    964: 
                    965: __END__
                    966:  
                    967: =head1 NAME
                    968: 
                    969: Apache::functionplotresponse.pm;
                    970: 
                    971: =head1 SYNOPSIS
                    972: 
                    973: Handles tags associated with accepting function plots.
                    974: 
                    975: This is part of the LearningOnline Network with CAPA project
                    976: described at http://www.lon-capa.org.
                    977: 
                    978: =head1 HANDLER SUBROUTINE
                    979: 
                    980: start_functionplotresponse()
                    981: 
                    982: =head1 OTHER SUBROUTINES
                    983: 
                    984: =over
                    985: 
                    986: =item end_functionplotresponse()
                    987: 
                    988: =back
                    989: 
                    990: =cut

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