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

1.1       www         1: # LearningOnline Network with CAPA
1.70      www         2: # Functionplot responses
1.1       www         3: #
1.91    ! www         4: # $Id: functionplotresponse.pm,v 1.90 2011/12/10 18:10:56 www Exp $
1.1       www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
                     28: 
                     29: package Apache::functionplotresponse;
                     30: use strict;
                     31: use Apache::response();
                     32: use Apache::lonlocal;
                     33: use Apache::lonnet;
1.65      www        34: use Apache::run;
1.85      www        35: use LONCAPA;
1.36      www        36:  
1.1       www        37: BEGIN {
1.37      www        38:   &Apache::lonxml::register('Apache::functionplotresponse',('functionplotresponse','backgroundplot','spline',
1.85      www        39:                                                             'plotobject','plotvector',
                     40:                                                             'functionplotvectorrule','functionplotvectorsumrule',
                     41:                                                             'functionplotcustomrule',
1.37      www        42:                                                             'functionplotrule','functionplotruleset',
                     43:                                                             'functionplotelements'));
1.1       www        44: }
                     45: 
1.5       www        46: #
                     47: # There can be a number of applets on a page, each called ggbApplet_$id, 
                     48: # where $id is the "_"-concatenated part and responseid
                     49: #
                     50: 
1.1       www        51: sub geogebra_startcode {
1.88      www        52:     my ($id,$width,$height)=@_;
                     53:     $width=int(1.*$width);
                     54:     $height=int(1.*$height);
                     55:     unless ($width) { $width=700; }
                     56:     unless ($height) { $height=400; }
1.1       www        57:     return (<<ENDSTARTCODE);
1.3       www        58: <applet name="ggbApplet_$id" code="geogebra.GeoGebraApplet" archive="geogebra.jar"
1.88      www        59:          codebase="/adm/geogebra/"  width="$width" height="$height" MAYSCRIPT>
1.1       www        60:        <param name="java_arguments" value="-Xmx512m -Djnlp.packEnabled=true"/>
                     61: ENDSTARTCODE
                     62: }
                     63: 
                     64: sub geogebra_endcode {
1.2       www        65:     return &Apache::lonhtmlcommon::java_not_enabled()."</applet>\n";
                     66: }
                     67: 
1.5       www        68: #
                     69: # This is the internal GeoGebra bytecode which defines the spline functions
                     70: #
1.2       www        71: sub geogebra_spline_program {
                     72:     return (<<ENDSPLINEPROGRAM);
1.57      www        73: <param name="ggbBase64" value="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"/>
1.2       www        74: ENDSPLINEPROGRAM
                     75: }
                     76: 
1.5       www        77: #
                     78: # The standard set of parameters inside <applet>
                     79: #
1.2       www        80: sub geogebra_default_parameters {
1.3       www        81:    my ($id)=@_;
1.2       www        82:    return(<<ENDDEFAULTPARAMETERS);
                     83:         <param name="image" value="/adm/lonIcons/lonanim.gif"  />
                     84:         <param name="boxborder" value="false"  />
                     85:         <param name="centerimage" value="true"  />
1.62      www        86: 	<param name="cache_archive" value="geogebra.jar, geogebra_main.jar, geogebra_gui.jar, geogebra_cas.jar, geogebra_export.jar, geogebra_algos.jar, geogebra_javascript.jar, geogebra_properties.jar, jlatexmath.jar, jlm_cyrillic.jar, jlm_greek.jar" />
1.69      www        87: 	<param name="cache_version" value="4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0" />
1.2       www        88:         <param name="framePossible" value="false" />
                     89: 
                     90:         <param name="showResetIcon" value="false" />
                     91:         <param name="showAnimationButton" value="false" />
                     92:         <param name="enableRightClick" value="false" />
                     93:         <param name="errorDialogsActive" value="true" />
                     94:         <param name="enableLabelDrags" value="false" />
                     95:         <param name="showMenuBar" value="false" />
                     96:         <param name="showToolBar" value="false" />
                     97:         <param name="showToolBarHelp" value="false" />
                     98:         <param name="showAlgebraInput" value="false" />
                     99:         <param name="enableShiftDragZoom" value="false" />
                    100:         <param name="allowRescaling" value="false" />
                    101:         <param name="enableLabelDrags" value="false" />
1.3       www       102:         <param name="ggbOnInitParam" value="applet_$id" />
1.2       www       103: ENDDEFAULTPARAMETERS
1.1       www       104: }
                    105: 
1.5       www       106: #
                    107: # This subroutine is called by LON-CAPA at </problem>
                    108: # Each applet on the page will call function ggbOnInit when it is done loading
                    109: # This function in turn will call the respective function registered by start_init_script
                    110: # Which one of the registered functions is called is determined by ggbOnInitParam, which GeoGebra passes to ggbOnInit
                    111: #
                    112: 
1.3       www       113: sub init_script {
1.16      www       114:    if ($#Apache::functionplotresponse::callscripts>=0) {
                    115:       my $script='';
                    116:       foreach my $id (@Apache::functionplotresponse::callscripts) {
                    117:           $script.="if (param=='applet_$id') { loaded_$id=true; }\n";
                    118:       }
                    119:       $script.="if (".join(' && ',map { "loaded_$_" } (@Apache::functionplotresponse::callscripts)).
1.52      www       120:                ") { setTimeout('ggbInitAll()',200) }";
1.16      www       121:       my $calls=join("\n",map { "ggbInit_$_();" } (@Apache::functionplotresponse::callscripts)); 
1.3       www       122:       return (<<ENDGGBINIT);
                    123: <script type="text/javascript">
                    124: // <![CDATA[
1.16      www       125: // Function that each applet will call when loaded
                    126: // It will pass "its" parameter
                    127: // Set flags for when an applet is loaded, wait till all are loaded, and then some
1.3       www       128: function ggbOnInit(param) {
1.16      www       129: $script
                    130: }
                    131: function ggbInitAll() {
1.17      www       132: $calls
1.3       www       133: }
                    134: // ]]>
                    135: </script>
                    136: ENDGGBINIT
                    137:    }
                    138: }
                    139: 
1.5       www       140: #
                    141: # Each Geogebra applet is supposed to call this when parameters change
1.10      www       142: # Changes the hidden fields on the web page
1.5       www       143: #
                    144: sub update_script {
                    145:     my ($id)=@_;
                    146:     return (<<ENDUPDATESCRIPT);
                    147: <script type="text/javascript">
                    148: // <![CDATA[
                    149: function updatePointCoordinates_$id(coordinateName) {
                    150:             var x = document.ggbApplet_$id.getXcoord(coordinateName);
                    151:             var y = document.ggbApplet_$id.getYcoord(coordinateName);
1.9       www       152:             document.lonhomework.elements["HWVAL_$id\_" + coordinateName + "_x"].value = x;
                    153:             document.lonhomework.elements["HWVAL_$id\_" + coordinateName + "_y"].value = y;
1.5       www       154:         }
                    155: // ]]>
                    156: </script>
                    157: ENDUPDATESCRIPT
                    158: }
                    159: 
                    160: #
                    161: # Register the above update-handler for a variable
                    162: #
                    163: 
                    164: sub update_register {
                    165:    my ($id,$variable)=@_;
1.6       www       166:    return "document.ggbApplet_$id.registerObjectUpdateListener('$variable','updatePointCoordinates_$id');\n";
                    167: }
                    168: 
                    169: #
1.40      www       170: # Set a point coordinate variable
1.6       www       171: #
1.40      www       172: sub set_point_coordinate {
1.48      www       173:    my ($id,$variable,$x,$y,$fixed)=@_;
                    174:    my $mult=($fixed?'a*':'');
1.68      www       175: # Get rid of wild exponents, make sure it's a number
                    176:    $x=1.*$x;
                    177:    $y=1.*$y;
                    178: # GeoGebra does not understand "E"
                    179:    $x=~s/[e|E]/\*10\^/;
                    180:    $x=~s/\+//;
                    181:    $y=~s/[e|E]/\*10\^/;
                    182:    $y=~s/\+//;
1.6       www       183:    return (<<ENDSETVARIABLE);
1.48      www       184: document.ggbApplet_$id.evalCommand("a=1");
                    185: document.ggbApplet_$id.evalCommand("$variable=$mult($x,$y)");
1.40      www       186: document.ggbApplet_$id.setLabelVisible("$variable",false);
1.6       www       187: ENDSETVARIABLE
                    188: }
                    189: 
                    190: #
1.40      www       191: # Set a slope coordinate variable
                    192: #
                    193: sub set_slope_coordinate {
1.48      www       194:    my ($id,$variable,$xrel,$yrel,$xmin,$xmax,$ymin,$ymax,$pointname,$fixed)=@_;
1.40      www       195:    my $xvariable=$variable.'x';
                    196:    my $yvariable=$variable.'y';
                    197:    my $domain=$xmax-$xmin;
                    198:    my $range=$ymax-$ymin;
                    199:    my $xinterval=$domain/100.;
                    200:    my $yinterval=$range/200.;
1.48      www       201:    my $mult=($fixed?'a*':'');
1.40      www       202:    return (<<ENDSETSVARIABLE);
1.48      www       203: document.ggbApplet_$id.evalCommand("a=1");
1.51      www       204: document.ggbApplet_$id.evalCommand("$xvariable=Slider[$xinterval,$domain,$xinterval]");
1.40      www       205: document.ggbApplet_$id.setVisible("$xvariable", false);
                    206: document.ggbApplet_$id.evalCommand("$xvariable=$xrel");
                    207: document.ggbApplet_$id.evalCommand("$yvariable=Slider[-$range,$range,$yinterval]");
                    208: document.ggbApplet_$id.setVisible("$yvariable", false);
                    209: document.ggbApplet_$id.evalCommand("$yvariable=$yrel");
1.48      www       210: document.ggbApplet_$id.evalCommand("$variable=$mult($xvariable+x($pointname),$yvariable+y($pointname))");
1.40      www       211: document.ggbApplet_$id.setLabelVisible("$variable", false);
                    212: ENDSETSVARIABLE
                    213: }
                    214: 
                    215: #
1.9       www       216: # Input field name for a coordinate variable
                    217: #
                    218: 
                    219: sub field_name {
                    220:     my ($id,$variable,$name)=@_;
                    221:     return "HWVAL_$id\_$variable\_$name";
                    222: }
                    223: 
                    224: #
                    225: # Generate an input field for a coordinate variable
                    226: #
                    227: 
                    228: sub generate_input_field {
                    229:     my ($id,$variable,$x,$y)=@_;
                    230:     $Apache::functionplotresponse::inputfields.=
                    231:        "<input type='hidden' name='".&field_name($id,$variable,'x')."' value='$x' />\n".
                    232:        "<input type='hidden' name='".&field_name($id,$variable,'y')."' value='$y' />\n";
                    233: }
                    234: 
                    235: #
1.40      www       236: # Initialize a new point coordinate variable at set a listener on it
1.6       www       237: #
1.40      www       238: sub new_point_coordinate {
1.48      www       239:     my ($id,$variable,$x,$y,$fixed)=@_;
1.11      www       240:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'x')})) {
1.10      www       241:        $x=$Apache::functionplotresponse::previous{&field_name($id,$variable,'x')};
                    242:     }
1.11      www       243:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'y')})) {
1.10      www       244:        $y=$Apache::functionplotresponse::previous{&field_name($id,$variable,'y')};
                    245:     }
1.9       www       246:     &generate_input_field($id,$variable,$x,$y);
1.48      www       247:     return &set_point_coordinate($id,$variable,$x,$y,$fixed).&update_register($id,$variable);
1.40      www       248: }
                    249: 
                    250: #
                    251: # Initialize a new slope coordinate variable at set a listener on it
                    252: #
                    253: sub new_slope_coordinate {
1.48      www       254:     my ($id,$variable,$x,$y,$pointname,$xp,$yp,$xmin,$xmax,$ymin,$ymax,$fixed)=@_;
1.40      www       255: #
                    256: # $variable: name of the slope point
                    257: # $x, $y: coordinates of the slope point
                    258: # $pointname: name of the associated point point
                    259: # $xp $yp: coordinates of the point point
                    260: #
                    261:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'x')})) {
                    262:        $x=$Apache::functionplotresponse::previous{&field_name($id,$variable,'x')};
                    263:     }
                    264:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'y')})) {
                    265:        $y=$Apache::functionplotresponse::previous{&field_name($id,$variable,'y')};
                    266:     }
                    267:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$pointname,'x')})) {
                    268:        $xp=$Apache::functionplotresponse::previous{&field_name($id,$pointname,'x')};
                    269:     }
                    270:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$pointname,'y')})) {
                    271:        $yp=$Apache::functionplotresponse::previous{&field_name($id,$pointname,'y')};
                    272:     }
                    273: 
                    274:     &generate_input_field($id,$variable,$x,$y);
                    275:     my $xrel=$x-$xp;
                    276:     my $yrel=$y-$yp;
1.48      www       277:     return &set_slope_coordinate($id,$variable,$xrel,$yrel,$xmin,$xmax,$ymin,$ymax,$pointname,$fixed).&update_register($id,$variable);
1.5       www       278: }
                    279: 
                    280: #
                    281: # This registers the init-function call for ggbOnInit, which LON-CAPA will place at </problem>
                    282: # It then starts the right headers
                    283: #
