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

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

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