1.3       www       284: sub start_init_script {
                    285:     my ($id)=@_;
1.16      www       286: # Add id to the list of ggbInit_$id functions that need to be called
                    287:     push(@Apache::functionplotresponse::callscripts,$id);
1.5       www       288: # ... and open this function
1.3       www       289:     return (<<ENDSTARTINIT);
                    290: <script type="text/javascript">
                    291: // <![CDATA[
1.5       www       292: // variable that will eventually be passed back to the server
                    293: var coordinateMap_$id = [];
1.16      www       294: // flag for not loaded yet
                    295: var loaded_$id=false;
1.5       www       296: // Init-function for applet
1.3       www       297: function ggbInit_$id() {
                    298: ENDSTARTINIT
                    299: }
                    300: 
1.5       www       301: #
                    302: # This sets the axes inside ggbInit_$id
                    303: #
                    304: 
1.4       www       305: sub axes_script {
                    306:     my ($id,$xmin,$xmax,$ymin,$ymax,$xvisible,$yvisible,$gvisible)=@_;
                    307:     return (<<ENDAXESSCRIPT);
                    308:             // changes (xmin, xmax, ymin, ymax)
                    309:             document.ggbApplet_$id.setCoordSystem($xmin,$xmax,$ymin,$ymax);
                    310: 
                    311:             // makes the (x,y) axis (in)visible
                    312:             document.ggbApplet_$id.setAxesVisible($xvisible,$yvisible);
                    313:             // makes the grid (in)visible
                    314:             document.ggbApplet_$id.setGridVisible($gvisible);
                    315: ENDAXESSCRIPT
                    316: }
                    317: 
1.14      www       318: sub axes_label {
1.45      www       319:     my ($id,$xmin,$xmax,$ymin,$ymax,$xlabel,$ylabel)=@_;
1.14      www       320:     unless ($xlabel || $ylabel) { return ''; }
                    321:     my $return='document.ggbApplet_'.$id.'.evalCommand("topRight=Corner[3]");';
                    322:     if ($xlabel) {
1.45      www       323:       if (($ymin<0) && ($ymax>0)) {
1.14      www       324:        $return.=(<<ENDXAXISLABELSCRIPT);
                    325: document.ggbApplet_$id.evalCommand("Xlabel=(x(topRight)-AxisStepX[],AxisStepY[]/6)");
                    326: document.ggbApplet_$id.setVisible("Xlabel",false);
                    327: document.ggbApplet_$id.evalCommand("Text[\\"$xlabel\\", Xlabel]");
                    328: ENDXAXISLABELSCRIPT
1.45      www       329:       } else {
                    330:        $return.=(<<ENDXOFFAXISLABEL);
                    331: document.ggbApplet_$id.evalCommand("LowerRight=Corner[2]");
                    332: document.ggbApplet_$id.evalCommand("Text[\\"$xlabel\\", (x(LowerRight) - AxisStepX[], y(LowerRight) + AxisStepY[] / 2)]");
                    333: ENDXOFFAXISLABEL
                    334:       }
1.14      www       335:     }
                    336:     if ($ylabel) {
1.45      www       337:       if (($xmin<0) && ($xmax>0)) {
1.14      www       338:        $return.=(<<ENDYAXISLABELSCRIPT);
                    339: document.ggbApplet_$id.evalCommand("Ylabel=(AxisStepX[]/6,y(topRight)-AxisStepY[]/3)");
                    340: document.ggbApplet_$id.setVisible("Ylabel",false);
                    341: document.ggbApplet_$id.evalCommand("Text[\\"$ylabel\\", Ylabel]");
                    342: ENDYAXISLABELSCRIPT
1.45      www       343:       } else {
                    344:        $return.=(<<ENDYOFFAXISLABEL);
                    345: document.ggbApplet_$id.evalCommand("UpperLeft=Corner[4]");
                    346: document.ggbApplet_$id.evalCommand("Text[\\"$ylabel\\", (x(UpperLeft) + AxisStepX[] / 5, y(UpperLeft) - AxisStepY[] / 1.8)]");
                    347: ENDYOFFAXISLABEL
                    348:       }
1.14      www       349:     }
                    350:     return $return;
                    351: }
                    352: 
1.58      www       353: #
                    354: # Subroutine to produce background and answer plots
                    355: #
                    356: 
1.4       www       357: sub plot_script {
1.47      www       358:    my ($id,$function,$fixed,$label,$color,$xmin,$xmax,$thickness)=@_;
1.41      www       359:    $label=~s/\W//g;
                    360:    if (($label) && ($label!~/^[A-Za-z]/)) {
                    361:       $label='C'.$label;
                    362:    }
                    363:    my $visible=0;
                    364:    if ($label) {
                    365:       $visible="1";
                    366:    } else {
                    367:       $Apache::functionplotresponse::counter++;
                    368:       $label='C'.$Apache::functionplotresponse::counter;
                    369:    }
1.46      www       370:    my $rc=0;
                    371:    my $gc=0;
                    372:    my $bc=0;
                    373:    if ($color) {
                    374:       my ($rh,$gh,$bh)=($color=~/(..)(..)(..)/);
                    375:       $rc=hex($rh);
                    376:       $gc=hex($gh);
                    377:       $bc=hex($bh);
                    378:    }
1.6       www       379:    if ($fixed) {
1.43      www       380:       return "document.ggbApplet_$id.evalCommand('$label=Function[$function,$xmin,$xmax]');\n".
1.46      www       381:              ($visible?'':"document.ggbApplet_$id.setLabelVisible('$label', false);\n").
1.47      www       382:              ($color?"document.ggbApplet_$id.setColor('$label',$rc,$gc,$bc);\n":'').
                    383:              ($thickness?"document.ggbApplet_$id.setLineThickness('$label',$thickness);\n":'');
1.6       www       384:    } else {
1.46      www       385:        return "document.ggbApplet_$id.evalCommand('y=$function');\n";
1.6       www       386:    }
1.4       www       387: }
                    388: 
1.5       www       389: #
1.70      www       390: # Subroutine to produce objects
                    391: #
                    392: 
                    393: sub plotobject_script {
                    394:    my ($id,$label,$x,$y)=@_;
                    395:    unless ($label) {
                    396:       $Apache::functionplotresponse::counter++;
                    397:       $label='O'.$Apache::functionplotresponse::counter;
                    398:    }
1.77      www       399:    &generate_input_field($id,$label,$x,$y);
1.70      www       400:    return "document.ggbApplet_$id.evalCommand('a=1');\n".
                    401:           "document.ggbApplet_$id.setVisible('a', false);\n".
                    402:           "document.ggbApplet_$id.setLabelVisible('a', false);\n".
                    403:           "document.ggbApplet_$id.evalCommand('$label=a*($x,$y)');\n".
                    404:           "document.ggbApplet_$id.setVisible('$label', true);\n".
                    405:           "document.ggbApplet_$id.setLabelVisible('$label', true);\n";
                    406: }
                    407: 
                    408: #
                    409: # Subroutine to produce vectors
                    410: #
                    411: 
                    412: sub plotvector_script {
1.72      www       413:    my ($id,$label,$xs,$ys,$xe,$ye,$xmin,$xmax)=@_;
1.70      www       414:    unless ($label) {
                    415:       $Apache::functionplotresponse::counter++;
                    416:       $label='V'.$Apache::functionplotresponse::counter;
                    417:    }
1.71      www       418:    my $startlabel=$label.'Start';
                    419:    my $endlabel=$label.'End';
                    420:    my $pointlabel=$label.'Point';
1.72      www       421:    my $pointx=2.*($xmax-$xmin)+$xmax;
1.71      www       422:    my $anglelabel=$label.'Angle';
1.74      www       423:    return 
                    424:        &new_point_coordinate($id,$startlabel,$xs,$ys,0).
                    425:        &new_point_coordinate($id,$endlabel,$xe,$ye,0).
                    426:        (<<ENDVECTOR);
1.71      www       427: document.ggbApplet_$id.evalCommand("$label=Vector[$startlabel,$endlabel]");
                    428: document.ggbApplet_$id.setLabelVisible("$label",true);
                    429: document.ggbApplet_$id.setLineThickness("$label",8);
1.72      www       430: document.ggbApplet_$id.evalCommand("$pointlabel=($pointx,y($startlabel))");
                    431: document.ggbApplet_$id.evalCommand("$anglelabel=Angle[$pointlabel,$startlabel,$endlabel]");
                    432: document.ggbApplet_$id.setLabelVisible("$anglelabel",true);
                    433: document.ggbApplet_$id.setLabelStyle("$anglelabel",VALUE=2);
1.70      www       434: ENDVECTOR
                    435: }
                    436: 
                    437: #
1.58      www       438: # Answer spline display
                    439: # 
                    440: # points: x,y,slope_x,slope_y
                    441: 
                    442: sub answer_spline_script {
                    443:    my ($id,@points)=@_;
                    444:    my $order=int(($#points+1)/4);
                    445:    if ($order<2) { $order=2; }
                    446:    if ($order>8) { $order=8; }
                    447:    $Apache::functionplotresponse::counter++;
1.60      www       448:    my $label='CSpline'.$Apache::functionplotresponse::counter;
1.59      www       449:    my $output='document.ggbApplet_'.$id.'.evalCommand("'.$label.'=Spline'.$order.'[';
                    450:    for (my $i=0;$i<=$#points;$i+=4) {
                    451:       $output.="($points[$i],$points[$i+1]),($points[$i+2],$points[$i+3]),";
                    452:    }
                    453:    $output=~s/\,$//;
                    454:    $output.=']");'."\n";
                    455:    for (my $i=2; $i<2*$order; $i+=2) {
1.61      www       456:        $output.='document.ggbApplet_'.$id.'.setColor("'.$label.'_'.($i>=10?'{':'').$i.($i>=10?'}':'').'",0,170,0);'."\n";
1.59      www       457:    }
1.60      www       458:    for (my $i=1; $i<2*$order; $i+=2) {
1.61      www       459:        $output.='document.ggbApplet_'.$id.'.setVisible("'.$label.'_'.($i>=10?'{':'').$i.($i>=10?'}':'').'",false);'."\n";
1.60      www       460:    }
                    461: 
1.59      www       462:    return $output;
1.58      www       463: }
                    464: 
                    465: #
1.7       www       466: # Subroutine that generates code for spline $label based on stored information
1.6       www       467: #
                    468: 
                    469: sub generate_spline {
1.48      www       470:    my ($id,$label,$xmin,$xmax,$ymin,$ymax,$fixed)=@_;
1.6       www       471:    my $result='';
1.7       www       472:    my $order=$Apache::functionplotresponse::splineorder{$label};
                    473:    my $x=$Apache::functionplotresponse::splineinitx{$label};
                    474:    my $y=$Apache::functionplotresponse::splineinity{$label};
                    475:    my $sx=$Apache::functionplotresponse::splinescalex{$label};
                    476:    my $sy=$Apache::functionplotresponse::splinescaley{$label};
                    477:    my @coords=();
                    478:    foreach my $i (1..$order) {
1.48      www       479:        $result.=&new_point_coordinate($id,$label.'P'.$i,$x,$y,$fixed);
1.40      www       480:        my $xp=$x;
1.8       www       481:        $x+=$sx/(2.*($order-1));
1.7       www       482:        push(@coords,$label.'P'.$i);
1.48      www       483:        $result.=&new_slope_coordinate($id,$label.'S'.$i,$x,$y+$sy,$label.'P'.$i,$xp,$y,$xmin,$xmax,$ymin,$ymax,$fixed);
1.8       www       484:        $x+=$sx/(2.*($order-1));
1.7       www       485:        push(@coords,$label.'S'.$i);
                    486:    }
                    487:    $result.='document.ggbApplet_'.$id.'.evalCommand("Spline'.$order.'['.join(',',@coords).']");'."\n";
1.6       www       488:    return $result;
                    489: }
1.70      www       490: 
                    491: #
                    492: # Object
                    493: #
                    494: 
                    495: sub start_plotobject {
                    496:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    497:    my $result='';
                    498:    my $internalid = $Apache::inputtags::part.'_'.$Apache::inputtags::response[-1];
                    499:    my $x=&Apache::lonxml::get_param('x',$parstack,$safeeval);
                    500:    my $y=&Apache::lonxml::get_param('y',$parstack,$safeeval);
                    501:    my $label=&Apache::lonxml::get_param('label',$parstack,$safeeval);
                    502:    $label=~s/\W//gs;
                    503:    $label=ucfirst($label);
                    504:    unless ($label) { $label="NewObject"; }
                    505:    if ($target eq 'web') {
                    506:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-3);
                    507:       unless (defined($x)) { $x=$xmin; }
                    508:       unless (defined($y)) { $y=$ymin; }
                    509:       $result.=&plotobject_script($internalid,$label,$x,$y);
                    510:    } elsif ($target eq 'edit') {
                    511:         $result=&Apache::edit::tag_start($target,$token,'Plot Object').
                    512:              &Apache::edit::text_arg('Label on Plot:','label',
                    513:                                      $token,'16').
                    514:              &Apache::edit::text_arg('x:','x',
                    515:                                      $token,'8').
                    516:              &Apache::edit::text_arg('y:','y',
                    517:                                      $token,'8').
                    518:              &Apache::edit::end_row();
                    519:   } elsif ($target eq 'modified') {
1.76      www       520:     $env{'form.'.&Apache::edit::html_element_name('label')}=ucfirst($env{'form.'.&Apache::edit::html_element_name('label')});
1.70      www       521:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,$safeeval,'label','x','y');
                    522:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
                    523:   }
                    524:   return $result;
                    525: }
                    526: 
                    527: sub end_plotobject {
                    528:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    529:    my $result='';
                    530:    if ($target eq 'edit') {
                    531:        $result=&Apache::edit::end_table();
                    532:    }
                    533:    return $result;
                    534: }
                    535: 
1.71      www       536: #
                    537: # Vector
                    538: #
                    539: 
                    540: sub start_plotvector {
                    541:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    542:    my $result='';
                    543:    my $internalid = $Apache::inputtags::part.'_'.$Apache::inputtags::response[-1];
                    544:    my $tailx=&Apache::lonxml::get_param('tailx',$parstack,$safeeval);
                    545:    my $taily=&Apache::lonxml::get_param('taily',$parstack,$safeeval);
                    546:    my $tipx=&Apache::lonxml::get_param('tipx',$parstack,$safeeval);
                    547:    my $tipy=&Apache::lonxml::get_param('tipy',$parstack,$safeeval);
                    548: 
                    549:    my $label=&Apache::lonxml::get_param('label',$parstack,$safeeval);
                    550:    $label=~s/\W//gs;
                    551:    $label=ucfirst($label);
                    552:    unless ($label) { $label="NewVector"; }
                    553:    if ($target eq 'web') {
                    554:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-3);
                    555:       unless (defined($tailx)) { $tailx=$xmin; }
                    556:       unless (defined($taily)) { $taily=$ymin; }
                    557:       unless (defined($tipx)) { $tipx=$xmin; }
                    558:       unless (defined($tipy)) { $tipy=$ymin; }
1.72      www       559:       $result.=&plotvector_script($internalid,$label,$tailx,$taily,$tipx,$tipy,$xmin,$xmax);
1.71      www       560:    } elsif ($target eq 'edit') {
                    561:         $result=&Apache::edit::tag_start($target,$token,'Plot Vector').
                    562:              &Apache::edit::text_arg('Label on Plot:','label',
                    563:                                      $token,'16').
                    564:              &Apache::edit::text_arg('Tail x:','tailx',
                    565:                                      $token,'8').
                    566:              &Apache::edit::text_arg('Tail y:','taily',
                    567:                                      $token,'8').
                    568:              &Apache::edit::text_arg('Tip x:','tipx',
                    569:                                      $token,'8').
                    570:              &Apache::edit::text_arg('Tip y:','tipy',
                    571:                                      $token,'8').
                    572: 
                    573:              &Apache::edit::end_row();
                    574:   } elsif ($target eq 'modified') {
1.76      www       575:     $env{'form.'.&Apache::edit::html_element_name('label')}=ucfirst($env{'form.'.&Apache::edit::html_element_name('label')});
1.71      www       576:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,$safeeval,'label','tailx','taily','tipx','tipy');
                    577:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
                    578:   }
                    579:   return $result;
                    580: }
                    581: 
                    582: sub end_plotvector {
                    583:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    584:    my $result='';
                    585:    if ($target eq 'edit') {
                    586:        $result=&Apache::edit::end_table();
                    587:    }
                    588:    return $result;
                    589: }
                    590: 
                    591: 
1.70      www       592: 
1.6       www       593: #
                    594: # <backgroundplot function="..." fixed="yes/no" />
1.5       www       595: #
1.4       www       596: sub start_backgroundplot {
                    597:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    598:    my $result='';
                    599:    my $internalid = $Apache::inputtags::part.'_'.$Apache::inputtags::response[-1];
                    600:    my $function=&Apache::lonxml::get_param('function',$parstack,$safeeval);
1.47      www       601:    my $xinitial=&Apache::lonxml::get_param('xinitial',$parstack,$safeeval);
                    602:    my $xfinal=&Apache::lonxml::get_param('xfinal',$parstack,$safeeval);
1.41      www       603:    my $label=&Apache::lonxml::get_param('label',$parstack,$safeeval);
1.46      www       604:    my $color=&Apache::lonxml::get_param('color',$parstack,$safeeval);
                    605:    $color=~s/[^a-fA-F0-9]//gs;
                    606:    unless (length($color)==6) { $color=''; }
1.6       www       607:    my $fixed=(&Apache::lonxml::get_param('fixed',$parstack,$safeeval)=~/on|true|yes|1/i?1:0);
                    608:  
1.4       www       609:    unless ($function) { $function="0"; }
                    610:    if ($target eq 'web') {
1.41      www       611:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-3);
1.47      www       612:       unless (defined($xinitial)) { $xinitial=$xmin; }
                    613:       unless (defined($xfinal)) { $xfinal=$xmax; }
                    614:       $result.=&plot_script($internalid,$function,$fixed,$label,$color,$xinitial,$xfinal);
1.13      www       615:    } elsif ($target eq 'edit') {
                    616:         $result=&Apache::edit::tag_start($target,$token,'Background Function Plot').
                    617:              &Apache::edit::text_arg('Function:','function',
                    618:                                      $token,'16').
1.47      www       619:              &Apache::edit::text_arg('Initial x-value (optional):','xinitial',
                    620:                                      $token,'8').
                    621:              &Apache::edit::text_arg('Final x-value (optional):','xfinal',
                    622:                                      $token,'8').
1.41      www       623:              &Apache::edit::text_arg('Label on Plot:','label',
                    624:                                      $token,'8').
1.46      www       625:              &Apache::edit::text_arg('Color (hex code):','color',
                    626:                                      $token,'8').
1.13      www       627:              &Apache::edit::select_arg('Fixed location:','fixed',
                    628:                                   ['yes','no'],$token).
                    629:              &Apache::edit::end_row();
                    630:   } elsif ($target eq 'modified') {
                    631:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.47      www       632:                                                  $safeeval,'function','label','xinitial','xfinal','color','fixed');
1.13      www       633:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
                    634:   }
                    635:   return $result;
1.4       www       636: }
                    637: 
                    638: sub end_backgroundplot {
1.13      www       639:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    640:    my $result='';
                    641:    if ($target eq 'edit') {
                    642:        $result=&Apache::edit::end_table();
                    643:    }
                    644:    return $result;
1.6       www       645: }
                    646: 
                    647: #
1.25      www       648: # <functionplotrule ... />
1.12      www       649: #
1.25      www       650: sub start_functionplotrule {
1.12      www       651:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    652:    my $result='';
1.24      www       653:    my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
                    654:    $Apache::functionplotresponse::counter++;
                    655:    if ($label=~/\W/) {
1.25      www       656:       &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
1.24      www       657:    }
                    658:    $label=~s/\W//gs;
                    659:    unless ($label) {
                    660:       $label='R'.$Apache::functionplotresponse::counter;
                    661:    } else {
                    662:       $label='R'.$label;
                    663:    }
                    664: 
                    665:    if ($target eq 'grade') {
                    666: # Simply remember - in order - for later
1.25      www       667:       my $beginninglabel=&Apache::lonxml::get_param('xinitiallabel',$parstack,$safeeval);
                    668:       my $endinglabel=&Apache::lonxml::get_param('xfinallabel',$parstack,$safeeval);
1.24      www       669:       if (($beginninglabel=~/\W/) || ($endinglabel=~/W/)) {
1.25      www       670:           &Apache::lonxml::warning(&mt('Rule labels must be alphanumeric.'));
1.24      www       671:       }
                    672:       $beginninglabel=~s/\W//gs;
                    673:       $endinglabel=~s/\W//gs;
                    674:       my $relationship=&Apache::lonxml::get_param('relationship',$parstack,$safeeval);
                    675:       $relationship=~s/\W//gs;
                    676:       $relationship=lc($relationship);
                    677:       unless ($relationship=~/^(eq|ge|gt|le|lt|ne)$/) {
1.25      www       678:           &Apache::lonxml::warning(&mt('Rule relationship not defined.'));
1.24      www       679:           $relationship='eq';
                    680:       }
1.35      www       681:       my $derivative=&Apache::lonxml::get_param('derivativeorder',$parstack,$safeeval);
1.42      www       682:       unless (($derivative==-1) || ($derivative==0) || ($derivative==1) || ($derivative==2)) {
1.25      www       683:          &Apache::lonxml::warning(&mt('Rule derivative not defined.'));
1.24      www       684:          $derivative=0;
                    685:       }
1.25      www       686:       push(@Apache::functionplotresponse::functionplotrules,join(':',(
1.24      www       687:            $label,
                    688:            $derivative,
1.25      www       689:            &Apache::lonxml::get_param('xinitial',$parstack,$safeeval),
1.24      www       690:            $beginninglabel,
1.25      www       691:            &Apache::lonxml::get_param('xfinal',$parstack,$safeeval),
1.24      www       692:            $endinglabel,
1.35      www       693:            &Apache::lonxml::get_param('minimumlength',$parstack,$safeeval),
                    694:            &Apache::lonxml::get_param('maximumlength',$parstack,$safeeval),
1.24      www       695:            $relationship,
1.33      www       696:            &Apache::lonxml::get_param('value',$parstack,$safeeval),
                    697:            &Apache::lonxml::get_param('percenterror',$parstack,$safeeval)
1.24      www       698:           )));
                    699:    } elsif ($target eq 'edit') {
1.75      www       700:         $result=&Apache::edit::tag_start($target,$token,'Function Plot Graph Rule').
1.36      www       701:              &Apache::edit::text_arg('Index/Name:','index',
                    702:                                      $token,'10').'&nbsp;'.
1.35      www       703:              &Apache::edit::select_arg(&mt('Function:'),'derivativeorder',
1.29      www       704:                                   [['0','Function itself'],
                    705:                                    ['1','First derivative'],
1.42      www       706:                                    ['2','Second derivative'],
                    707:                                    ['-1','Integral']],$token).'<br />'.
1.44      www       708:              &Apache::edit::text_arg('Initial x-value:','xinitial',
1.35      www       709:                                       $token,'8').
1.44      www       710:              &Apache::edit::select_or_text_arg('Initial x-value label:','xinitiallabel',
                    711:                                                [['start','Start of Plot'],
                    712:                                                 ['end','End of Plot']],$token,'8').'<br />'.
1.30      www       713: 
1.44      www       714:              &Apache::edit::text_arg('Final x-value (optional):','xfinal',
1.35      www       715:                                       $token,'8').
1.44      www       716:              &Apache::edit::select_or_text_arg('Final x-value label (optional):','xfinallabel',
1.32      www       717:                                                [['end','End of Plot']],$token,'8').'<br />'.
1.44      www       718:              &Apache::edit::text_arg('Minimum length for range (optional):','minimumlength',
1.35      www       719:                                      $token,'8').
1.44      www       720:              &Apache::edit::text_arg('Maximum length for range (optional):','maximumlength',
1.35      www       721:                                      $token,'8').'<br />'.
1.38      www       722:              &Apache::edit::select_or_text_arg(&mt('Relationship:'),'relationship',
1.29      www       723:                                   [['eq','equal'],
                    724:                                    ['ne','not equal'],
                    725:                                    ['ge','greater than or equal'],
                    726:                                    ['gt','greater than'],
                    727:                                    ['lt','less than'],
                    728:                                    ['le','less than or equal']],$token).
                    729:              $result.= &Apache::edit::select_or_text_arg('Value:','value',
1.65      www       730:                                                [['undef','not defined']],$token,'30').
1.29      www       731:              &Apache::edit::text_arg('Percent error:','percenterror',
1.35      www       732:                                      $token,'8').
1.29      www       733:              &Apache::edit::end_row();
                    734:   } elsif ($target eq 'modified') {
1.54      www       735:     if (($env{'form.'.&Apache::edit::html_element_name('xinitial')} ne '') && ($env{'form.'.&Apache::edit::html_element_name('xinitiallabel')} eq 'start')) {
1.53      www       736:        $env{'form.'.&Apache::edit::html_element_name('xinitiallabel')}='';
                    737:     }
1.54      www       738:     if (($env{'form.'.&Apache::edit::html_element_name('xfinal')} ne '') && ($env{'form.'.&Apache::edit::html_element_name('xfinallabel')} eq 'end')) {
1.53      www       739:        $env{'form.'.&Apache::edit::html_element_name('xfinallabel')}='';
                    740:     }
1.29      www       741:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.35      www       742:                                                  $safeeval,'index','derivativeorder',
                    743:                                                            'xinitial','xinitiallabel','xfinal','xfinallabel',
                    744:                                                            'minimumlength','maximumlength',
                    745:                                                            'relationship','value','percenterror');
1.29      www       746:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
1.13      www       747:    }
1.12      www       748:    return $result;
                    749: }
                    750: 
1.25      www       751: sub end_functionplotrule {
1.13      www       752:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    753:    my $result='';
                    754:    if ($target eq 'edit') {
                    755:        $result=&Apache::edit::end_table();
                    756:    }
                    757:    return $result;
1.12      www       758: }
                    759: 
                    760: 
                    761: #
1.75      www       762: # <functionplotvectorrule ... />
                    763: #
                    764: sub start_functionplotvectorrule {
                    765:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    766:    my $result='';
                    767:    my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
                    768:    $Apache::functionplotresponse::counter++;
                    769:    if ($label=~/\W/) {
                    770:       &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
                    771:    }
                    772:    $label=~s/\W//gs;
                    773:    unless ($label) {
1.79      www       774:       $label='R'.$Apache::functionplotresponse::counter;
1.75      www       775:    } else {
1.79      www       776:       $label='R'.$label;
1.75      www       777:    }
                    778: 
                    779:    if ($target eq 'grade') {
                    780: # Simply remember - in order - for later
1.77      www       781: 
                    782:       my $id=$Apache::inputtags::response[-1];
                    783:       my $partid=$Apache::inputtags::part;
                    784:       my $internalid = $partid.'_'.$id;
                    785: 
1.75      www       786:       my $vector=&Apache::lonxml::get_param('vector',$parstack,$safeeval);
                    787:       $vector=~s/\W//gs;
                    788:       $vector=ucfirst($vector);
1.76      www       789: 
1.75      www       790:       push(@Apache::functionplotresponse::functionplotvectorrules,join(':',(
                    791:            $label,
1.76      www       792:            'vector',
1.77      www       793:            $internalid,
1.75      www       794:            $vector,
1.87      www       795:            &Apache::lonxml::get_param('attachpoint',$parstack,$safeeval),
                    796:            &Apache::lonxml::get_param('notattachpoint',$parstack,$safeeval),
                    797:            &Apache::lonxml::get_param('tailpoint',$parstack,$safeeval),
                    798:            &Apache::lonxml::get_param('tippoint',$parstack,$safeeval),
                    799:            &Apache::lonxml::get_param('nottailpoint',$parstack,$safeeval),
                    800:            &Apache::lonxml::get_param('nottippoint',$parstack,$safeeval),
1.75      www       801:            &Apache::lonxml::get_param('length',$parstack,$safeeval),
                    802:            &Apache::lonxml::get_param('angle',$parstack,$safeeval),
1.79      www       803:            &Apache::lonxml::get_param('lengtherror',$parstack,$safeeval),
                    804:            &Apache::lonxml::get_param('angleerror',$parstack,$safeeval),
1.75      www       805:           )));
                    806:    } elsif ($target eq 'edit') {
                    807:         $result=&Apache::edit::tag_start($target,$token,'Function Plot Vector Rule').
                    808:              &Apache::edit::text_arg('Index/Name:','index',
                    809:                                      $token,'10').'&nbsp;'.
                    810:              &Apache::edit::text_arg('Vector:','vector',
                    811:                                       $token,'16').'<br />'.
1.76      www       812:              &Apache::edit::text_arg('Attached to object:','attachpoint',
                    813:                                       $token,'16').
                    814:              &Apache::edit::text_arg('Not attached to object:','notattachpoint',
                    815:                                       $token,'16').'<br />'.
1.75      www       816:              &Apache::edit::text_arg('Tail attached to object:','tailpoint',
                    817:                                       $token,'16').
                    818:              &Apache::edit::text_arg('Tip attached to object:','tippoint',
                    819:                                       $token,'16').
                    820:              &Apache::edit::text_arg('Tail not attached to object:','nottailpoint',
                    821:                                       $token,'16').
                    822:              &Apache::edit::text_arg('Tip not attached to object:','nottippoint',
                    823:                                       $token,'16').'<br />'.
                    824:              &Apache::edit::text_arg('Length:','length',
1.84      www       825:                                      $token,'30').
                    826:              &Apache::edit::text_arg('Absolute error length:','lengtherror',
                    827:                                      $token,'8').'<br />'.
1.75      www       828:              &Apache::edit::text_arg('Angle:','angle',
1.84      www       829:                                      $token,'30').
1.79      www       830:              &Apache::edit::text_arg('Absolute error angle:','angleerror',
1.75      www       831:                                      $token,'8').
                    832:              &Apache::edit::end_row();
                    833:   } elsif ($target eq 'modified') {
1.76      www       834:     $env{'form.'.&Apache::edit::html_element_name('vector')}=ucfirst($env{'form.'.&Apache::edit::html_element_name('vector')});
1.75      www       835:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.76      www       836:                                                  $safeeval,'index','vector','attachpoint','notattachpoint',
1.75      www       837:                                                            'tailpoint','tippoint','nottailpoint','nottipoint',
                    838:                                                            'length','angle',
1.79      www       839:                                                            'lengtherror','angleerror');
1.75      www       840:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
                    841:    }
                    842:    return $result;
                    843: }
                    844: 
                    845: sub end_functionplotvectorrule {
                    846:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    847:    my $result='';
                    848:    if ($target eq 'edit') {
                    849:        $result=&Apache::edit::end_table();
                    850:    }
                    851:    return $result;
                    852: }
                    853: 
1.76      www       854: #
                    855: # <functionplotvectorsumrule ... />
                    856: #
                    857: sub start_functionplotvectorsumrule {
                    858:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    859:    my $result='';
                    860:    my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
                    861:    $Apache::functionplotresponse::counter++;
                    862:    if ($label=~/\W/) {
                    863:       &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
                    864:    }
                    865:    $label=~s/\W//gs;
                    866:    unless ($label) {
1.79      www       867:       $label='R'.$Apache::functionplotresponse::counter;
1.76      www       868:    } else {
1.79      www       869:       $label='R'.$label;
1.76      www       870:    }
                    871:    if ($target eq 'grade') {
                    872: # Simply remember - in order - for later
1.77      www       873:       my $id=$Apache::inputtags::response[-1];
                    874:       my $partid=$Apache::inputtags::part;
                    875:       my $internalid = $partid.'_'.$id;
1.82      www       876:       my $vectors=&Apache::lonxml::get_param('vectors',$parstack,$safeeval);
1.76      www       877:       push(@Apache::functionplotresponse::functionplotvectorrules,join(':',(
                    878:            $label,
                    879:            'sum',
1.77      www       880:            $internalid,
1.82      www       881:            $vectors,
1.76      www       882:            &Apache::lonxml::get_param('length',$parstack,$safeeval),
                    883:            &Apache::lonxml::get_param('angle',$parstack,$safeeval),
1.80      www       884:            &Apache::lonxml::get_param('lengtherror',$parstack,$safeeval),
1.79      www       885:            &Apache::lonxml::get_param('angleerror',$parstack,$safeeval),
1.76      www       886:           )));
                    887:    } elsif ($target eq 'edit') {
                    888:         $result=&Apache::edit::tag_start($target,$token,'Function Plot Vector Sum Rule').
                    889:              &Apache::edit::text_arg('Index/Name:','index',
                    890:                                      $token,'10').'&nbsp;'.
1.82      www       891:              &Apache::edit::text_arg('Comma-separated list of vectors:','vectors',
                    892:                                       $token,'30').'<br />'.
1.76      www       893:              &Apache::edit::text_arg('Sum vector length:','length',
1.84      www       894:                                      $token,'30').
                    895:              &Apache::edit::text_arg('Absolute error length:','lengtherror',
                    896:                                      $token,'8').'<br />'.
1.76      www       897:              &Apache::edit::text_arg('Sum vector angle:','angle',
1.84      www       898:                                      $token,'30').
                    899:              &Apache::edit::text_arg('Absolute error angle:','angleerror',
1.76      www       900:                                      $token,'8').
                    901:              &Apache::edit::end_row();
1.85      www       902:    } elsif ($target eq 'modified') {
                    903:       my $constructtag=&Apache::edit::get_new_args($token,$parstack,
                    904:                                                    $safeeval,'index','vectors',
                    905:                                                              'length','angle',
                    906:                                                              'lengtherror','angleerror');
                    907:       if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
1.76      www       908:    }
                    909:    return $result;
                    910: }
1.75      www       911: 
1.76      www       912: sub end_functionplotvectorsumrule {
                    913:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    914:    my $result='';
                    915:    if ($target eq 'edit') {
                    916:        $result=&Apache::edit::end_table();
                    917:    }
                    918:    return $result;
                    919: }
1.75      www       920: 
                    921: #
1.85      www       922: # <functionplotcustom ... />
                    923: #
                    924: sub start_functionplotcustomrule {
                    925:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    926:    my $result='';
                    927:    my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
                    928:    $Apache::functionplotresponse::counter++;
                    929:    if ($label=~/\W/) {
                    930:       &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
                    931:    }
                    932:    $label=~s/\W//gs;
                    933:    unless ($label) {
                    934:       $label='R'.$Apache::functionplotresponse::counter;
                    935:    } else {
                    936:       $label='R'.$label;
                    937:    }
                    938:    &Apache::lonxml::register('Apache::response',('answer'));
                    939:    if ($target eq 'edit') {
                    940:         $result=&Apache::edit::tag_start($target,$token,'Function Plot Custom Rule').
                    941:              &Apache::edit::text_arg('Index/Name:','index',$token,'10').
                    942:              &Apache::edit::end_row();
                    943:   } elsif ($target eq 'modified') {
                    944:       my $constructtag=&Apache::edit::get_new_args($token,$parstack,$safeeval,'index');
                    945:       if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
                    946:    }
                    947:    return $result;
                    948: }
                    949: 
                    950: sub end_functionplotcustomrule {
                    951:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    952:    my $result='';
                    953:    if ($target eq 'edit') {
                    954:       $result=&Apache::edit::end_table();
                    955:    } elsif ($target eq 'grade') {
                    956: # Simply remember - in order - for later
                    957:       my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
                    958:       $Apache::functionplotresponse::counter++;
                    959:       if ($label=~/\W/) {
                    960:          &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
                    961:       }
                    962:       $label=~s/\W//gs;
                    963:       unless ($label) {
                    964:          $label='R'.$Apache::functionplotresponse::counter;
                    965:       } else {
                    966:          $label='R'.$label;
                    967:       }
                    968:       push(@Apache::functionplotresponse::functionplotvectorrules,join(':',(
                    969:            $label,
                    970:            'custom',
                    971:            &escape($Apache::response::custom_answer[-1])
                    972:           )));
                    973:    }
                    974:    &Apache::lonxml::deregister('Apache::response',('answer'));
                    975:    return $result;
                    976: }
                    977: 
                    978: 
                    979: 
                    980: #
1.23      www       981: # <spline index="..." order="1,2,3,4" initx="..." inity="..." scalex="..." scaley="..." />
1.6       www       982: #
                    983: # Unfortunately, GeoGebra seems to want all splines after everything else, so we need to store them
                    984: #
                    985: sub start_spline {
                    986:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1.13      www       987:    my $result='';
                    988:    if ($target eq 'web') {
1.23      www       989:       my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
1.13      www       990:       $Apache::functionplotresponse::counter++;
                    991:       if ($label=~/\W/) {
1.23      www       992:          &Apache::lonxml::warning(&mt('Spline indices should only contain alphanumeric characters.'));
1.13      www       993:       }
                    994:       $label=~s/\W//gs;
1.23      www       995:       unless ($label) { 
                    996:          $label='S'.$Apache::functionplotresponse::counter; 
                    997:       } else {
                    998:          $label='S'.$label;
                    999:       }
1.13      www      1000:       if ($Apache::functionplotresponse::splineorder{$label}) {
1.23      www      1001:          &Apache::lonxml::error(&mt('Spline indices must be unique.'));
1.13      www      1002:       }
                   1003: 
                   1004:       my $order=&Apache::lonxml::get_param('order',$parstack,$safeeval);
                   1005:       if ($order<2) { $order=2; }
                   1006:       if ($order>8) { $order=8; }
                   1007:       $Apache::functionplotresponse::splineorder{$label}=$order;
                   1008: 
                   1009:       my $x=&Apache::lonxml::get_param('initx',$parstack,$safeeval);
                   1010:       unless ($x) { $x=0; }
                   1011:       $Apache::functionplotresponse::splineinitx{$label}=$x;
                   1012: 
                   1013:       my $y=&Apache::lonxml::get_param('inity',$parstack,$safeeval);
                   1014:       unless ($y) { $y=0; }
                   1015:       $Apache::functionplotresponse::splineinity{$label}=$y;
                   1016: 
                   1017:       my $sx=&Apache::lonxml::get_param('scalex',$parstack,$safeeval);
                   1018:       unless ($sx) { $sx=$order; }
                   1019:       $Apache::functionplotresponse::splinescalex{$label}=$sx;
                   1020: 
                   1021:       my $sy=&Apache::lonxml::get_param('scaley',$parstack,$safeeval);
                   1022:       unless ($sy) { $sy=2; }
                   1023:       $Apache::functionplotresponse::splinescaley{$label}=$sy;
                   1024:    } elsif ($target eq 'edit') {
                   1025:         $result=&Apache::edit::tag_start($target,$token,'Spline').
1.23      www      1026:              &Apache::edit::text_arg('Index:','index',
1.14      www      1027:                                      $token,'4').'&nbsp;'.
1.13      www      1028:              &Apache::edit::select_arg('Order:','order',
1.44      www      1029:                                   ['2','3','4','5','6','7','8'],$token).'&nbsp;'.
1.13      www      1030:              &Apache::edit::text_arg('Initial x-value:','initx',
1.14      www      1031:                                      $token,'4').'&nbsp;'.
1.13      www      1032:              &Apache::edit::text_arg('Initial y-value:','inity',
1.14      www      1033:                                      $token,'4').'&nbsp;'.
1.13      www      1034:              &Apache::edit::text_arg('Scale x:','scalex',
1.14      www      1035:                                      $token,'4').'&nbsp;'.
1.13      www      1036:              &Apache::edit::text_arg('Scale y:','scaley',
                   1037:                                      $token,'4').
                   1038:              &Apache::edit::end_row();
                   1039:   } elsif ($target eq 'modified') {
                   1040:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.23      www      1041:                                                  $safeeval,'index','order','initx','inity',
1.13      www      1042:                                                            'scalex','scaley');
                   1043:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
                   1044:   }
                   1045:   return $result;
1.6       www      1046: }
                   1047: 
                   1048: sub end_spline {
1.13      www      1049:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1050:    my $result='';
                   1051:    if ($target eq 'edit') {
                   1052:        $result=&Apache::edit::end_table();
                   1053:    }
                   1054:    return $result;
1.4       www      1055: }
                   1056:  
1.3       www      1057: sub end_init_script {
                   1058:     return (<<ENDENDINIT);
                   1059: }
                   1060: // ]]>
                   1061: </script>
                   1062: ENDENDINIT
                   1063: }
                   1064: 
1.10      www      1065: #
                   1066: # Storing and restoring spline coordinates from part answers
                   1067: #
                   1068: sub decode_previous_answer {
                   1069:    my ($answer)=@_;
                   1070:    foreach my $coordinate (split(/\,/,$answer)) {
                   1071:       my ($key,$value)=split(/\=/,$coordinate);
                   1072:       $Apache::functionplotresponse::previous{$key}=$value;
                   1073:    }
                   1074: }
                   1075: 
                   1076: sub get_answer_from_form_fields {
                   1077:    my ($id)=@_;
                   1078:    my $answer='';
                   1079:    my %coords=();
                   1080:    foreach my $field (keys(%env)) {
                   1081:       if ($field=~/^form\.HWVAL\_$id/) {
                   1082:          $field=~/^form\.(.*)$/;
                   1083:          $coords{$1}=$env{$field};
                   1084:       }
                   1085:    }
                   1086:    $answer=join(',',map { $_.'='.$coords{$_} } (sort(keys(%coords))));
                   1087:    return ($answer,%coords);
                   1088: }
                   1089: 
1.15      www      1090: #
                   1091: # The following functions calculate the cubic-hermite splines server-side
                   1092: #
                   1093: 
                   1094: sub cubic_hermite {
                   1095:    my ($t,$p1,$s1,$p2,$s2)=@_;
1.42      www      1096:    return (2.*$t*$t*$t-3.*$t*$t+1.)*$p1 + 3.*($t*$t*$t-2.*$t*$t+$t)*($s1-$p1)+
                   1097:           (-2.*$t*$t*$t+3.*$t*$t)  *$p2 + 3.*($t*$t*$t-$t*$t)      *($s2-$p2);
1.15      www      1098: }
                   1099: 
                   1100: #
                   1101: # d/dt(...)
                   1102: # 
                   1103: 
                   1104: sub ddt_cubic_hermite {
                   1105:    my ($t,$p1,$s1,$p2,$s2)=@_;
1.42      www      1106:    return (6.*$t*$t-6.*$t) *$p1 + 3.*(3.*$t*$t-4.*$t+1.)*($s1-$p1)+
                   1107:           (-6.*$t*$t+6.*$t)*$p2 + 3.*(3.*$t*$t-2.*$t)   *($s2-$p2);
1.15      www      1108: }
                   1109: 
                   1110: #
                   1111: # d^2/dt^2(...)
                   1112: #
                   1113: 
                   1114: sub d2dt2_cubic_hermite {
                   1115:    my ($t,$p1,$s1,$p2,$s2)=@_;
1.42      www      1116:    return (12.*$t-6.) *$p1 + 3.*(6.*$t-4.)*($s1-$p1)+
                   1117:           (-12.*$t+6.)*$p2 + 3.*(6.*$t-2.)*($s2-$p2);
1.15      www      1118: }
                   1119: 
                   1120: #
1.18      www      1121: # Array index calculation
                   1122: #
                   1123: sub array_index {
                   1124:    my ($xmin,$xmax,$x)=@_;
1.38      www      1125:    if ($x ne '') {
                   1126:       return int(($x-$xmin)/($xmax-$xmin)*400.+0.5);
                   1127:    } else {
                   1128:       return undef;
                   1129:    }
1.20      www      1130: }
                   1131: 
                   1132: #
1.18      www      1133: # Populate the arrays
                   1134: #
                   1135: 
                   1136: sub populate_arrays {
1.64      www      1137:     my ($id,$xmin,$xmax,$ymin,$ymax)=@_;
1.26      www      1138:     for (my $i=0; $i<=400; $i++) {
1.35      www      1139:        $Apache::functionplotresponse::actualxval[$i]=undef;
1.19      www      1140:        $Apache::functionplotresponse::func[$i]=undef;
1.22      www      1141:        $Apache::functionplotresponse::dfuncdx[$i]=undef;
1.19      www      1142:        $Apache::functionplotresponse::d2funcd2x[$i]=undef;
1.18      www      1143:     }
1.19      www      1144:     unless ($xmax>$xmin) { return 'no_func'; }
1.18      www      1145: # Run over all splines in response
                   1146:     foreach my $label (split(/\,/,$env{"form.HWVAL_AllSplines_$id"})) {
1.19      www      1147:         my $xiold=-1;
1.18      www      1148: # Run over all points in spline
1.19      www      1149:         for (my $i=1; $i<$env{"form.HWVAL_SplineOrder_".$id."_".$label}; $i++) {
1.18      www      1150:             my $ni=$i+1;
                   1151:             my @xparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_x'},
                   1152:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_x'},
                   1153:                         $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_x'},
                   1154:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_x'});
                   1155:             my @yparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_y'},
                   1156:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_y'},
                   1157:                         $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_y'},
                   1158:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_y'});
                   1159: # Run in small steps over spline parameter
1.26      www      1160:             for (my $t=0; $t<=1; $t+=0.0001) {
1.35      www      1161:                 my $xreal=&cubic_hermite($t,@xparms);
                   1162:                 my $xi=&array_index($xmin,$xmax,$xreal);
1.19      www      1163:                 if ($xi<$xiold) { return 'no_func'; }
1.26      www      1164:                 if (($xi>$xiold) && ($xi>=0) && ($xi<=400)) {
1.18      www      1165:                    $xiold=$xi;
1.35      www      1166:                    $Apache::functionplotresponse::actualxval[$xi]=$xreal;
1.22      www      1167: # Function value
1.30      www      1168:                    my $funcval=&cubic_hermite($t,@yparms);
1.64      www      1169: 
                   1170: # Do we already have a value for this point, and is it different from the new one?
                   1171:                    if ((defined($Apache::functionplotresponse::func[$xi])) &&
                   1172:                        (abs($Apache::functionplotresponse::func[$xi]-$funcval)>($ymax-$ymin)/100.)) { 
                   1173:                        return 'no_func'; 
                   1174:                    }
                   1175: # Okay, remember the new point
1.30      www      1176:                    $Apache::functionplotresponse::func[$xi]=$funcval;
1.64      www      1177: 
1.30      www      1178:                    if (defined($funcval)) {
                   1179:                       if ($xi<$Apache::functionplotresponse::functionplotrulelabels{'start'}) {
                   1180:                          $Apache::functionplotresponse::functionplotrulelabels{'start'}=$xi;
                   1181:                       }
                   1182:                       if ($xi>$Apache::functionplotresponse::functionplotrulelabels{'end'}) {
                   1183:                          $Apache::functionplotresponse::functionplotrulelabels{'end'}=$xi;
                   1184:                       }
                   1185:                    }
1.28      www      1186: # Chain rule
1.22      www      1187: # dy/dx=dy/dt/(dx/dt)
                   1188:                    my $dxdt=&ddt_cubic_hermite($t,@xparms);
                   1189:                    if ($dxdt) {
                   1190:                       $Apache::functionplotresponse::dfuncdx[$xi]=&ddt_cubic_hermite($t,@yparms)/$dxdt;
1.34      www      1191: # Second derivative
1.28      www      1192:                       $Apache::functionplotresponse::d2funcdx2[$xi]=
1.34      www      1193:                          ($dxdt*&d2dt2_cubic_hermite($t,@yparms)-&ddt_cubic_hermite($t,@yparms)*&d2dt2_cubic_hermite($t,@xparms))/
                   1194:                          ($dxdt*$dxdt*$dxdt);
1.22      www      1195:                    }
1.18      www      1196:                 }
                   1197:             }
                   1198:         }
                   1199:     }
                   1200: }
                   1201: 
                   1202: #
1.37      www      1203: # Implementation of <functionplotresponse>
1.15      www      1204: #
                   1205: 
1.1       www      1206: sub start_functionplotresponse {
                   1207:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1208:   my $result='';
1.6       www      1209: # To remember the splines - somehow, they need to come last
                   1210:   undef %Apache::functionplotresponse::splineorder;
                   1211:   undef %Apache::functionplotresponse::splineinitx;
                   1212:   undef %Apache::functionplotresponse::splineinity;
                   1213:   undef %Apache::functionplotresponse::splinescalex;
                   1214:   undef %Apache::functionplotresponse::splinescaley;
1.10      www      1215: # Remember input fields, etc
                   1216:   undef %Apache::functionplotresponse::previous;
1.9       www      1217:   $Apache::functionplotresponse::inputfields='';
1.6       www      1218:   $Apache::functionplotresponse::counter=0;
1.24      www      1219: # Remember rules
1.25      www      1220:   undef @Apache::functionplotresponse::functionplotrules;
1.75      www      1221:   undef @Apache::functionplotresponse::functionplotvectorrules;
1.37      www      1222: # Remember failed rules
                   1223:   if ($target eq 'grade') {
                   1224:      undef @Apache::functionplotresponse::failedrules;
                   1225:   }
                   1226: # Delete previous awards
                   1227:   undef $Apache::functionplotresponse::awarddetail;
1.10      www      1228: # Part and ID
                   1229:   my $partid=$Apache::inputtags::part;
                   1230:   my $id=&Apache::response::start_response($parstack,$safeeval);
1.6       www      1231: # Internal ID to mark the applet and its coordinates
1.10      www      1232:   my $internalid = $partid.'_'.$id;
                   1233: # Previous answer
                   1234:   &decode_previous_answer($Apache::lonhomework::history{"resource.$partid.$id.submission"});
                   1235: 
1.6       www      1236: # Parameters of <functionplotresponse>
1.41      www      1237:   my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval);
1.6       www      1238:   my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
                   1239:   my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
                   1240:   my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
1.14      www      1241:   my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval);
                   1242:   my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval);
1.12      www      1243:   if ($target eq 'edit') {
                   1244:     $result.=&Apache::edit::start_table($token)
                   1245:        .'<tr><td><span class="LC_nobreak">'.&mt('Function Plot Question').'</span></td>'
                   1246:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
1.37      www      1247:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'
1.50      www      1248:        .&Apache::edit::insertlist($target,$token).'&nbsp;&nbsp;&nbsp;'
                   1249:        .&Apache::loncommon::help_open_topic('Function_Plot_Response_Question','Function Plot Responses')
1.12      www      1250:        .'</span></td>'
                   1251:        ."<td>&nbsp;"
                   1252:        .&Apache::edit::end_row()
                   1253:        .&Apache::edit::start_spanning_row()
                   1254:        ."\n";
1.88      www      1255:     $result.=&Apache::edit::text_arg('Width (pixels):','width',
                   1256:                                      $token,'6').'&nbsp;'.
                   1257:              &Apache::edit::text_arg('Height (pixels):','height',
                   1258:                                      $token,'6').'<br />'.
                   1259:              &Apache::edit::text_arg('Label x-axis:','xlabel',
1.14      www      1260:                                      $token,'6').'&nbsp;'.
                   1261:              &Apache::edit::text_arg('Minimum x-value:','xmin',
                   1262:                                      $token,'4').'&nbsp;'.
1.12      www      1263:              &Apache::edit::text_arg('Maximum x-value:','xmax',
1.14      www      1264:                                      $token,'4').'&nbsp;'.
1.12      www      1265:              &Apache::edit::select_arg('x-axis visible:','xaxisvisible',
1.32      www      1266:                                   ['yes','no'],$token).'<br />'.
1.14      www      1267:              &Apache::edit::text_arg('Label y-axis:','ylabel',
                   1268:                                      $token,'6').'&nbsp;'.
1.12      www      1269:              &Apache::edit::text_arg('Minimum y-value:','ymin',
1.14      www      1270:                                      $token,'4').'&nbsp;'.
1.12      www      1271:              &Apache::edit::text_arg('Maximum y-value:','ymax',
1.14      www      1272:                                      $token,'4').'&nbsp;'.
1.12      www      1273:              &Apache::edit::select_arg('y-axis visible:','yaxisvisible',
1.32      www      1274:                                   ['yes','no'],$token).'<br />'.
1.12      www      1275:              &Apache::edit::select_arg('Grid visible:','gridvisible',
1.47      www      1276:                                   ['yes','no'],$token).'<br />'.
1.58      www      1277:              &Apache::edit::text_arg('Background plot(s) for answer (function(x):xmin:xmax,function(x):xmin:xmax,x1:y1:sx1:sy1:x2:y2:sx2:sy2,...):',
1.63      raeburn  1278:                                          'answerdisplay',$token,'50').
1.12      www      1279:              &Apache::edit::end_row().&Apache::edit::start_spanning_row();
                   1280:   } elsif ($target eq 'modified') {
                   1281:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.88      www      1282:                                                  $safeeval,'width','height','xlabel','xmin','xmax','ylabel','ymin','ymax',
1.47      www      1283:                                                            'xaxisvisible','yaxisvisible','gridvisible','answerdisplay');
1.12      www      1284:     if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
1.3       www      1285: 
1.12      www      1286:   } elsif ($target eq 'meta') {
1.10      www      1287:        $result=&Apache::response::meta_package_write('functionplotresponse');
1.35      www      1288:   } elsif (($target eq 'answer') &&
                   1289:             ($env{'form.answer_output_mode'} ne 'tex') &&
                   1290:             ($Apache::lonhomework::viewgrades == 'F')) {
                   1291:       my (undef,undef,$udom,$uname)=&Apache::lonnet::whichuser();
                   1292:       $uname =~s/\W//g;
                   1293:       $udom  =~s/\W//g;
                   1294:       my $function_name =
                   1295:                 join('_','LONCAPA_scriptvars',$uname,$udom,
                   1296:                      $env{'form.counter'},$Apache::lonxml::curdepth);
1.89      www      1297:       &Apache::lonxml::add_script_result(
1.90      www      1298:           &Apache::loncommon::modal_adhoc_window($function_name,700,500,
                   1299:              '<pre>'.$Apache::functionplotresponse::ruleslog.'</pre>',
                   1300:               &mt('Rules Log'))."<br />");
                   1301:   }
1.1       www      1302:   return $result;
                   1303: }
                   1304: 
1.25      www      1305: sub compare_rel {
1.26      www      1306:    my ($relationship,$value,$realval,$tol)=@_;
1.36      www      1307: # is the real value undefined?
1.26      www      1308:    unless (defined($realval)) {
1.36      www      1309: # the real value is not defined
1.26      www      1310:       if ($relationship eq 'eq') {
                   1311:          if ($value eq 'undef') {
                   1312:             return 1;
                   1313:          } else {
                   1314:             return 0;
                   1315:          }
                   1316:       } elsif ($relationship eq 'ne') {
                   1317:          if ($value eq 'undef') {
                   1318:             return 0;
                   1319:          } else {
                   1320:             return 1;
                   1321:          }
                   1322:       } else {
                   1323:          return 0;
                   1324:       }
                   1325:    }
                   1326: 
1.36      www      1327: # is the expected value undefined?
                   1328:    if ($value eq 'undef') {
                   1329: # but by now we know that the real value is defined
                   1330:       return 0;
                   1331:    }
                   1332: 
                   1333: # both are defined.
1.26      www      1334:    if ($relationship eq 'gt') {
                   1335:       return ($realval>$value);
                   1336:    } elsif ($relationship eq 'ge') {
                   1337:       return ($realval>$value-$tol);
                   1338:    } elsif ($relationship eq 'lt') {
                   1339:       return ($realval<$value);
                   1340:    } elsif ($relationship eq 'le') {
                   1341:       return ($realval<$value+$tol);
                   1342:    } elsif ($relationship eq 'ne') {
                   1343:       return (abs($value-$realval)>$tol);
                   1344:    } else {
                   1345:       return (abs($value-$realval)<$tol);
                   1346:    }
1.25      www      1347:    return 0;
                   1348: }
                   1349: 
1.35      www      1350: sub addlog {
                   1351:    my ($text)=@_;
1.67      www      1352:    $text=~s/\'/\\\'/g;
1.35      www      1353:    $Apache::functionplotresponse::ruleslog.=$text.'<br />';
                   1354: }
                   1355: 
                   1356: sub actualval {
                   1357:    my ($i,$xmin,$xmax)=@_;
                   1358:    return $xmin+$i/400.*($xmax-$xmin);
                   1359: }
1.65      www      1360: 
1.66      www      1361: sub fpr_val {
                   1362:    my ($arg)=@_;
                   1363:    return &actualval($Apache::functionplotresponse::functionplotrulelabels{$arg},
                   1364:                      $Apache::functionplotresponse::fpr_xmin,
                   1365:                      $Apache::functionplotresponse::fpr_xmax);
                   1366: }
                   1367: 
1.65      www      1368: sub fpr_f {
                   1369:    my ($arg)=@_;
                   1370:    return $Apache::functionplotresponse::func[&array_index($Apache::functionplotresponse::fpr_xmin,
                   1371:                                                            $Apache::functionplotresponse::fpr_xmax,
                   1372:                                                            $arg)];
                   1373: }
                   1374: 
                   1375: sub fpr_dfdx {
                   1376:    my ($arg)=@_;
                   1377:    return $Apache::functionplotresponse::dfuncdx[&array_index($Apache::functionplotresponse::fpr_xmin,
                   1378:                                                               $Apache::functionplotresponse::fpr_xmax,
                   1379:                                                               $arg)];
                   1380: }
                   1381: 
                   1382: sub fpr_d2fdx2 {
                   1383:    my ($arg)=@_;
                   1384:    return $Apache::functionplotresponse::d2funcdx2[&array_index($Apache::functionplotresponse::fpr_xmin,
                   1385:                                                                 $Apache::functionplotresponse::fpr_xmax,
                   1386:                                                                 $arg)];
                   1387: }
1.77      www      1388: 
1.84      www      1389: sub fpr_vectorcoords {
                   1390:    my ($arg)=@_;
                   1391:    $arg=~s/\W//gs;
                   1392:    $arg=ucfirst($arg);
                   1393:    my $id=$Apache::inputtags::response[-1];
                   1394:    my $partid=$Apache::inputtags::part;
                   1395:    my $internalid = $partid.'_'.$id;
                   1396:    return ($env{'form.HWVAL_'.$internalid.'_'.$arg.'Start_x'},
                   1397:            $env{'form.HWVAL_'.$internalid.'_'.$arg.'End_x'},
                   1398:            $env{'form.HWVAL_'.$internalid.'_'.$arg.'Start_y'},
                   1399:            $env{'form.HWVAL_'.$internalid.'_'.$arg.'End_y'});
                   1400: }
                   1401: 
                   1402: sub fpr_objectcoords {
                   1403:    my ($arg)=@_;
                   1404:    $arg=~s/\W//gs;
                   1405:    $arg=ucfirst($arg);
                   1406:    my $id=$Apache::inputtags::response[-1];
                   1407:    my $partid=$Apache::inputtags::part;
                   1408:    my $internalid = $partid.'_'.$id;
                   1409:    return ($env{'form.HWVAL_'.$internalid.'_'.$arg.'_x'},
                   1410:            $env{'form.HWVAL_'.$internalid.'_'.$arg.'_y'});
                   1411: }
                   1412: 
                   1413: sub fpr_vectorlength {
                   1414:    my ($arg)=@_;
                   1415:    my ($xs,$xe,$ys,$ye)=&fpr_vectorcoords($arg);
                   1416:    return sqrt(($xe-$xs)*($xe-$xs)+($ye-$ys)*($ye-$ys));
                   1417: }
                   1418: 
                   1419: sub fpr_vectorangle {
                   1420:    my ($arg)=@_;
                   1421:    my ($xs,$xe,$ys,$ye)=&fpr_vectorcoords($arg);
                   1422:    my $angle=57.2957795*atan2(($ye-$ys),($xe-$xs));
                   1423:    if ($angle<0) { $angle=360+$angle; }
                   1424:    return $angle;
                   1425: }
1.77      www      1426: 
                   1427: sub vectorcoords {
                   1428:    my ($id,$label)=@_;
                   1429:    return ($env{'form.HWVAL_'.$id.'_'.$label.'Start_x'},
                   1430:            $env{'form.HWVAL_'.$id.'_'.$label.'End_x'},
                   1431:            $env{'form.HWVAL_'.$id.'_'.$label.'Start_y'},
                   1432:            $env{'form.HWVAL_'.$id.'_'.$label.'End_y'});
                   1433: }
                   1434: 
                   1435: sub objectcoords {
                   1436:    my ($id,$label)=@_;
                   1437:    return ($env{'form.HWVAL_'.$id.'_'.$label.'_x'},
                   1438:            $env{'form.HWVAL_'.$id.'_'.$label.'_y'});
                   1439: }
1.81      www      1440: 
                   1441: sub attached {
1.87      www      1442:    my ($id,$vector,$objects,$xmin,$xmax,$ymin,$ymax)=@_;
1.81      www      1443:    my ($xs,$xe,$ys,$ye)=&vectorcoords($id,$vector);
                   1444:    my $tolx=($xmax-$xmin)/100.;
                   1445:    my $toly=($ymax-$ymin)/100.;
                   1446:    my $tail=0;
                   1447:    my $tip=0;
1.87      www      1448:    foreach my $obj (split(/\s*\,\s*/,$objects)) {
                   1449:       $obj=~s/\W//g;
                   1450:       unless ($obj) { next; }
                   1451:       $obj=ucfirst($obj);
                   1452:       my ($xo,$yo)=&objectcoords($id,$obj);
                   1453:       &addlog("Proximity $vector ($xs,$ys)-($xe,$ye) to $obj ($xo,$yo)");
                   1454:       if ((abs($xs-$xo)<$tolx) && (abs($ys-$yo)<$toly)) {
                   1455:          $tail=1;
                   1456:          &addlog("Attached tail: $obj"); 
                   1457:       }
                   1458:       if ((abs($xe-$xo)<$tolx) && (abs($ye-$yo)<$toly)) { 
                   1459:          $tip=1;
                   1460:          &addlog("Attached tip: $obj"); 
                   1461:       }
                   1462:    }
1.81      www      1463:    &addlog("Result tail:$tail tip:$tip");
                   1464:    return($tail,$tip);
                   1465: }
                   1466: 
1.77      www      1467:  
                   1468: sub vectorangle {
                   1469:    my ($x,$y)=@_;
1.78      www      1470:    my $angle=57.2957795*atan2($y,$x);
                   1471:    if ($angle<0) { $angle=360+$angle; }
                   1472:    return $angle;
1.77      www      1473: }
                   1474: 
                   1475: sub vectorlength {
                   1476:    my ($x,$y)=@_;
                   1477:    return sqrt($x*$x+$y*$y);
                   1478: }
                   1479: 
1.78      www      1480: sub relvector {
                   1481:    my ($xs,$xe,$ys,$ye)=@_;
                   1482:    return ($xe-$xs,$ye-$ys);
                   1483: }
                   1484: 
                   1485: sub plotvectorlength {
                   1486:    return &vectorlength(&relvector(&vectorcoords(@_)));
                   1487: }
                   1488: 
                   1489: sub plotvectorangle {
                   1490:    return &vectorangle(&relvector(&vectorcoords(@_)));
                   1491: }
                   1492: 
1.77      www      1493: 
                   1494: #
                   1495: # Evaluate a functionplotvectorrule
                   1496: #
                   1497: 
                   1498: sub functionplotvectorrulecheck {
                   1499:    my ($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)=@_;
1.78      www      1500:    &addlog("=================");
1.77      www      1501:    my ($label,$type)=split(/\:/,$rule);
                   1502:    if ($type eq 'vector') {
                   1503:       return &vectorcheck($rule,$xmin,$xmax,$ymin,$ymax,$safeeval);
                   1504:    } elsif ($type eq 'sum') {
                   1505:       return &sumcheck($rule,$xmin,$xmax,$ymin,$ymax,$safeeval);
1.85      www      1506:    } elsif ($type eq 'custom') {
                   1507:       return &customcheck($rule,$safeeval);
1.77      www      1508:    }
                   1509: }
                   1510: 
                   1511: sub vectorcheck {
                   1512:    my ($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)=@_;
                   1513:    my ($label,$type,$id,$vector,
                   1514:        $attachpoint,$notattachpoint,
                   1515:        $tailpoint,$tippoint,$nottailpoint,$nottippoint,
1.79      www      1516:        $length,$angle,$lengtherror,$angleerror)=split(/\:/,$rule);
1.78      www      1517:    &addlog("Vector Rule $label for vector ".$vector);
1.79      www      1518:    if ($length ne '') {
                   1519:       &addlog("Checking for length $length with error $lengtherror");
                   1520:       $length=&Apache::run::run($length,$safeeval);
                   1521:       &addlog("Length evaluated to $length");
                   1522:       my $thislength=&plotvectorlength($id,$vector);
                   1523:       &addlog("Found length $thislength");
                   1524:       if (abs($thislength-$length)>$lengtherror) {
                   1525:          &setfailed($label);
                   1526:          return 0;
                   1527:       }
                   1528:    }
1.80      www      1529:    if ($angle ne '') {
                   1530:       &addlog("Checking for angle $angle with error $angleerror");
                   1531:       $angle=&Apache::run::run($angle,$safeeval);
                   1532:       &addlog("Angle evaluated to $angle");
                   1533:       my $thisangle=&plotvectorangle($id,$vector);
                   1534:       &addlog("Found angle $thisangle");
                   1535:       my $anglediff=abs($thisangle-$angle);
                   1536:       &addlog("Angle difference: $anglediff");
                   1537:       if ($anglediff>360.-$anglediff) {
                   1538:          $anglediff=360.-$anglediff;
                   1539:       }
                   1540:       &addlog("Smallest angle difference: $anglediff");
                   1541:       if ($anglediff>$angleerror) {
                   1542:          &setfailed($label);
                   1543:          return 0;
                   1544:       }
                   1545:    }
1.81      www      1546:    if ($attachpoint ne '') {
                   1547:       &addlog("Checking attached: ".$attachpoint);
                   1548:       my ($tail,$tip)=&attached($id,$vector,$attachpoint,$xmin,$xmax,$ymin,$ymax);
                   1549:       unless ($tail || $tip) {
                   1550:          &setfailed($label);
                   1551:          return 0;
                   1552:       }
                   1553:    }
                   1554:    if ($notattachpoint ne '') {
                   1555:       &addlog("Checking not attached: ".$notattachpoint);
                   1556:       my ($tail,$tip)=&attached($id,$vector,$notattachpoint,$xmin,$xmax,$ymin,$ymax);
                   1557:       if ($tail || $tip) {
                   1558:          &setfailed($label);
                   1559:          return 0;
                   1560:       }
                   1561:    }
                   1562:    if ($tailpoint ne '') {
                   1563:       &addlog("Checking tail: ".$tailpoint);
                   1564:       my ($tail,$tip)=&attached($id,$vector,$tailpoint,$xmin,$xmax,$ymin,$ymax);
                   1565:       unless ($tail) {
                   1566:          &setfailed($label);
                   1567:          return 0;
                   1568:       }
                   1569:    }
                   1570:    if ($nottailpoint ne '') {
                   1571:       &addlog("Checking not tail: ".$nottailpoint);
                   1572:       my ($tail,$tip)=&attached($id,$vector,$nottailpoint,$xmin,$xmax,$ymin,$ymax);
                   1573:       if ($tail) {
                   1574:          &setfailed($label);
                   1575:          return 0;
                   1576:       }
                   1577:    }
                   1578:    if ($tippoint ne '') {
                   1579:       &addlog("Checking tip: ".$tippoint);
                   1580:       my ($tail,$tip)=&attached($id,$vector,$tippoint,$xmin,$xmax,$ymin,$ymax);
                   1581:       unless ($tip) {
                   1582:          &setfailed($label);
                   1583:          return 0;
                   1584:       }
                   1585:    }
                   1586:    if ($nottippoint ne '') {
                   1587:       &addlog("Checking not tip: ".$nottippoint);
                   1588:       my ($tail,$tip)=&attached($id,$vector,$nottippoint,$xmin,$xmax,$ymin,$ymax);
                   1589:       if ($tip) {
                   1590:          &setfailed($label);
                   1591:          return 0;
                   1592:       }
                   1593:    }
                   1594: 
1.79      www      1595:    &addlog("Rule $label passed.");
                   1596:    return 1;
1.77      www      1597: }
                   1598: 
                   1599: sub sumcheck {
                   1600:    my ($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)=@_;
1.82      www      1601:    my ($label,$type,$id,$vectors,$length,$angle,$lengtherror,$angleerror)=split(/\:/,$rule);
                   1602:    &addlog("Vector Sum Rule $label for vectors ".$vectors);
                   1603:    my $sumx=0;
                   1604:    my $sumy=0;
                   1605:    foreach my $sv (split(/\s*\,\s*/,$vectors)) {
                   1606:       my ($rx,$ry)=&relvector(&vectorcoords($id,$sv));
                   1607:       $sumx+=$rx;
                   1608:       $sumy+=$ry;
                   1609:    }
                   1610:    &addlog("Sum vector ($sumx,$sumy)");
1.83      www      1611:    if ($length ne '') {
                   1612:       &addlog("Checking length $length with error $lengtherror");
                   1613:       $length=&Apache::run::run($length,$safeeval);
                   1614:       &addlog("Evaluated to $length");
                   1615:       my $thislength=&vectorlength($sumx,$sumy);
                   1616:       &addlog("Actual length $thislength");
                   1617:       if (abs($length-$thislength)>$lengtherror) {
                   1618:                   &setfailed($label);
                   1619:          return 0;
                   1620:       }
                   1621:    }
                   1622:    if ($angle ne '') {
                   1623:       &addlog("Checking angle $angle with error $angleerror");
                   1624:       $angle=&Apache::run::run($angle,$safeeval);
                   1625:       &addlog("Evaluated to $angle");
                   1626:       my $thisangle=&vectorangle($sumx,$sumy);
                   1627:       &addlog("Actual angle $thisangle");
                   1628:       my $anglediff=abs($thisangle-$angle);
                   1629:       &addlog("Angle difference: $anglediff");
                   1630:       if ($anglediff>360.-$anglediff) {
                   1631:          $anglediff=360.-$anglediff;
                   1632:       }
                   1633:       &addlog("Smallest angle difference: $anglediff");
                   1634:       if ($anglediff>$angleerror) {
                   1635:          &setfailed($label);
                   1636:          return 0;
                   1637:       }
                   1638:    }
1.79      www      1639:    &addlog("Rule $label passed.");
                   1640:    return 1;
1.77      www      1641: }
                   1642: 
1.85      www      1643: sub customcheck {
                   1644:    my ($rule,$safeeval)=@_;
                   1645:    my ($label,$type,$prg)=split(/\:/,$rule);
                   1646:    &addlog("Custom Rule ".$label);
                   1647:    my $result=&Apache::run::run(&unescape($prg),$safeeval);
                   1648:    &addlog("Algorithm returned $result");
                   1649:    unless ($result) {
                   1650:       &setfailed($label);
                   1651:       return 0;
                   1652:    }
                   1653:    &addlog("Rule $label passed.");
                   1654:    return 1;
                   1655: }
                   1656: 
1.77      www      1657: #
                   1658: # Evaluate a functionplotrule
                   1659: #
1.35      www      1660:  
1.25      www      1661: sub functionplotrulecheck {
1.65      www      1662:    my ($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)=@_;
1.33      www      1663: 
1.35      www      1664:    my ($label,$derivative,$xinitial,$xinitiallabel,$xfinal,$xfinallabel,$minimumlength,$maximumlength,$relationship,$value,$percent)
1.25      www      1665:       =split(/\:/,$rule);
1.33      www      1666:    $percent=($percent>0?$percent:5);
1.35      www      1667:    &addlog("=================");
1.42      www      1668:    &addlog("Rule $label for ".($derivative<0?'integral':('function itself','first derivative','second derivative')[$derivative])." $relationship $value");
1.65      www      1669: #
                   1670: # Evaluate the value
                   1671: #
1.91    ! www      1672:    if (($value=~/\D/) && ($value ne 'undef')) {
1.65      www      1673:       $Apache::functionplotresponse::fpr_xmin=$xmin;
                   1674:       $Apache::functionplotresponse::fpr_xmax=$xmax;
                   1675:       $value=&Apache::run::run($value,$safeeval);
                   1676:       &addlog("Value evaluated to $value");
                   1677:    }
                   1678: 
                   1679: #
                   1680: # Minimum and maximum lengths of the interval
                   1681: #
1.49      www      1682:    if ((defined($minimumlength)) || (defined($maximumlength))) {
                   1683:       &addlog("Minimumlength $minimumlength Maximumlength $maximumlength");
                   1684:    }
1.30      www      1685:    my $li=0;
                   1686:    my $lh=400;
                   1687: 
1.31      www      1688: # Special case: the upper boundary was not defined
                   1689: # and needs to be set to the value where
                   1690: # the condition is not true anymore => set flag
                   1691: 
                   1692:    my $findupper=0;
                   1693:    if (($xfinal eq '')
                   1694:     && (!defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}))
                   1695:     && ($xfinallabel)) {
                   1696:        $findupper=1;
                   1697:    }
                   1698: 
1.25      www      1699: # if a hard value is set for the boundaries, it overrides the label
1.30      www      1700:    if (($xinitial ne '') && ($xinitiallabel ne '') && ($xinitiallabel ne 'start')) {
                   1701:       $li=&array_index($xmin,$xmax,$xinitial);
                   1702:       $Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel}=$li;
                   1703:    }
                   1704:    if (($xfinal ne '') && ($xfinallabel ne '') && ($xfinallabel ne 'end')) {
                   1705:       $lh=&array_index($xmin,$xmax,$xfinal);
                   1706:       $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$lh;
1.25      www      1707:    }
1.31      www      1708: # if the label is defined, use it
1.25      www      1709:    if (defined($Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel})) {
1.35      www      1710:       &addlog("Using lower label $xinitiallabel");
1.30      www      1711:       $li=$Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel};
                   1712:    } else {
                   1713:       $li=&array_index($xmin,$xmax,$xinitial);
1.25      www      1714:    }
1.31      www      1715:    unless ($findupper) {
                   1716:       if (defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel})) {
1.35      www      1717:          &addlog("Using upper label $xfinallabel");
1.33      www      1718:          $lh=$Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}-1;
1.31      www      1719:       } else {
                   1720:          $lh=&array_index($xmin,$xmax,$xfinal);
                   1721:       }
1.25      www      1722:    }
                   1723: # Basic sanity checks
1.30      www      1724:    if ($li<0) { $li=0; }
                   1725:    if ($lh>400) { $lh=400; }
1.38      www      1726:    if (($li>$lh) || (!defined($lh))) {
1.30      www      1727:        $lh=$li;
1.25      www      1728:    }
1.31      www      1729: 
1.35      www      1730:    &addlog("Boundaries: x=".&actualval($li,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$li]."; index $li)) to x=".
                   1731:                             &actualval($lh,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$lh]."; index $lh))");
                   1732:    if ($findupper) {
                   1733:       &addlog("Looking for label $xfinallabel");
                   1734:    }
1.33      www      1735:    my $tol=$percent*($ymax-$ymin)/100;
                   1736:    if ($xmax>$xmin) {
                   1737:       if ($derivative==2) {
                   1738:          $tol=4.*$tol/($xmax-$xmin);
                   1739:       } elsif ($derivative==1) {
                   1740:          $tol=2.*$tol/($xmax-$xmin);
1.42      www      1741:       } elsif ($derivative==-1) {
                   1742:          $tol=$tol*($xmax-$xmin)/2.;
1.33      www      1743:       }
1.27      www      1744:    }
1.42      www      1745:    my $integral=0;
                   1746:    my $binwidth=($xmax-$xmin)/400.;
                   1747:    if (($derivative<0) && (!$findupper)) {
                   1748: # definite integral, calculate over whole length
                   1749:      &addlog("Calculating definite integral");
                   1750:      for (my $i=$li; $i<=$lh; $i++) {
                   1751:         $integral+=$Apache::functionplotresponse::func[$i]*$binwidth;
                   1752:      }
                   1753:      unless (&compare_rel($relationship,$value,$integral,$tol)) {
                   1754:         &addlog("Actual integral ".(defined($integral)?$integral:'undef').", expected $value, tolerance $tol");
                   1755:         &addlog("Rule $label failed.");
1.79      www      1756:         &setfailed($label);
1.42      www      1757:         return 0;
                   1758:      } 
                   1759:    } else {
                   1760:      for (my $i=$li; $i<=$lh; $i++) {
1.25      www      1761:         my $val;
                   1762:         if ($derivative==2) {
1.27      www      1763:            $val=$Apache::functionplotresponse::d2funcdx2[$i];
1.25      www      1764:         } elsif ($derivative==1) {
1.27      www      1765:            $val=$Apache::functionplotresponse::dfuncdx[$i];
1.42      www      1766:         } elsif ($derivative==-1) {
                   1767:            $integral+=$Apache::functionplotresponse::func[$i]*$binwidth;
                   1768:            $val=$integral;      
1.25      www      1769:         } else {
1.27      www      1770:            $val=$Apache::functionplotresponse::func[$i];
1.25      www      1771:         }
1.31      www      1772:         unless (&compare_rel($relationship,$value,$val,$tol)) { 
1.37      www      1773:            &addlog("Actual value ".(defined($val)?$val:'undef').", expected $value, tolerance $tol");
1.35      www      1774:            &addlog("Condition not fulfilled at x=".&actualval($i,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$i]."; index $i)");
1.31      www      1775:            if (($findupper) && ($i>$li)) {
1.49      www      1776: # Check lengths
                   1777:               unless (&checklength($i,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)) { return 0; }
                   1778: # Successfully found a new label, set it
1.31      www      1779:               $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$i;
1.35      www      1780:               &addlog("Rule $label passed, setting label $xfinallabel");
1.31      www      1781:               return 1;
                   1782:            } else {
1.35      www      1783:               &addlog("Rule $label failed.");
1.49      www      1784:               &setfailed($label);
1.31      www      1785:               return 0; 
                   1786:            }
                   1787:         }
1.42      www      1788:      }
1.25      www      1789:    }
1.49      www      1790: # Corner case where this makes sense: using start or stop as defined labels
                   1791:    unless (&checklength($lh,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)) { return 0; }
1.35      www      1792:    &addlog("Rule $label passed.");
1.27      www      1793:    return 1;
1.24      www      1794: }
                   1795: 
1.49      www      1796: #
                   1797: # check for minimum and maximum lengths
                   1798: #
                   1799: 
                   1800: sub checklength {
                   1801:     my ($i,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)=@_;
                   1802:     unless (($minimumlength) || ($maximumlength)) { return 1; }
                   1803:     my $length=&actualval($i,$xmin,$xmax)-&actualval($li,$xmin,$xmax);
                   1804:     if ($minimumlength) {
                   1805:        if ($length<$minimumlength) {
                   1806:           &addlog("Rule $label failed, actual length $length, minimum length $minimumlength");
                   1807:           &setfailed($label);
                   1808:           return 0;
                   1809:        }
                   1810:     }
                   1811:     if ($maximumlength) {
                   1812:        if ($length>$maximumlength) {
                   1813:           &addlog("Rule $label failed, actual length $length, maximum length $maximumlength");
                   1814:           &setfailed($label);
                   1815:           return 0;
                   1816:        }
                   1817:     }
                   1818:     return 1;
                   1819: }
                   1820: 
                   1821: sub setfailed {
1.79      www      1822:    my ($hintlabel)=@_;
1.49      www      1823:    $hintlabel=~s/^R//;
                   1824:    push(@Apache::functionplotresponse::failedrules,$hintlabel);
                   1825:    &addlog("Set hint condition $hintlabel");
                   1826: }
                   1827: 
1.37      www      1828: sub start_functionplotruleset {
                   1829:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1830:    if ($target eq 'edit') {
                   1831:       return &Apache::edit::start_table($token).
                   1832:         '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Rule Set').'</span></td>'
                   1833:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
                   1834:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'.
1.50      www      1835:         &Apache::edit::insertlist($target,$token).'&nbsp;&nbsp;&nbsp;'
                   1836:        .&Apache::loncommon::help_open_topic('Function_Plot_Response_Rule_Set','Function Plot Rules')
1.37      www      1837:        .'</span></td>'
                   1838:        ."<td>&nbsp;"
                   1839:        .&Apache::edit::end_row()
                   1840:        .&Apache::edit::start_spanning_row()
                   1841:        ."\n";
                   1842:    }
                   1843: }
1.3       www      1844: 
1.37      www      1845: sub end_functionplotruleset {
                   1846:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                   1847:     my $id=$Apache::inputtags::response[-1];
                   1848:     my $partid=$Apache::inputtags::part;
                   1849:     my $internalid = $partid.'_'.$id;
                   1850: 
                   1851:     if ($target eq 'edit' ) {
                   1852:         return &Apache::edit::end_table();
                   1853:     }  elsif ($target eq 'grade'
1.10      www      1854:          && &Apache::response::submitted()
                   1855:          && $Apache::lonhomework::type ne 'exam') {
1.12      www      1856: #
                   1857: # Actually grade
                   1858: #
1.41      www      1859:     my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
1.27      www      1860: 
1.24      www      1861:         my $ad='';
1.30      www      1862:         undef  %Apache::functionplotresponse::functionplotrulelabels;
1.35      www      1863:         $Apache::functionplotresponse::ruleslog='';
1.30      www      1864:         $Apache::functionplotresponse::functionplotrulelabels{'start'}=400;
                   1865:         $Apache::functionplotresponse::functionplotrulelabels{'end'}=0;
1.64      www      1866:         if (&populate_arrays($internalid,$xmin,$xmax,$ymin,$ymax) eq 'no_func') {
1.21      www      1867:            $ad='NOT_FUNCTION';
1.18      www      1868:         } else {
1.35      www      1869:            &addlog("Start of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'start'},$xmin,$xmax)." (index ".
                   1870:                                         $Apache::functionplotresponse::functionplotrulelabels{'start'}.")");
                   1871:            &addlog("End of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'end'},$xmin,$xmax)." (index ".
                   1872:                                         $Apache::functionplotresponse::functionplotrulelabels{'end'}.")");
                   1873: 
1.24      www      1874: # We have a function that we can actually grade, go through the spline rules.
1.25      www      1875:            foreach my $rule (@Apache::functionplotresponse::functionplotrules) {
1.65      www      1876:               unless (&functionplotrulecheck($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)) {
1.24      www      1877:                  $ad='INCORRECT';
                   1878:                  last;
                   1879:               }
                   1880:            }
1.77      www      1881: # And now go through the vector rules
                   1882:            foreach my $rule (@Apache::functionplotresponse::functionplotvectorrules) {
                   1883:               unless (&functionplotvectorrulecheck($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)) {
                   1884:                  $ad='INCORRECT';
                   1885:                  last;
                   1886:               }
                   1887:            }
1.24      www      1888: # If it's not wrong, it's correct 
                   1889:            unless ($ad) { $ad='EXACT_ANS' };
1.18      www      1890:         }
1.37      www      1891:         &addlog("Set hint conditions: ".join(",",@Apache::functionplotresponse::failedrules));
                   1892:         &addlog("Assigned award detail: $ad");
                   1893: # Store for later to be assigned at end_functionplotresponse
                   1894:         $Apache::functionplotresponse::awarddetail=$ad;
                   1895:      }
                   1896: }
                   1897: 
                   1898: 
                   1899: sub end_functionplotresponse {
                   1900:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1901:   &Apache::response::end_response;
                   1902: 
                   1903:   my $result;
                   1904:   my $id=$Apache::inputtags::response[-1];
                   1905:   my $partid=$Apache::inputtags::part;
                   1906:   my $internalid = $partid.'_'.$id;
1.20      www      1907: 
1.37      www      1908:     if ($target eq 'edit') { $result=&Apache::edit::end_table(); }
                   1909:     if ($target eq 'grade'
                   1910:          && &Apache::response::submitted()
                   1911:          && $Apache::lonhomework::type eq 'exam') {
                   1912: 
                   1913:         &Apache::response::scored_response($partid,$id);
                   1914: 
                   1915:     } elsif ($target eq 'grade'
                   1916:          && &Apache::response::submitted()
                   1917:          && $Apache::lonhomework::type ne 'exam') {
                   1918:         my ($response,%coords)=&get_answer_from_form_fields($internalid);
                   1919:         $Apache::lonhomework::results{"resource.$partid.$id.submission"}=$response;
                   1920:         my %previous=&Apache::response::check_for_previous($response,$partid,$id);
                   1921: #
                   1922: # Assign grade
                   1923: #
                   1924:         my $ad=$Apache::functionplotresponse::awarddetail;
1.12      www      1925: #
                   1926: # Store grading info
                   1927: #
                   1928:         $Apache::lonhomework::results{"resource.$partid.$id.awarddetail"}=$ad;
                   1929:         &Apache::response::handle_previous(\%previous,$ad);
1.10      www      1930:    } elsif ($target eq 'web') {
1.37      www      1931:         undef @Apache::functionplotresponse::failedrules;
                   1932:    }
                   1933:    return $result;
                   1934: }
                   1935: 
                   1936: sub end_functionplotelements {
                   1937:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                   1938:   my $result='';
                   1939:   my $id=$Apache::inputtags::response[-1];
                   1940:   my $partid=$Apache::inputtags::part;
                   1941:   my $internalid = $partid.'_'.$id;
                   1942:   if ($target eq 'edit' ) {
                   1943:      $result=&Apache::edit::end_table();
                   1944:   } elsif ($target eq 'web') {
1.47      www      1945:      my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
                   1946: 
                   1947: # Are we in show answer mode?
                   1948:      my $showanswer=&Apache::response::show_answer();
                   1949:      if ($showanswer) {
                   1950: # Render answerdisplay
                   1951:         my $answerdisplay=&Apache::lonxml::get_param('answerdisplay',$parstack,$safeeval,-2);
                   1952:         if ($answerdisplay=~/\S/s) {
                   1953:            foreach my $plot (split(/\s*\,\s*/,$answerdisplay)) {
1.58      www      1954:               my @components=split(/\s*\:\s*/,$plot);
                   1955:               if ($#components<3) {
                   1956: # Just a simple plot
                   1957:                  my ($func,$xl,$xh)=@components;
                   1958:                  if ((!defined($xl)) || ($xl eq '')) { $xl=$xmin; }
                   1959:                  if ((!defined($xh)) || ($xh eq '')) { $xh=$xmax; }
                   1960:                  $result.=&plot_script($internalid,$func,1,'','00aa00',$xl,$xh,6);
                   1961:               } else {
                   1962: # This is a spline
1.59      www      1963:                  $result.=&answer_spline_script($internalid,@components);
1.58      www      1964:               }
1.47      www      1965:            }
                   1966:         }
                   1967:      }
1.48      www      1968:      my $fixed=0;
                   1969:      if (($showanswer) || (&Apache::response::check_status()>=2)) { $fixed=1; }
1.6       www      1970: # Now is the time to render all of the stored splines
                   1971:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
1.48      www      1972:         $result.=&generate_spline($internalid,$label,$xmin,$xmax,$ymin,$ymax,$fixed);
1.6       www      1973:      }
1.5       www      1974: # close the init script
1.3       www      1975:      $result.=&end_init_script();
1.17      www      1976: # register all splines in this response 
                   1977:      $result.='<input type="hidden" name="HWVAL_AllSplines_'.$internalid.'" value="'.
                   1978:                  join(',',keys(%Apache::functionplotresponse::splineorder)).'" />'."\n";
                   1979:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
                   1980:         $result.='<input type="hidden" name="HWVAL_SplineOrder_'.$internalid.'_'.$label.'" value="'.
                   1981:                  $Apache::functionplotresponse::splineorder{$label}.'" />'."\n";
                   1982:      }
1.9       www      1983: # generate the input fields
                   1984:      $result.=$Apache::functionplotresponse::inputfields;
1.5       www      1985: # actually start the <applet>-tag
1.88      www      1986:      $result.=&geogebra_startcode($internalid,
                   1987:                                   &Apache::lonxml::get_param('width',$parstack,$safeeval,-2),
                   1988:                                   &Apache::lonxml::get_param('height',$parstack,$safeeval,-2));
1.5       www      1989: # load the spline bytecode
1.3       www      1990:      $result.=&geogebra_spline_program();
1.5       www      1991: # set default parameters
1.3       www      1992:      $result.=&geogebra_default_parameters($internalid);
1.5       www      1993: # close the <applet>-tag
1.1       www      1994:      $result.=&geogebra_endcode();
                   1995:   }
                   1996:   return $result;
                   1997: }
                   1998: 
1.41      www      1999: sub boundaries {
                   2000:    my ($parstack,$safeeval,$level)=@_;
                   2001:    my $xmin=&Apache::lonxml::get_param('xmin',$parstack,$safeeval,$level);
                   2002:    $xmin=(defined($xmin)?$xmin:-10);
                   2003:    my $xmax=&Apache::lonxml::get_param('xmax',$parstack,$safeeval,$level);
                   2004:    $xmax=(defined($xmax)?$xmax:10);
                   2005:    my $ymin=&Apache::lonxml::get_param('ymin',$parstack,$safeeval,$level);
                   2006:    $ymin=(defined($ymin)?$ymin:-10);
                   2007:    my $ymax=&Apache::lonxml::get_param('ymax',$parstack,$safeeval,$level);
                   2008:    $ymax=(defined($ymax)?$ymax:10);
                   2009:    if ($xmax<=$xmin) {
                   2010:       $xmax=$xmin+20;
                   2011:    }
                   2012:    if ($ymax<=$ymin) {
                   2013:       $ymax=$ymin+20;
                   2014:    }
                   2015:    return ($xmin,$xmax,$ymin,$ymax);
                   2016: }
                   2017: 
1.37      www      2018: sub start_functionplotelements {
                   2019:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   2020:    my $result='';
                   2021:    my $id=$Apache::inputtags::response[-1];
                   2022:    my $partid=$Apache::inputtags::part;
                   2023:    my $internalid = $partid.'_'.$id;
                   2024: 
                   2025:    if ($target eq 'edit') {
                   2026:       return &Apache::edit::start_table($token).
                   2027:         '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Elements').'</span></td>'
                   2028:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
                   2029:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'.
1.50      www      2030:         &Apache::edit::insertlist($target,$token).'&nbsp;&nbsp;&nbsp;'
                   2031:        .&Apache::loncommon::help_open_topic('Function_Plot_Response_Elements','Function Plot Elements')
1.37      www      2032:        .'</span></td>'
                   2033:        ."<td>&nbsp;"
                   2034:        .&Apache::edit::end_row()
                   2035:        .&Apache::edit::start_spanning_row()
                   2036:        ."\n";
                   2037:    } elsif ($target eq 'web') {
1.41      www      2038:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
1.37      www      2039:       my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
                   2040:       my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
                   2041:       my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
                   2042:       my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval,-2);
                   2043:       my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval,-2);
                   2044: 
                   2045: 
                   2046: # paste in the update routine to receive stuff back from the applet
                   2047:      $result.=&update_script($internalid);
                   2048: # start the initscript for this applet
                   2049:      $result.=&start_init_script($internalid);
                   2050: # put the axis commands inside
                   2051:      $result.=&axes_script($internalid,$xmin,$xmax,$ymin,$ymax,$xaxisvisible,$yaxisvisible,$gridvisible);
1.45      www      2052:      $result.=&axes_label($internalid,$xmin,$xmax,$ymin,$ymax,$xlabel,$ylabel);
1.37      www      2053: # init script is left open
                   2054:   }
                   2055:   return $result;
                   2056: }
                   2057: 
1.1       www      2058: 1;
                   2059: 
                   2060: __END__
                   2061:  
                   2062: =head1 NAME
                   2063: 
                   2064: Apache::functionplotresponse.pm;
                   2065: 
                   2066: =head1 SYNOPSIS
                   2067: 
                   2068: Handles tags associated with accepting function plots.
                   2069: 
                   2070: This is part of the LearningOnline Network with CAPA project
                   2071: described at http://www.lon-capa.org.
                   2072: 
                   2073: =head1 HANDLER SUBROUTINE
                   2074: 
                   2075: start_functionplotresponse()
                   2076: 
                   2077: =head1 OTHER SUBROUTINES
                   2078: 
                   2079: =over
                   2080: 
                   2081: =item end_functionplotresponse()
                   2082: 
                   2083: =back
                   2084: 
                   2085: =cut

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