[system] / trunk / pg / macros / PGanswermacros.pl Repository:
ViewVC logotype

View of /trunk/pg/macros/PGanswermacros.pl

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1450 - (download) (as text) (annotate)
Tue Aug 5 16:24:48 2003 UTC (16 years, 6 months ago) by jj
File size: 149340 byte(s)
Added option of test_points to fun_cmp.

    1 
    2 
    3 # This file is PGanswermacros.pl
    4 # This includes the subroutines for the ANS macros, that
    5 # is, macros allowing a more flexible answer checking
    6 ####################################################################
    7 # Copyright @ 1995-2000 University of Rochester
    8 # All Rights Reserved
    9 ####################################################################
   10 #$Id$
   11 
   12 =head1 NAME
   13 
   14   PGanswermacros.pl -- located in the courseScripts directory
   15 
   16 =head1 SYNPOSIS
   17 
   18   Number Answer Evaluators:
   19     num_cmp() --  uses an input hash to determine parameters
   20 
   21     std_num_cmp(), std_num_cmp_list(), std_num_cmp_abs, std_num_cmp_abs_list()
   22     frac_num_cmp(), frac_num_cmp_list(), frac_num_cmp_abs, frac_num_cmp_abs_list()
   23     arith_num_cmp(), arith_num_cmp_list(), arith_num_cmp_abs, arith_num_cmp_abs_list()
   24     strict_num_cmp(), strict_num_cmp_list(), strict_num_cmp_abs, strict_num_cmp_abs_list()
   25     numerical_compare_with_units()  --  requires units as part of the answer
   26     std_num_str_cmp() --  also accepts a set of strings as possible answers
   27 
   28   Function Answer Evaluators:
   29     fun_cmp() --  uses an input hash to determine parameters
   30 
   31     function_cmp(), function_cmp_abs()
   32     function_cmp_up_to_constant(), function_cmp_up_to_constant_abs()
   33     multivar_function_cmp()
   34 
   35   String Answer Evaluators:
   36     str_cmp() --  uses an input hash to determine parameters
   37 
   38     std_str_cmp(), std_str_cmp_list(), std_cs_str_cmp(), std_cs_str_cmp_list()
   39     strict_str_cmp(), strict_str_cmp_list()
   40     ordered_str_cmp(), ordered_str_cmp_list(), ordered_cs_str_cmp(), ordered_cs_str_cmp_list()
   41     unordered_str_cmp(), unordered_str_cmp_list(), unordered_cs_str_cmp(), unordered_cs_str_cmp_list()
   42 
   43   Miscellaneous Answer Evaluators:
   44     checkbox_cmp()
   45     radio_cmp()
   46 
   47 =cut
   48 
   49 =head1 DESCRIPTION
   50 
   51 This file adds subroutines which create "answer evaluators" for checking
   52 answers. Each answer evaluator accepts a single input from a student answer,
   53 checks it and creates an output hash %ans_hash with seven or eight entries
   54 (the preview_latex_string is optional). The output hash is now being created
   55 with the AnswerHash package "class", which is located at the end of this file.
   56 This class is currently just a wrapper for the hash, but this might change in
   57 the future as new capabilities are added.
   58 
   59           score     =>  $correctQ,
   60           correct_ans   =>  $originalCorrEqn,
   61           student_ans   =>  $modified_student_ans
   62           original_student_ans  =>  $original_student_answer,
   63           ans_message   =>  $PGanswerMessage,
   64           type      =>  'typeString',
   65           preview_text_string =>  $preview_text_string,
   66           preview_latex_string  =>  $preview_latex_string
   67 
   68 
   69   $ans_hash{score}      --  a number between 0 and 1 indicating
   70                     whether the answer is correct. Fractions
   71                     allow the implementation of partial
   72                     credit for incorrect answers.
   73   $ans_hash{correct_ans}      --  The correct answer, as supplied by the
   74                     instructor and then formatted. This can
   75                     be viewed by the student after the answer date.
   76   $ans_hash{student_ans}      --  This is the student answer, after reformatting;
   77                     for example the answer might be forced
   78                     to capital letters for comparison with
   79                     the instructors answer. For a numerical
   80                     answer, it gives the evaluated answer.
   81                     This is displayed in the section reporting
   82                     the results of checking the student answers.
   83   $ans_hash{original_student_ans}   --  This is the original student answer. This is displayed
   84                     on the preview page and may be used for sticky answers.
   85   $ans_hash{ans_message}      --  Any error message, or hint provided by the answer evaluator.
   86                     This is also displayed in the section reporting
   87                     the results of checking the student answers.
   88   $ans_hash{type}       --  A string indicating the type of answer evaluator. This
   89                     helps in preprocessing the student answer for errors.
   90                     Some examples:
   91                       'number_with_units'
   92                       'function'
   93                       'frac_number'
   94                       'arith_number'
   95   $ans_hash{preview_text_string}    --  This typically shows how the student answer was parsed. It is
   96                     displayed on the preview page. For a student answer of 2sin(3x)
   97                     this would be 2*sin(3*x). For string answers it is typically the
   98                     same as $ans_hash{student_ans}.
   99   $ans_hash{preview_latex_string}   --  THIS IS OPTIONAL. This is latex version of the student answer
  100                     which is used to show a typeset view on the answer on the preview
  101                     page. For a student answer of 2/3, this would be \frac{2}{3}.
  102 
  103 Technical note: the routines in this file are not actually answer evaluators. Instead, they create
  104 answer evaluators. An answer evaluator is an anonymous subroutine, referenced by a named scalar. The
  105 routines in this file build the subroutine and return a reference to it. Later, when the student
  106 actually enters an answer, the problem processor feeds that answer to the referenced subroutine, which
  107 evaluates it and returns a score (usually 0 or 1). For most users, this distinction is unimportant, but
  108 if you plan on writing your own answer evaluators, you should understand this point.
  109 
  110 =cut
  111 
  112 BEGIN {
  113   be_strict(); # an alias for use strict.  This means that all global variable must contain main:: as a prefix.
  114 }
  115 
  116 
  117 my ($BR                   ,   # convenient localizations.
  118   $PAR                  ,
  119   $numRelPercentTolDefault    ,
  120   $numZeroLevelDefault      ,
  121   $numZeroLevelTolDefault     ,
  122   $numAbsTolDefault         ,
  123   $numFormatDefault         ,
  124   $functRelPercentTolDefault      ,
  125   $functZeroLevelDefault      ,
  126   $functZeroLevelTolDefault   ,
  127   $functAbsTolDefault         ,
  128   $functNumOfPoints         ,
  129   $functVarDefault          ,
  130   $functLLimitDefault         ,
  131   $functULimitDefault         ,
  132   $functMaxConstantOfIntegration  ,
  133   $CA                             ,
  134   $rh_envir                          ,
  135 );
  136 
  137 
  138 
  139 
  140 sub _PGanswermacros_init {
  141 
  142      $BR                              = main::PG_restricted_eval(q!$main::BR!);
  143      $PAR                             = main::PG_restricted_eval(q!$main::PAR!);
  144 
  145     # import defaults
  146     # these are now imported from the %envir variable
  147      $numRelPercentTolDefault     = main::PG_restricted_eval(q!$main::numRelPercentTolDefault!);
  148      $numZeroLevelDefault       = main::PG_restricted_eval(q!$main::numZeroLevelDefault!);
  149      $numZeroLevelTolDefault      = main::PG_restricted_eval(q!$main::numZeroLevelTolDefault!);
  150      $numAbsTolDefault            = main::PG_restricted_eval(q!$main::numAbsTolDefault!);
  151      $numFormatDefault            = main::PG_restricted_eval(q!$main::numFormatDefault!);
  152      $functRelPercentTolDefault     = main::PG_restricted_eval(q!$main::functRelPercentTolDefault!);
  153      $functZeroLevelDefault       = main::PG_restricted_eval(q!$main::functZeroLevelDefault!);
  154      $functZeroLevelTolDefault      = main::PG_restricted_eval(q!$main::functZeroLevelTolDefault!);
  155      $functAbsTolDefault        = main::PG_restricted_eval(q!$main::functAbsTolDefault!);
  156      $functNumOfPoints            = main::PG_restricted_eval(q!$main::functNumOfPoints!);
  157      $functVarDefault           = main::PG_restricted_eval(q!$main::functVarDefault!);
  158      $functLLimitDefault        = main::PG_restricted_eval(q!$main::functLLimitDefault!);
  159      $functULimitDefault        = main::PG_restricted_eval(q!$main::functULimitDefault!);
  160      $functMaxConstantOfIntegration   = main::PG_restricted_eval(q!$main::functMaxConstantOfIntegration!);
  161      $rh_envir                          =   main::PG_restricted_eval(q!\%main::envir!);
  162 }
  163 
  164 ##########################################################################
  165 ##########################################################################
  166 ## Number answer evaluators
  167 
  168 =head2 Number Answer Evaluators
  169 
  170 Number answer evaluators take in a numerical answer, compare it to the correct answer,
  171 and return a score. In addition, they can choose to accept or reject an answer based on
  172 its format, closeness to the correct answer, and other criteria. There are two types
  173 of numerical answer evaluators: num_cmp(), which takes a hash of named options as parameters,
  174 and the "mode"_num_cmp() variety, which use different functions to access different sets of
  175 options. In addition, there is the special case of std_num_str_cmp(), which can evaluate
  176 both numbers and strings.
  177 
  178 Numerical Comparison Options
  179 
  180   correctAnswer   --  This is the correct answer that the student answer will
  181             be compared to. However, this does not mean that the
  182             student answer must match this exactly. How close the
  183             student answer must be is determined by the other
  184             options, especially tolerance and format.
  185 
  186   tolerance   --  These options determine how close the student answer
  187             must be to the correct answer to qualify. There are two
  188             types of tolerance: relative and absolute. Relative
  189             tolerances are given in percentages. A relative
  190             tolerance of 1 indicates that the student answer must
  191             be within 1% of the correct answer to qualify as correct.
  192             In other words, a student answer is correct when
  193               abs(studentAnswer - correctAnswer) <= abs(.01*relpercentTol*correctAnswer)
  194             Using absolute tolerance, the student answer must be a
  195             fixed distance from the correct answer to qualify.
  196             For example, an absolute tolerance of 5 means that any
  197             number which is +-5 of the correct answer qualifies as correct.
  198               Final (rarely used) tolerance options are zeroLevel
  199             and zeroLevelTol, used in conjunction with relative
  200             tolerance. if correctAnswer has absolute value less than
  201             or equal to zeroLevel, then the student answer must be,
  202             in absolute terms, within zeroLevelTol of correctAnswer, i.e.,
  203               abs(studentAnswer - correctAnswer) <= zeroLevelTol.
  204             In other words, if the correct answer is very near zero,
  205             an absolute tolerance will be used. One must do this to
  206             handle floating point answers very near zero, because of
  207             the inaccuracy of floating point arithmetic. However, the
  208             default values are almost always adequate.
  209 
  210   mode      --  This determines the allowable methods for entering an
  211             answer. Answers which do not meet this requirement will
  212             be graded as incorrect, regardless of their numerical
  213             value. The recognized modes are:
  214               'std' (default) --  allows any expression which evaluates
  215                         to a number, including those using
  216                         elementary functions like sin() and
  217                         exp(), as well as the operations of
  218                         arithmetic (+, -, *, /, ^)
  219               'strict'  --  only decimal numbers are allowed
  220               'frac'    --  whole numbers and fractions are allowed
  221               'arith'   --  arithmetic expressions are allowed, but
  222                         no functions
  223             Note that all modes allow the use of "pi" and "e" as
  224             constants, and also the use of "E" to represent scientific
  225             notation.
  226 
  227   format      --  The format to use when displaying the correct and
  228             submitted answers. This has no effect on how answers are
  229             evaluated; it is only for cosmetic purposes. The
  230             formatting syntax is the same as Perl uses for the sprintf()
  231             function. Format strings are of the form '%m.nx' or '%m.nx#',
  232             where m and n are described below, and x is a formatter.
  233               Esentially, m is the minimum length of the field
  234             (make this negative to left-justify). Note that the decimal
  235             point counts as a character when determining the field width.
  236             If m begins with a zero, the number will be padded with zeros
  237             instead of spaces to fit the field.
  238               The precision specifier (n) works differently, depending
  239             on which formatter you are using. For d, i, o, u, x and X
  240             formatters (non-floating point formatters), n is the minimum
  241             number of digits to display. For e and f, it is the number of
  242             digits that appear after the decimal point (extra digits will
  243             be rounded; insufficient digits will be padded with spaces--see
  244             '#' below). For g, it is the number of significant digits to
  245             display.
  246               The full list of formatters can be found in the manpage
  247             for printf(3), or by typing "perldoc -f sprintf" at a
  248             terminal prompt. The following is a brief summary of the
  249             most frequent formatters:
  250               d --  decimal number
  251               ld  --  long decimal number
  252               u --  unsigned decimal number
  253               lu  --  long unsigned decimal number
  254               x --  hexadecimal number
  255               o --  octal number
  256               e --  floating point number in scientific notation
  257               f --  floating point number
  258               g --  either e or f, whichever takes less space
  259             Technically, g will use e if the exponent is less than -4 or
  260             greater than or equal to the precision. Trailing zeros are
  261             removed in this mode.
  262               If the format string ends in '#', trailing zeros will be
  263             removed in the decimal part. Note that this is not a standard
  264             syntax; it is handled internally by WeBWorK and not by Perl
  265             (although this should not be a concern to end users).
  266             The default format is '%0.5f#', which displays as a floating
  267             point number with 5 digits of precision and no trailing zeros.
  268             Other useful format strings might be '%0.2f' for displaying
  269             dollar amounts, or '%010d' to display an integer with leading
  270             zeros. Setting format to an empty string ( '' ) means no
  271             formatting will be used; this will show 'arbitrary' precision
  272             floating points.
  273 
  274 Default Values (As of 7/24/2000) (Option -- Variable Name -- Value)
  275 
  276   Format          --  $numFormatDefault   --  "%0.5f#"
  277   Relative Tolerance    --  $numRelPercentTolDefault  --  .1
  278   Absolute Tolerance    --  $numAbsTolDefault   --  .001
  279   Zero Level        --  $numZeroLevelDefault    --  1E-14
  280   Zero Level Tolerance  --  $numZeroLevelTolDefault   --  1E-12
  281 
  282 =cut
  283 
  284 
  285 =head3 num_cmp()
  286 
  287 Compares a number or a list of numbers, using a named hash of options to set
  288 parameters. This can make for more readable code than using the "mode"_num_cmp()
  289 style, but some people find one or the other easier to remember.
  290 
  291 ANS( num_cmp( answer or answer_array_ref, options_hash ) );
  292 
  293   1. the correct answer, or a reference to an array of correct answers
  294   2. a hash with the following keys (all optional):
  295     mode      --  'std' (default) (allows any expression evaluating to
  296                 a number)
  297               'strict' (only numbers are allowed)
  298               'frac' (fractions are allowed)
  299               'arith' (arithmetic expressions allowed)
  300     format      --  '%0.5f#' (default); defines formatting for the
  301                 correct answer
  302     tol       --  an absolute tolerance, or
  303     relTol      --  a relative tolerance
  304     units     --  the units to use for the answer(s)
  305     strings     --  a reference to an array of strings which are valid
  306                 answers (works like std_num_str_cmp() )
  307     zeroLevel   --  if the correct answer is this close to zero,
  308                  then zeroLevelTol applies
  309     zeroLevelTol  --  absolute tolerance to allow when answer is close
  310                  to zero
  311 
  312     debug     --  if set to 1, provides verbose listing of
  313                 hash entries throughout fliters.
  314 
  315   Returns an answer evaluator, or (if given a reference to an array of
  316   answers), a list of answer evaluators. Note that a reference to an array of
  317   answers results is just a shortcut for writing a separate <code>num_cmp()</code> for each
  318   answer.
  319 
  320 EXAMPLES:
  321 
  322   num_cmp( 5 )          --  correct answer is 5, using defaults
  323                   for all options
  324   num_cmp( [5,6,7] )        --  correct answers are 5, 6, and 7,
  325                   using defaults for all options
  326   num_cmp( 5, mode => 'strict' )  --  correct answer is 5, mode is strict
  327   num_cmp( [5,6], relTol => 5 ) --  correct answers are 5 and 6,
  328                     both with 5% relative tolerance
  329   num_cmp( 6, strings => ["Inf", "Minf", "NaN"] )
  330                   --  correct answer is 6, "Inf", "Minf",
  331                    and "NaN" recognized as valid, but
  332                    incorrect answers.
  333   num_cmp( "-INF", strings => ["INF", "-INF"] )
  334                   --  correct answer is "-INF", "INF" and
  335                    numerical expressions recognized as valid,
  336                    but incorrect answers.
  337 
  338 
  339 =cut
  340 
  341 sub num_cmp {
  342   my $correctAnswer = shift @_;
  343   $CA = $correctAnswer;
  344   my @opt = @_;
  345   my %out_options;
  346 
  347 #########################################################################
  348 # Retain this first check for backword compatibility.  Allows input of the form
  349 # num_cmp($ans, 1, '%0.5f') but warns against it
  350 #########################################################################
  351   my %known_options = (
  352           'mode'      =>  'std',
  353           'format'    =>  $numFormatDefault,
  354           'tol'     =>  $numAbsTolDefault,
  355           'relTol'    =>  $numRelPercentTolDefault,
  356           'units'     =>  undef,
  357           'strings'   =>  undef,
  358           'zeroLevel'   =>  $numZeroLevelDefault,
  359           'zeroLevelTol'  =>  $numZeroLevelTolDefault,
  360           'tolType'       =>  'relative',
  361           'tolerance'     =>  1,
  362           'reltol'    =>  undef,      #alternate spelling
  363           'unit'      =>  undef,      #alternate spelling
  364           'debug'     =>  0
  365         );
  366 
  367   my @output_list;
  368   my( $relPercentTol, $format, $zeroLevel, $zeroLevelTol) = @opt;
  369 
  370   unless( ref($correctAnswer) eq 'ARRAY' || scalar( @opt ) == 0 ||
  371         ( defined($opt[0]) and exists $known_options{$opt[0]} ) ) {
  372     # unless the first parameter is a list of arrays
  373     # or the second parameter is a known option or
  374     # no options were used,
  375     # use the old num_cmp which does not use options, but has inputs
  376     # $relPercentTol,$format,$zeroLevel,$zeroLevelTol
  377     warn "This method of using num_cmp() is deprecated. Please rewrite this" .
  378           " problem using the options style of parameter passing (or" .
  379           " check that your first option is spelled correctly).";
  380 
  381     %out_options = (  'relTol'    => $relPercentTol,
  382           'format'    => $format,
  383           'zeroLevel'   => $zeroLevel,
  384           'zeroLevelTol'  => $zeroLevelTol,
  385           'mode'      => 'std'
  386     );
  387   }
  388 
  389 #########################################################################
  390 # Now handle the options assuming they are entered in the form
  391 # num_cmp($ans, relTol=>1, format=>'%0.5f')
  392 #########################################################################
  393   %out_options = @opt;
  394   assign_option_aliases( \%out_options,
  395         'reltol'    =>      'relTol',
  396         'unit'      =>      'units',
  397         'abstol'  =>    'tol',
  398         );
  399 
  400   set_default_options( \%out_options,
  401            'tolType'    =>  (defined($out_options{'tol'}) ) ? 'absolute' : 'relative',  # the existence of "tol" means that we use absolute tolerance mode
  402            'tolerance'    =>  (defined($out_options{'tolType'}) && $out_options{'tolType'} eq 'absolute' ) ? $numAbsTolDefault : $numRelPercentTolDefault,  # relative tolerance is the default
  403            'mode'       =>  'std',
  404            'format'   =>  $numFormatDefault,
  405            'tol'        =>  undef,
  406            'relTol'   =>  undef,
  407            'units'    =>  undef,
  408            'strings'    =>  undef,
  409            'zeroLevel'  =>  $numZeroLevelDefault,
  410            'zeroLevelTol' =>  $numZeroLevelTolDefault,
  411            'debug'    =>  0,
  412   );
  413 
  414   # can't use both units and strings
  415   if( defined( $out_options{'units'} ) && defined( $out_options{'strings'} ) ) {
  416     warn "Can't use both 'units' and 'strings' in the same problem " .
  417     "(check your parameters to num_cmp() )";
  418   }
  419 
  420   # absolute tolType and relTol are incompatible. So are relative tolType and tol
  421   if( defined( $out_options{'relTol'} ) &&  $out_options{'tolType'} eq 'absolute' )  {
  422     warn "The 'tolType' 'absolute' is not compatible with 'relTol' " .
  423     "(check your parameters to num_cmp() )";
  424   }
  425   if( defined( $out_options{'tol'} ) &&  $out_options{'tolType'} eq 'relative' )  {
  426     warn "The 'tolType' 'relative' is not compatible with 'tol' " .
  427     "(check your parameters to num_cmp() )";
  428   }
  429 
  430 
  431   # Handle legacy options
  432     if ($out_options{tolType} eq 'absolute')   {
  433     $out_options{'tolerance'}=$out_options{'tol'} if defined($out_options{'tol'});
  434     delete($out_options{'relTol'}) if exists( $out_options{'relTol'} );
  435   } else {
  436     $out_options{'tolerance'}=$out_options{'relTol'} if defined($out_options{'relTol'});
  437     # delete($out_options{'tol'}) if exists( $out_options{'tol'} );
  438   }
  439   # end legacy options
  440 
  441   # thread over lists
  442   my @ans_list = ();
  443 
  444   if ( ref($correctAnswer) eq 'ARRAY' ) {
  445     @ans_list = @{$correctAnswer};
  446   }
  447   else { push( @ans_list, $correctAnswer );
  448   }
  449 
  450   # produce answer evaluators
  451   foreach my $ans (@ans_list) {
  452     if( defined( $out_options{'units'} ) ) {
  453       $ans = "$ans $out_options{'units'}";
  454 
  455       push( @output_list, NUM_CMP(  'correctAnswer'       =>  $ans,
  456               'tolerance'   =>  $out_options{'tolerance'},
  457               'tolType'   =>  $out_options{'tolType'},
  458               'format'    =>  $out_options{'format'},
  459               'mode'      =>  $out_options{'mode'},
  460               'zeroLevel'   =>  $out_options{'zeroLevel'},
  461               'zeroLevelTol'  =>  $out_options{'zeroLevelTol'},
  462               'debug'     =>  $out_options{'debug'},
  463               'units'     =>  $out_options{'units'},
  464             )
  465       );
  466     } elsif( defined( $out_options{'strings'} ) ) {
  467 
  468 
  469       push( @output_list, NUM_CMP(  'correctAnswer' =>  $ans,
  470               'tolerance' =>  $out_options{tolerance},
  471               'tolType' =>  $out_options{tolType},
  472               'format'  =>  $out_options{'format'},
  473               'mode'    =>  $out_options{'mode'},
  474               'zeroLevel' =>  $out_options{'zeroLevel'},
  475               'zeroLevelTol'  =>  $out_options{'zeroLevelTol'},
  476               'debug'   =>  $out_options{'debug'},
  477               'strings' =>  $out_options{'strings'},
  478          )
  479          );
  480     } else {
  481       push(@output_list,
  482         NUM_CMP(  'correctAnswer'       =>  $ans,
  483           'tolerance'   =>  $out_options{tolerance},
  484           'tolType'   =>  $out_options{tolType},
  485           'format'    =>  $out_options{'format'},
  486           'mode'      =>  $out_options{'mode'},
  487           'zeroLevel'   =>  $out_options{'zeroLevel'},
  488           'zeroLevelTol'        =>  $out_options{'zeroLevelTol'},
  489           'debug'     =>  $out_options{'debug'},
  490         ),
  491       );
  492       }
  493   }
  494 
  495   return (wantarray) ? @output_list : $output_list[0];
  496 }
  497 
  498 #legacy code for compatability purposes
  499 sub num_rel_cmp {   # compare numbers
  500     std_num_cmp( @_ );
  501 }
  502 
  503 
  504 =head3 "mode"_num_cmp() functions
  505 
  506 There are 16 functions total, 4 for each mode (std, frac, strict, arith). Each mode has
  507 one "normal" function, one which accepts a list of answers, one which uses absolute
  508 rather than relative tolerance, and one which uses absolute tolerance and accepts a list.
  509 The "std" family is documented below; all others work precisely the same.
  510 
  511  std_num_cmp($correctAnswer) OR
  512  std_num_cmp($correctAnswer, $relPercentTol) OR
  513  std_num_cmp($correctAnswer, $relPercentTol, $format) OR
  514  std_num_cmp($correctAnswer, $relPercentTol, $format, $zeroLevel) OR
  515  std_num_cmp($correctAnswer, $relPercentTol, $format, $zeroLevel, $zeroLevelTol)
  516 
  517   $correctAnswer  --  the correct answer
  518   $relPercentTol  --  the tolerance, as a percentage (optional)
  519   $format   --  the format of the displayed answer (optional)
  520   $zeroLevel  --  if the correct answer is this close to zero, then zeroLevelTol applies (optional)
  521   $zeroLevelTol --  absolute tolerance to allow when correct answer is close to zero (optional)
  522 
  523   std_num_cmp() uses standard mode (arithmetic operations and elementary
  524   functions allowed) and relative tolerance. Options are specified by
  525   one or more parameters. Note that if you wish to set an option which
  526   is later in the parameter list, you must set all previous options.
  527 
  528  std_num_cmp_abs($correctAnswer) OR
  529  std_num_cmp_abs($correctAnswer, $absTol) OR
  530  std_num_cmp_abs($correctAnswer, $absTol, $format)
  531 
  532   $correctAnswer    --  the correct answer
  533   $absTol     --  an absolute tolerance (optional)
  534   $format     --  the format of the displayed answer (optional)
  535 
  536   std_num_cmp_abs() uses standard mode and absolute tolerance. Options
  537   are set as with std_num_cmp(). Note that $zeroLevel and $zeroLevelTol
  538   do not apply with absolute tolerance.
  539 
  540  std_num_cmp_list($relPercentTol, $format, @answerList)
  541 
  542   $relPercentTol    --  the tolerance, as a percentage
  543   $format     --  the format of the displayed answer(s)
  544   @answerList   --  a list of one or more correct answers
  545 
  546   std_num_cmp_list() uses standard mode and relative tolerance. There
  547   is no way to set $zeroLevel or $zeroLevelTol. Note that no
  548   parameters are optional. All answers in the list will be
  549   evaluated with the same set of parameters.
  550 
  551  std_num_cmp_abs_list($absTol, $format, @answerList)
  552 
  553   $absTol   --  an absolute tolerance
  554   $format   --  the format of the displayed answer(s)
  555   @answerList --  a list of one or more correct answers
  556 
  557   std_num_cmp_abs_list() uses standard mode and absolute tolerance.
  558   Note that no parameters are optional. All answers in the list will be
  559   evaluated with the same set of parameters.
  560 
  561  arith_num_cmp(), arith_num_cmp_list(), arith_num_cmp_abs(), arith_num_cmp_abs_list()
  562  strict_num_cmp(), strict_num_cmp_list(), strict_num_cmp_abs(), strict_num_cmp_abs_list()
  563  frac_num_cmp(), frac_num_cmp_list(), frac_num_cmp_abs(), frac_num_cmp_abs_list()
  564 
  565 Examples:
  566 
  567   ANS( strict_num_cmp( 3.14159 ) )  --  The student answer must be a number
  568     in decimal or scientific notation which is within .1 percent of 3.14159.
  569     This assumes $numRelPercentTolDefault has been set to .1.
  570   ANS( strict_num_cmp( $answer, .01 ) ) --  The student answer must be a
  571     number within .01 percent of $answer (e.g. 3.14159 if $answer is 3.14159
  572     or $answer is "pi" or $answer is 4*atan(1)).
  573   ANS( frac_num_cmp( $answer) ) or ANS( frac_num_cmp( $answer,.01 ))  --
  574     The student answer can be a number or fraction, e.g. 2/3.
  575   ANS( arith_num_cmp( $answer) ) or ANS( arith_num_cmp( $answer,.01 ))  --
  576     The student answer can be an arithmetic expression, e.g. (2+3)/7-2^.5 .
  577   ANS( std_num_cmp( $answer) ) or ANS( std_num_cmp( $answer,.01 ))  --
  578     The student answer can contain elementary functions, e.g. sin(.3+pi/2)
  579 
  580 =cut
  581 
  582 sub std_num_cmp {           # compare numbers allowing use of elementary functions
  583     my ( $correctAnswer, $relPercentTol, $format, $zeroLevel, $zeroLevelTol ) = @_;
  584 
  585   my %options = ( 'relTol'        =>  $relPercentTol,
  586             'format'    =>  $format,
  587             'zeroLevel'   =>  $zeroLevel,
  588             'zeroLevelTol'  =>  $zeroLevelTol
  589     );
  590 
  591     set_default_options( \%options,
  592        'tolType'      =>  'relative',
  593        'tolerance'    =>  $numRelPercentTolDefault,
  594        'mode'       =>  'std',
  595        'format'     =>  $numFormatDefault,
  596        'relTol'     =>  $numRelPercentTolDefault,
  597        'zeroLevel'    =>  $numZeroLevelDefault,
  598        'zeroLevelTol' =>  $numZeroLevelTolDefault,
  599        'debug'        =>  0,
  600     );
  601 
  602     num_cmp([$correctAnswer], %options);
  603 }
  604 
  605 ##  Similar to std_num_cmp but accepts a list of numbers in the form
  606 ##  std_num_cmp_list(relpercentTol,format,ans1,ans2,ans3,...)
  607 ##  format is of the form "%10.3g" or "", i.e., a format suitable for sprintf(). Use "" for default
  608 ##  You must enter a format and tolerance
  609 
  610 sub std_num_cmp_list {
  611   my ( $relPercentTol, $format, @answerList) = @_;
  612 
  613   my %options = ( 'relTol'  =>      $relPercentTol,
  614       'format'        =>      $format,
  615   );
  616 
  617   set_default_options( \%options,
  618            'tolType'      =>      'relative',
  619            'tolerance'    =>      $numRelPercentTolDefault,
  620            'mode'         =>      'std',
  621            'format'       =>      $numFormatDefault,
  622            'relTol'       =>      $numRelPercentTolDefault,
  623            'zeroLevel'    =>      $numZeroLevelDefault,
  624            'zeroLevelTol' =>      $numZeroLevelTolDefault,
  625            'debug'        =>      0,
  626   );
  627 
  628   num_cmp(\@answerList, %options);
  629 
  630 }
  631 
  632 sub std_num_cmp_abs {     # compare numbers allowing use of elementary functions with absolute tolerance
  633   my ( $correctAnswer, $absTol, $format) = @_;
  634   my %options = ( 'tolerance'  => $absTol,
  635             'format'     => $format
  636   );
  637 
  638   set_default_options (\%options,
  639            'tolType'      =>      'absolute',
  640            'tolerance'    =>      $absTol,
  641            'mode'         =>      'std',
  642            'format'       =>      $numFormatDefault,
  643            'zeroLevel'    =>      0,
  644            'zeroLevelTol' =>      0,
  645            'debug'        =>      0,
  646   );
  647 
  648   num_cmp([$correctAnswer], %options);
  649 }
  650 
  651 ##  See std_num_cmp_list for usage
  652 
  653 sub std_num_cmp_abs_list {
  654   my ( $absTol, $format, @answerList ) = @_;
  655 
  656         my %options = ( 'tolerance'         =>      $absTol,
  657                         'format'            =>      $format,
  658   );
  659 
  660         set_default_options( \%options,
  661                              'tolType'      =>      'absolute',
  662                              'tolerance'    =>      $absTol,
  663                              'mode'         =>      'std',
  664                              'format'       =>      $numFormatDefault,
  665                              'zeroLevel'    =>      0,
  666                              'zeroLevelTol' =>      0,
  667                              'debug'        =>      0,
  668         );
  669 
  670         num_cmp(\@answerList, %options);
  671 }
  672 
  673 sub frac_num_cmp {            # only allow fractions and numbers as submitted answer
  674 
  675   my ( $correctAnswer, $relPercentTol, $format, $zeroLevel, $zeroLevelTol ) = @_;
  676 
  677   my %options = ( 'relTol'   =>   $relPercentTol,
  678           'format'     =>   $format,
  679           'zeroLevel'  =>   $zeroLevel,
  680           'zeroLevelTol'   =>   $zeroLevelTol
  681   );
  682 
  683   set_default_options( \%options,
  684          'tolType'     =>   'relative',
  685          'tolerance'   =>   $relPercentTol,
  686          'mode'      =>   'frac',
  687          'format'    =>   $numFormatDefault,
  688          'zeroLevel'   =>   $numZeroLevelDefault,
  689          'zeroLevelTol'  =>   $numZeroLevelTolDefault,
  690          'relTol'    =>   $numRelPercentTolDefault,
  691          'debug'     =>   0,
  692    );
  693 
  694   num_cmp([$correctAnswer], %options);
  695 }
  696 
  697 ##  See std_num_cmp_list for usage
  698 sub frac_num_cmp_list {
  699   my ( $relPercentTol, $format, @answerList ) = @_;
  700 
  701   my %options = (      'relTol'  =>   $relPercentTol,
  702                'format'    =>   $format
  703   );
  704 
  705   set_default_options( \%options,
  706        'tolType'     =>   'relative',
  707        'tolerance'   =>   $relPercentTol,
  708        'mode'      =>   'frac',
  709        'format'    =>   $numFormatDefault,
  710        'zeroLevel'   =>   $numZeroLevelDefault,
  711        'zeroLevelTol'  =>   $numZeroLevelTolDefault,
  712        'relTol'    =>   $numRelPercentTolDefault,
  713        'debug'     =>   0,
  714   );
  715 
  716   num_cmp(\@answerList, %options);
  717 }
  718 
  719 sub frac_num_cmp_abs {      # only allow fraction expressions as submitted answer with absolute tolerance
  720     my ( $correctAnswer, $absTol, $format ) = @_;
  721 
  722     my %options = (             'tolerance'    =>     $absTol,
  723               'format'       =>     $format
  724     );
  725 
  726   set_default_options (\%options,
  727       'tolType'    =>   'absolute',
  728       'tolerance'    =>   $absTol,
  729       'mode'       =>   'frac',
  730       'format'     =>   $numFormatDefault,
  731       'zeroLevel'    =>   0,
  732       'zeroLevelTol' =>   0,
  733       'debug'      =>   0,
  734   );
  735 
  736     num_cmp([$correctAnswer], %options);
  737 }
  738 
  739 ##  See std_num_cmp_list for usage
  740 
  741 sub frac_num_cmp_abs_list {
  742     my ( $absTol, $format, @answerList ) = @_;
  743 
  744     my %options = (             'tolerance'    =>     $absTol,
  745               'format'       =>     $format
  746     );
  747 
  748     set_default_options (\%options,
  749        'tolType'      =>     'absolute',
  750        'tolerance'    =>     $absTol,
  751        'mode'         =>     'frac',
  752        'format'       =>     $numFormatDefault,
  753        'zeroLevel'    =>     0,
  754        'zeroLevelTol' =>     0,
  755        'debug'        =>     0,
  756     );
  757 
  758     num_cmp(\@answerList, %options);
  759 }
  760 
  761 
  762 sub arith_num_cmp {           # only allow arithmetic expressions as submitted answer
  763 
  764     my ( $correctAnswer, $relPercentTol, $format, $zeroLevel, $zeroLevelTol ) = @_;
  765 
  766     my %options = (     'relTol'      =>     $relPercentTol,
  767       'format'         =>     $format,
  768       'zeroLevel'      =>     $zeroLevel,
  769       'zeroLevelTol'   =>     $zeroLevelTol
  770     );
  771 
  772     set_default_options( \%options,
  773                         'tolType'       =>     'relative',
  774                         'tolerance'     =>     $relPercentTol,
  775                         'mode'          =>     'arith',
  776                         'format'        =>     $numFormatDefault,
  777                         'zeroLevel'     =>     $numZeroLevelDefault,
  778                         'zeroLevelTol'  =>     $numZeroLevelTolDefault,
  779                         'relTol'        =>     $numRelPercentTolDefault,
  780                         'debug'         =>     0,
  781     );
  782 
  783     num_cmp([$correctAnswer], %options);
  784 }
  785 
  786 ##  See std_num_cmp_list for usage
  787 sub arith_num_cmp_list {
  788     my ( $relPercentTol, $format, @answerList ) = @_;
  789 
  790     my %options = (     'relTol'     =>     $relPercentTol,
  791                         'format'        =>     $format,
  792     );
  793 
  794     set_default_options( \%options,
  795                          'tolType'       =>     'relative',
  796                          'tolerance'     =>     $relPercentTol,
  797                          'mode'          =>     'arith',
  798                          'format'        =>     $numFormatDefault,
  799                          'zeroLevel'     =>     $numZeroLevelDefault,
  800                          'zeroLevelTol'  =>     $numZeroLevelTolDefault,
  801                          'relTol'        =>     $numRelPercentTolDefault,
  802                          'debug'         =>     0,
  803     );
  804 
  805     num_cmp(\@answerList, %options);
  806 }
  807 
  808 sub arith_num_cmp_abs {     # only allow arithmetic expressions as submitted answer with absolute tolerance
  809     my ( $correctAnswer, $absTol, $format ) = @_;
  810 
  811     my %options = (      'tolerance'    =>     $absTol,
  812                          'format'       =>     $format
  813     );
  814 
  815     set_default_options (\%options,
  816                          'tolType'      =>     'absolute',
  817                          'tolerance'    =>     $absTol,
  818                          'mode'         =>     'arith',
  819                          'format'       =>     $numFormatDefault,
  820                          'zeroLevel'    =>     0,
  821                          'zeroLevelTol' =>     0,
  822                          'debug'        =>     0,
  823     );
  824 
  825     num_cmp([$correctAnswer], %options);
  826 }
  827 
  828 ##  See std_num_cmp_list for usage
  829 sub arith_num_cmp_abs_list {
  830     my ( $absTol, $format, @answerList ) = @_;
  831 
  832     my %options = (      'tolerance'    =>     $absTol,
  833                          'format'       =>     $format
  834     );
  835 
  836     set_default_options (\%options,
  837                          'tolType'      =>     'absolute',
  838                          'tolerance'    =>     $absTol,
  839                          'mode'         =>     'arith',
  840                          'format'       =>     $numFormatDefault,
  841                          'zeroLevel'    =>     0,
  842                          'zeroLevelTol' =>     0,
  843                          'debug'        =>     0,
  844     );
  845 
  846     num_cmp(\@answerList, %options);
  847 }
  848 
  849 sub strict_num_cmp {          # only allow numbers as submitted answer
  850     my ( $correctAnswer, $relPercentTol, $format, $zeroLevel, $zeroLevelTol ) = @_;
  851 
  852     my %options = (      'relTol'     =>     $relPercentTol,
  853                          'format'        =>     $format,
  854                          'zeroLevel'     =>     $zeroLevel,
  855                          'zeroLevelTol'  =>     $zeroLevelTol
  856     );
  857 
  858     set_default_options( \%options,
  859                          'tolType'       =>     'relative',
  860                          'tolerance'     =>     $relPercentTol,
  861                          'mode'          =>     'strict',
  862                          'format'        =>     $numFormatDefault,
  863                          'zeroLevel'     =>     $numZeroLevelDefault,
  864                          'zeroLevelTol'  =>     $numZeroLevelTolDefault,
  865                          'relTol'        =>     $numRelPercentTolDefault,
  866                          'debug'         =>     0,
  867     );
  868     num_cmp([$correctAnswer], %options);
  869 
  870 }
  871 
  872 ##  See std_num_cmp_list for usage
  873 sub strict_num_cmp_list {       # compare numbers
  874     my ( $relPercentTol, $format, @answerList ) = @_;
  875 
  876     my %options = (    'relTol'     =>     $relPercentTol,
  877        'format'        =>     $format,
  878     );
  879 
  880     set_default_options( \%options,
  881                          'tolType'       =>     'relative',
  882                          'tolerance'     =>     $relPercentTol,
  883                          'mode'          =>     'strict',
  884                          'format'        =>     $numFormatDefault,
  885                          'zeroLevel'     =>     $numZeroLevelDefault,
  886                          'zeroLevelTol'  =>     $numZeroLevelTolDefault,
  887                          'relTol'        =>     $numRelPercentTolDefault,
  888                          'debug'         =>     0,
  889     );
  890 
  891     num_cmp(\@answerList, %options);
  892 }
  893 
  894 
  895 sub strict_num_cmp_abs {        # only allow numbers as submitted answer with absolute tolerance
  896     my ( $correctAnswer, $absTol, $format ) = @_;
  897 
  898     my %options = (       'tolerance'    =>     $absTol,
  899                     'format'       =>     $format
  900     );
  901 
  902     set_default_options (\%options,
  903                          'tolType'      =>     'absolute',
  904                          'tolerance'    =>     $absTol,
  905                          'mode'         =>     'strict',
  906                          'format'       =>     $numFormatDefault,
  907                          'zeroLevel'    =>     0,
  908                          'zeroLevelTol' =>     0,
  909                          'debug'        =>     0,
  910     );
  911     num_cmp([$correctAnswer], %options);
  912 
  913 }
  914 
  915 ##  See std_num_cmp_list for usage
  916 sub strict_num_cmp_abs_list {     # compare numbers
  917     my ( $absTol, $format, @answerList ) = @_;
  918 
  919     my %options = (      'tolerance'    =>     $absTol,
  920                          'format'       =>     $format
  921     );
  922 
  923     set_default_options (\%options,
  924                          'tolType'      =>     'absolute',
  925                          'tolerance'    =>     $absTol,
  926                          'mode'         =>     'strict',
  927                          'format'       =>     $numFormatDefault,
  928                          'zeroLevel'    =>     0,
  929                          'zeroLevelTol' =>     0,
  930                          'debug'        =>     0,
  931     );
  932 
  933     num_cmp(\@answerList, %options);
  934 }
  935 
  936 ## sub numerical_compare_with_units
  937 ## Compares a number with units
  938 ## Deprecated; use num_cmp()
  939 ##
  940 ## IN:  a string which includes the numerical answer and the units
  941 ##    a hash with the following keys (all optional):
  942 ##      mode    --  'std', 'frac', 'arith', or 'strict'
  943 ##      format    --  the format to use when displaying the answer
  944 ##      tol   --  an absolute tolerance, or
  945 ##      relTol    --  a relative tolerance
  946 ##      zeroLevel --  if the correct answer is this close to zero, then zeroLevelTol applies
  947 ##      zeroLevelTol  --  absolute tolerance to allow when correct answer is close to zero
  948 
  949 # This mode is depricated.  send input through num_cmp -- it can handle units.
  950 
  951 sub numerical_compare_with_units {
  952   my $correct_answer = shift;  # the answer is a string which includes both the numerical answer and the units.
  953   my %options = @_;    # all of the other inputs are (key value) pairs
  954 
  955   # Prepare the correct answer
  956   $correct_answer = str_filters( $correct_answer, 'trim_whitespace' );
  957 
  958   # it surprises me that the match below works since the first .* is greedy.
  959   my ($correct_num_answer, $correct_units) = $correct_answer =~ /^(.*)\s+([^\s]*)$/;
  960   $options{units} = $correct_units;
  961 
  962   num_cmp($correct_num_answer, %options);
  963 }
  964 
  965 
  966 =head3 std_num_str_cmp()
  967 
  968 NOTE: This function is maintained for compatibility. num_cmp() with the
  969     'strings' parameter is slightly preferred.
  970 
  971 std_num_str_cmp() is used when the correct answer could be either a number or a
  972 string. For example, if you wanted the student to evaluate a function at number
  973 of points, but write "Inf" or "Minf" if the function is unbounded. This routine
  974 will provide error messages that do not give a hint as to whether the correct
  975 answer is a string or a number. For numerical comparisons, std_num_cmp() is
  976 used internally; for string comparisons, std_str_cmp() is used.  String answers
  977 must consist entirely of letters except that an initial minus sign is allowed.
  978 E.g. "inf" and "-inf" are valid strings where as "too-big" is not.
  979 
  980  std_num_str_cmp( $correctAnswer ) OR
  981  std_num_str_cmp( $correctAnswer, $ra_legalStrings ) OR
  982  std_num_str_cmp( $correctAnswer, $ra_legalStrings, $relPercentTol ) OR
  983  std_num_str_cmp( $correctAnswer, $ra_legalStrings, $relPercentTol, $format ) OR
  984  std_num_str_cmp( $correctAnswer, $ra_legalStrings, $relPercentTol, $format, $zeroLevel ) OR
  985  std_num_str_cmp( $correctAnswer, $ra_legalStrings, $relPercentTol, $format,
  986           $zeroLevel, $zeroLevelTol )
  987 
  988   $correctAnswer    --  the correct answer
  989   $ra_legalStrings  --  a reference to an array of legal strings, e.g. ["str1", "str2"]
  990   $relPercentTol    --  the error tolerance as a percentage
  991   $format     --  the display format
  992   $zeroLevel    --  if the correct answer is this close to zero, then zeroLevelTol applies
  993   $zeroLevelTol   --  absolute tolerance to allow when correct answer is close to zero
  994 
  995 Examples:
  996   ANS( std_num_str_cmp( $ans, ["Inf", "Minf", "NaN"] ) );
  997   ANS( std_num_str_cmp( $ans, ["INF", "-INF"] ) );
  998 
  999 =cut
 1000 
 1001 sub std_num_str_cmp {
 1002   my ( $correctAnswer, $ra_legalStrings, $relpercentTol, $format, $zeroLevel, $zeroLevelTol ) = @_;
 1003   # warn ('This method is depreciated.  Use num_cmp instead.');
 1004   return num_cmp ($correctAnswer, strings=>$ra_legalStrings, relTol=>$relpercentTol, format=>$format,
 1005     zeroLevel=>$zeroLevel, zeroLevelTol=>$zeroLevelTol);
 1006 }
 1007 
 1008 sub NUM_CMP {   # low level numeric compare
 1009   my %num_params = @_;
 1010 
 1011   my @keys = qw ( correctAnswer tolerance tolType format mode zeroLevel zeroLevelTol debug );
 1012   foreach my $key (@keys) {
 1013       warn "$key must be defined in options when calling NUM_CMP" unless defined ($num_params{$key});
 1014   }
 1015 
 1016   my $correctAnswer = $num_params{'correctAnswer'};
 1017   my $format        = $num_params{'format'};
 1018   my $mode        = $num_params{'mode'};
 1019 
 1020   if( $num_params{tolType} eq 'relative' ) {
 1021     $num_params{'tolerance'} = .01*$num_params{'tolerance'};
 1022   }
 1023 
 1024   my $formattedCorrectAnswer;
 1025   my $correct_units;
 1026   my $correct_num_answer;
 1027   my %correct_units;
 1028   my $corrAnswerIsString = 0;
 1029 
 1030 
 1031   if (defined($num_params{units}) && $num_params{units}) {
 1032     $correctAnswer  = str_filters( $correctAnswer, 'trim_whitespace' );
 1033             # units are in form stuff space units where units contains no spaces.
 1034 
 1035     ($correct_num_answer, $correct_units) = $correctAnswer =~ /^(.*)\s+([^\s]*)$/;
 1036     %correct_units = Units::evaluate_units($correct_units);
 1037     if ( defined( $correct_units{'ERROR'} ) ) {
 1038        warn ("ERROR: The answer \"$correctAnswer\" in the problem definition cannot be parsed:\n" .
 1039         "$correct_units{'ERROR'}\n");
 1040     }
 1041     # $formattedCorrectAnswer = spf($correct_num_answer,$num_params{'format'}) . " $correct_units";
 1042     $formattedCorrectAnswer = prfmt($correct_num_answer,$num_params{'format'}) . " $correct_units";
 1043 
 1044   } elsif (defined($num_params{strings}) && $num_params{strings}) {
 1045     my $legalString = '';
 1046     my @legalStrings = @{$num_params{strings}};
 1047     $correct_num_answer = $correctAnswer;
 1048     $formattedCorrectAnswer = $correctAnswer;
 1049     foreach $legalString (@legalStrings) {
 1050       if ( uc($correctAnswer) eq uc($legalString) ) {
 1051         $corrAnswerIsString = 1;
 1052 
 1053         last;
 1054       }
 1055     }     ## at this point $corrAnswerIsString = 0 iff correct answer is numeric
 1056   } else {
 1057     $correct_num_answer = $correctAnswer;
 1058     $formattedCorrectAnswer = prfmt( $correctAnswer, $num_params{'format'} );
 1059   }
 1060 
 1061   $correct_num_answer = math_constants($correct_num_answer);
 1062 
 1063   my $PGanswerMessage = '';
 1064 
 1065   my ($inVal,$correctVal,$PG_eval_errors,$PG_full_error_report);
 1066 
 1067   if (defined($correct_num_answer) && $correct_num_answer =~ /\S/ && $corrAnswerIsString == 0 ) {
 1068       ($correctVal, $PG_eval_errors,$PG_full_error_report) = PG_answer_eval($correct_num_answer);
 1069   } else { # case of a string answer
 1070     $PG_eval_errors = ' ';
 1071     $correctVal = $correctAnswer;
 1072   }
 1073 
 1074   if ( ($PG_eval_errors && $corrAnswerIsString == 0) or ((not is_a_number($correctVal)) && $corrAnswerIsString == 0)) {
 1075         ##error message from eval or above
 1076     warn "Error in 'correct' answer: $PG_eval_errors<br>
 1077           The answer $correctAnswer evaluates to $correctVal,
 1078           which cannot be interpreted as a number.  ";
 1079 
 1080   }
 1081   #########################################################################
 1082 
 1083   #construct the answer evaluator
 1084       my $answer_evaluator = new AnswerEvaluator;
 1085       $answer_evaluator->{debug} = $num_params{debug};
 1086       $answer_evaluator->ans_hash(
 1087                 correct_ans       =>  $correctVal,
 1088                 type          =>  "${mode}_number",
 1089                 tolerance       =>  $num_params{tolerance},
 1090               tolType         =>  $num_params{tolType},
 1091               units         =>  $correct_units,
 1092                 original_correct_ans  =>  $formattedCorrectAnswer,
 1093                 rh_correct_units    =>      \%correct_units,
 1094                 answerIsString      =>  $corrAnswerIsString,
 1095       );
 1096       my ($in, $formattedSubmittedAnswer);
 1097   $answer_evaluator->install_pre_filter(sub {my $rh_ans = shift;
 1098     $rh_ans->{original_student_ans} = $rh_ans->{student_ans}; $rh_ans;}
 1099   );
 1100   if (defined($num_params{units}) && $num_params{units}) {
 1101       $answer_evaluator->install_pre_filter(\&check_units);
 1102   }
 1103   if (defined($num_params{strings}) && $num_params{strings}) {
 1104       $answer_evaluator->install_pre_filter(\&check_strings, %num_params);
 1105   }
 1106 
 1107   $answer_evaluator->install_pre_filter(\&check_syntax);
 1108 
 1109   $answer_evaluator->install_pre_filter(\&math_constants);
 1110 
 1111   if ($mode eq 'std') {
 1112         # do nothing
 1113   } elsif ($mode eq 'strict') {
 1114     $answer_evaluator->install_pre_filter(\&is_a_number);
 1115   } elsif ($mode eq 'arith') {
 1116       $answer_evaluator->install_pre_filter(\&is_an_arithmetic_expression);
 1117     } elsif ($mode eq 'frac') {
 1118       $answer_evaluator->install_pre_filter(\&is_a_fraction);
 1119 
 1120     } elsif ($mode eq 'phase_pi') {
 1121       $answer_evaluator->install_pre_filter(\&phase_pi);
 1122 
 1123     } else {
 1124       $PGanswerMessage = 'Tell your professor that there is an error in his or her answer mechanism. No mode was specified.';
 1125       $formattedSubmittedAnswer = $in;
 1126     }
 1127 
 1128   if ($corrAnswerIsString == 0 ){   # avoiding running compare_numbers when correct answer is a string.
 1129     $answer_evaluator->install_evaluator(\&compare_numbers, %num_params);
 1130    }
 1131 
 1132 
 1133 ###############################################################################
 1134 # We'll leave these next lines out for now, so that the evaluated versions of the student's and professor's
 1135 # can be displayed in the answer message.  This may still cause a few anomolies when strings are used
 1136 #
 1137 ###############################################################################
 1138 
 1139   $answer_evaluator->install_post_filter(\&fix_answers_for_display);
 1140 
 1141       $answer_evaluator->install_post_filter(sub {my $rh_ans = shift;
 1142           return $rh_ans unless $rh_ans->catch_error('EVAL');
 1143           $rh_ans->{student_ans} = $rh_ans->{original_student_ans}. ' '. $rh_ans->{error_message};
 1144           $rh_ans->clear_error('EVAL'); } );
 1145       $answer_evaluator->install_post_filter(sub {my $rh_ans = shift; $rh_ans->clear_error('SYNTAX'); } );
 1146       $answer_evaluator->install_post_filter(sub {my $rh_ans = shift; $rh_ans->clear_error('UNITS'); } );
 1147       $answer_evaluator->install_post_filter(sub {my $rh_ans = shift; $rh_ans->clear_error('NUMBER'); } );
 1148   $answer_evaluator->install_post_filter(sub {my $rh_ans = shift; $rh_ans->clear_error('STRING'); } );
 1149       $answer_evaluator;
 1150 }
 1151 
 1152 
 1153 
 1154 ##########################################################################
 1155 ##########################################################################
 1156 ## Function answer evaluators
 1157 
 1158 =head2 Function Answer Evaluators
 1159 
 1160 Function answer evaluators take in a function, compare it numerically to a
 1161 correct function, and return a score. They can require an exactly equivalent
 1162 function, or one that is equal up to a constant. They can accept or reject an
 1163 answer based on specified tolerances for numerical deviation.
 1164 
 1165 Function Comparison Options
 1166 
 1167   correctEqn  --  The correct equation, specified as a string. It may include
 1168           all basic arithmetic operations, as well as elementary
 1169           functions. Variable usage is described below.
 1170 
 1171   Variables --  The independent variable(s). When comparing the correct
 1172           equation to the student equation, each variable will be
 1173           replaced by a certain number of numerical values. If
 1174           the student equation agrees numerically with the correct
 1175           equation, they are considered equal. Note that all
 1176           comparison is numeric; it is possible (although highly
 1177           unlikely and never a practical concern) for two unequal
 1178           functions to yield the same numerical results.
 1179 
 1180   Limits    --  The limits of evaluation for the independent variables.
 1181           Each variable is evaluated only in the half-open interval
 1182           [lower_limit, upper_limit). This is useful if the function
 1183           has a singularity or is not defined in a certain range.
 1184           For example, the function "sqrt(-1-x)" could be evaluated
 1185           in [-2,-1).
 1186 
 1187   Tolerance --  Tolerance in function comparisons works exactly as in
 1188           numerical comparisons; see the numerical comparison
 1189           documentation for a complete description. Note that the
 1190           tolerance does applies to the function as a whole, not
 1191           each point individually.
 1192 
 1193   Number of --  Specifies how many points to evaluate each variable at. This
 1194   Points      is typically 3, but can be set higher if it is felt that
 1195           there is a strong possibility of "false positives."
 1196 
 1197   Maximum   --  Sets the maximum size of the constant of integration. For
 1198   Constant of   technical reasons concerning floating point arithmetic, if
 1199   Integration   the additive constant, i.e., the constant of integration, is
 1200           greater (in absolute value) than maxConstantOfIntegration
 1201           AND is greater than maxConstantOfIntegration times the
 1202           correct value, WeBWorK will give an error message saying
 1203           that it can not handle such a large constant of integration.
 1204           This is to prevent e.g. cos(x) + 1E20 or even 1E20 as being
 1205           accepted as a correct antiderivatives of sin(x) since
 1206           floating point arithmetic cannot tell the difference
 1207           between cos(x) + 1E20, 1E20, and -cos(x) + 1E20.
 1208 
 1209 Technical note: if you examine the code for the function routines, you will see
 1210 that most subroutines are simply doing some basic error-checking and then
 1211 passing the parameters on to the low-level FUNCTION_CMP(). Because this routine
 1212 is set up to handle multivariable functions, with single-variable functions as
 1213 a special case, it is possible to pass multivariable parameters to single-
 1214 variable functions. This usage is strongly discouraged as unnecessarily
 1215 confusing. Avoid it.
 1216 
 1217 Default Values (As of 7/24/2000) (Option -- Variable Name -- Value)
 1218 
 1219   Variable      --  $functVarDefault      --  'x'
 1220   Relative Tolerance    --  $functRelPercentTolDefault    --  .1
 1221   Absolute Tolerance    --  $functAbsTolDefault     --  .001
 1222   Lower Limit     --  $functLLimitDefault     --  .0000001
 1223   Upper Limit     --  $functULimitDefault     --  1
 1224   Number of Points    --  $functNumOfPoints     --  3
 1225   Zero Level      --  $functZeroLevelDefault      --  1E-14
 1226   Zero Level Tolerance    --  $functZeroLevelTolDefault   --  1E-12
 1227   Maximum Constant    --  $functMaxConstantOfIntegration    --  1E8
 1228     of Integration
 1229 
 1230 =cut
 1231 
 1232 
 1233 
 1234 =head3 fun_cmp()
 1235 
 1236 Compares a function or a list of functions, using a named hash of options to set
 1237 parameters. This can make for more readable code than using the function_cmp()
 1238 style, but some people find one or the other easier to remember.
 1239 
 1240 ANS( fun_cmp( answer or answer_array_ref, options_hash ) );
 1241 
 1242   1. a string containing the correct function, or a reference to an
 1243     array of correct functions
 1244   2. a hash containing the following items (all optional):
 1245     var           --  either the number of variables or a reference to an
 1246                       array of variable names (see below)
 1247     limits            --  reference to an array of arrays of limits (see below), or:
 1248     mode            --  'std' (default) (function must match exactly), or:
 1249                     'antider' (function must match up to a constant)
 1250     relTol            --  (default) a relative tolerance (as a percentage), or:
 1251     tol           --  an absolute tolerance for error
 1252     numPoints         --  the number of points to evaluate the function at
 1253     maxConstantOfIntegration      --  maximum size of the constant of integration
 1254     zeroLevel         --  if the correct answer is this close to zero, then
 1255                       zeroLevelTol applies
 1256     zeroLevelTol          --  absolute tolerance to allow when answer is close to zero
 1257     params                an array of "free" parameters which can be used to adapt
 1258                     the correct answer to the submitted answer. (e.g. ['c'] for
 1259                     a constant of integration in the answer x^3/3 + c.
 1260     debug           --  when set to 1 this provides extra information while checking the
 1261                         the answer.
 1262 
 1263   Returns an answer evaluator, or (if given a reference to an array
 1264   of answers), a list of answer evaluators
 1265 
 1266 ANSWER:
 1267 
 1268   The answer must be in the form of a string. The answer can contain
 1269   functions, pi, e, and arithmetic operations. However, the correct answer
 1270   string follows a slightly stricter syntax than student answers; specifically,
 1271   there is no implicit multiplication. So the correct answer must be "3*x" rather
 1272   than "3 x". Students can still enter "3 x".
 1273 
 1274 VARIABLES:
 1275 
 1276   The var parameter can contain either a number or a reference to an array of
 1277   variable names. If it contains a number, the variables are named automatically
 1278   as follows: 1 variable  --  x
 1279       2 variables --  x, y
 1280       3 variables --  x, y, z
 1281       4 or more --  x_1, x_2, x_3, etc.
 1282   If the var parameter contains a reference to an array of variable names, then
 1283   the number of variables is determined by the number of items in the array. A
 1284   reference to an array is created with brackets, e.g. "var => ['r', 's', 't']".
 1285   If only one variable is being used, you can write either "var => ['t']" for
 1286   consistency or "var => 't'" as a shortcut. The default is one variable, x.
 1287 
 1288 LIMITS:
 1289 
 1290   Limits are specified with the limits parameter. You may NOT use llimit/ulimit.
 1291   If you specify limits for one variable, you must specify them for all variables.
 1292   The limit parameter must be a reference to an array of arrays of the form
 1293   [lower_limit. upper_limit], each array corresponding to the lower and upper
 1294   endpoints of the (half-open) domain of one variable. For example,
 1295   "vars => 2, limits => [[0,2], [-3,8]]" would cause x to be evaluated in [0,2) and
 1296   y to be evaluated in [-3,8). If only one variable is being used, you can write
 1297   either "limits => [[0,3]]" for consistency or "limits => [0,3]" as a shortcut.
 1298 
 1299 EXAMPLES:
 1300 
 1301   fun_cmp( "3*x" )  --  standard compare, variable is x
 1302   fun_cmp( ["3*x", "4*x+3", "3*x**2"] ) --  standard compare, defaults used for all three functions
 1303   fun_cmp( "3*t", var => 't' )  --  standard compare, variable is t
 1304   fun_cmp( "5*x*y*z", var => 3 )  --  x, y and z are the variables
 1305   fun_cmp( "5*x", mode => 'antider' ) --  student answer must match up to constant (i.e., 5x+C)
 1306   fun_cmp( ["3*x*y", "4*x*y"], limits => [[0,2], [5,7]] ) --  x evaluated in [0,2)
 1307                                 y evaluated in [5,7)
 1308 
 1309 =cut
 1310 
 1311 sub fun_cmp {
 1312   my $correctAnswer = shift @_;
 1313   my %opt = @_;
 1314 
 1315     assign_option_aliases( \%opt,
 1316         'vars'    =>  'var',    # set the standard option 'var' to the one specified as vars
 1317           'domain'  =>  'limits', # set the standard option 'limits' to the one specified as domain
 1318           'reltol'    =>  'relTol',
 1319           'param'   =>  'params',
 1320     );
 1321 
 1322     set_default_options(  \%opt,
 1323         'var'         =>  $functVarDefault,
 1324             'params'        =>  [],
 1325         'limits'        =>  [[$functLLimitDefault, $functULimitDefault]],
 1326         'test_points'   => undef,
 1327         'mode'          =>  'std',
 1328         'tolType'       =>    (defined($opt{tol}) ) ? 'absolute' : 'relative',
 1329         'tol'         =>  .01, # default mode should be relative, to obtain this tol must not be defined
 1330             'relTol'        =>  $functRelPercentTolDefault,
 1331         'numPoints'       =>  $functNumOfPoints,
 1332         'maxConstantOfIntegration'  =>  $functMaxConstantOfIntegration,
 1333         'zeroLevel'       =>  $functZeroLevelDefault,
 1334         'zeroLevelTol'      =>  $functZeroLevelTolDefault,
 1335             'debug'         =>  0,
 1336      );
 1337 
 1338     # allow var => 'x' as an abbreviation for var => ['x']
 1339   my %out_options = %opt;
 1340   unless ( ref($out_options{var}) eq 'ARRAY' ) {
 1341     $out_options{var} = [$out_options{var}];
 1342   }
 1343   # allow params => 'c' as an abbreviation for params => ['c']
 1344   unless ( ref($out_options{params}) eq 'ARRAY' ) {
 1345     $out_options{params} = [$out_options{params}];
 1346   }
 1347   my ($tolType, $tol);
 1348     if ($out_options{tolType} eq 'absolute') {
 1349     $tolType = 'absolute';
 1350     $tol = $out_options{'tol'};
 1351     delete($out_options{'relTol'}) if exists( $out_options{'relTol'} );
 1352   } else {
 1353     $tolType = 'relative';
 1354     $tol = $out_options{'relTol'};
 1355     delete($out_options{'tol'}) if exists( $out_options{'tol'} );
 1356   }
 1357 
 1358   my @output_list = ();
 1359   # thread over lists
 1360   my @ans_list = ();
 1361 
 1362   if ( ref($correctAnswer) eq 'ARRAY' ) {
 1363     @ans_list = @{$correctAnswer};
 1364   }
 1365   else {
 1366     push( @ans_list, $correctAnswer );
 1367   }
 1368 
 1369   # produce answer evaluators
 1370   foreach my $ans (@ans_list) {
 1371     push(@output_list,
 1372       FUNCTION_CMP(
 1373           'correctEqn'    =>  $ans,
 1374           'var'       =>  $out_options{'var'},
 1375           'limits'      =>  $out_options{'limits'},
 1376           'tolerance'     =>  $tol,
 1377           'tolType'     =>  $tolType,
 1378           'numPoints'     =>  $out_options{'numPoints'},
 1379           'test_points' =>  $out_options{'test_points'},
 1380           'mode'        =>  $out_options{'mode'},
 1381           'maxConstantOfIntegration'  =>  $out_options{'maxConstantOfIntegration'},
 1382           'zeroLevel'     =>  $out_options{'zeroLevel'},
 1383           'zeroLevelTol'    =>  $out_options{'zeroLevelTol'},
 1384           'params'      =>  $out_options{'params'},
 1385           'debug'       =>  $out_options{'debug'},
 1386       ),
 1387     );
 1388   }
 1389 
 1390   return (wantarray) ? @output_list : $output_list[0];
 1391 }
 1392 
 1393 =head3 Single-variable Function Comparisons
 1394 
 1395 There are four single-variable function answer evaluators: "normal," absolute
 1396 tolerance, antiderivative, and antiderivative with absolute tolerance. All
 1397 parameters (other than the correct equation) are optional.
 1398 
 1399  function_cmp( $correctEqn ) OR
 1400  function_cmp( $correctEqn, $var ) OR
 1401  function_cmp( $correctEqn, $var, $llimit, $ulimit ) OR
 1402  function_cmp( $correctEqn, $var, $llimit, $ulimit, $relPercentTol ) OR
 1403  function_cmp( $correctEqn, $var, $llimit, $ulimit,
 1404         $relPercentTol, $numPoints ) OR
 1405  function_cmp( $correctEqn, $var, $llimit, $ulimit,
 1406         $relPercentTol, $numPoints, $zeroLevel ) OR
 1407  function_cmp( $correctEqn, $var, $llimit, $ulimit, $relPercentTol, $numPoints,
 1408         $zeroLevel,$zeroLevelTol )
 1409 
 1410   $correctEqn   --  the correct equation, as a string
 1411   $var      --  the string representing the variable (optional)
 1412   $llimit     --  the lower limit of the interval to evaluate the
 1413               variable in (optional)
 1414   $ulimit     --  the upper limit of the interval to evaluate the
 1415               variable in (optional)
 1416   $relPercentTol  --  the error tolerance as a percentage (optional)
 1417   $numPoints    --  the number of points at which to evaluate the
 1418               variable (optional)
 1419   $zeroLevel    --  if the correct answer is this close to zero, then
 1420               zeroLevelTol applies (optional)
 1421   $zeroLevelTol --  absolute tolerance to allow when answer is close to zero
 1422 
 1423   function_cmp() uses standard comparison and relative tolerance. It takes a
 1424   string representing a single-variable function and compares the student
 1425   answer to that function numerically.
 1426 
 1427  function_cmp_up_to_constant( $correctEqn ) OR
 1428  function_cmp_up_to_constant( $correctEqn, $var ) OR
 1429  function_cmp_up_to_constant( $correctEqn, $var, $llimit, $ulimit ) OR
 1430  function_cmp_up_to_constant( $correctEqn, $var, $llimit, $ulimit,
 1431                 $relpercentTol ) OR
 1432  function_cmp_up_to_constant( $correctEqn, $var, $llimit, $ulimit,
 1433                 $relpercentTol, $numOfPoints ) OR
 1434  function_cmp_up_to_constant( $correctEqn, $var, $llimit, $ulimit,
 1435                 $relpercentTol, $numOfPoints,
 1436                 $maxConstantOfIntegration ) OR
 1437  function_cmp_up_to_constant( $correctEqn, $var, $llimit, $ulimit,
 1438                 $relpercentTol, $numOfPoints,
 1439                 $maxConstantOfIntegration, $zeroLevel)  OR
 1440  function_cmp_up_to_constant( $correctEqn, $var, $llimit, $ulimit,
 1441                 $relpercentTol, $numOfPoints,
 1442                 $maxConstantOfIntegration,
 1443                 $zeroLevel, $zeroLevelTol )
 1444 
 1445   $maxConstantOfIntegration --  the maximum size of the constant of
 1446                   integration
 1447 
 1448   function_cmp_up_to_constant() uses antiderivative compare and relative
 1449   tolerance. All options work exactly like function_cmp(), except of course
 1450   $maxConstantOfIntegration. It will accept as correct any function which
 1451   differs from $correctEqn by at most a constant; that is, if
 1452     $studentEqn = $correctEqn + C
 1453   the answer is correct.
 1454 
 1455  function_cmp_abs( $correctFunction ) OR
 1456  function_cmp_abs( $correctFunction, $var ) OR
 1457  function_cmp_abs( $correctFunction, $var, $llimit, $ulimit ) OR
 1458  function_cmp_abs( $correctFunction, $var, $llimit, $ulimit, $absTol ) OR
 1459  function_cmp_abs( $correctFunction, $var, $llimit, $ulimit, $absTol,
 1460           $numOfPoints )
 1461 
 1462   $absTol --  the tolerance as an absolute value
 1463 
 1464   function_cmp_abs() uses standard compare and absolute tolerance. All
 1465   other options work exactly as for function_cmp().
 1466 
 1467  function_cmp_up_to_constant_abs( $correctFunction ) OR
 1468  function_cmp_up_to_constant_abs( $correctFunction, $var ) OR
 1469  function_cmp_up_to_constant_abs( $correctFunction, $var, $llimit, $ulimit ) OR
 1470  function_cmp_up_to_constant_abs( $correctFunction, $var, $llimit, $ulimit,
 1471                   $absTol ) OR
 1472  function_cmp_up_to_constant_abs( $correctFunction, $var, $llimit, $ulimit,
 1473                   $absTol, $numOfPoints ) OR
 1474  function_cmp_up_to_constant_abs( $correctFunction, $var, $llimit, $ulimit,
 1475                   $absTol, $numOfPoints,
 1476                   $maxConstantOfIntegration )
 1477 
 1478   function_cmp_up_to_constant_abs() uses antiderivative compare
 1479   and absolute tolerance. All other options work exactly as with
 1480   function_cmp_up_to_constant().
 1481 
 1482 Examples:
 1483 
 1484   ANS( function_cmp( "cos(x)" ) ) --  Accepts cos(x), sin(x+pi/2),
 1485     sin(x)^2 + cos(x) + cos(x)^2 -1, etc. This assumes
 1486     $functVarDefault has been set to "x".
 1487   ANS( function_cmp( $answer, "t" ) ) --  Assuming $answer is "cos(t)",
 1488     accepts cos(t), etc.
 1489   ANS( function_cmp_up_to_constant( "cos(x)" ) )  --  Accepts any
 1490     antiderivative of sin(x), e.g. cos(x) + 5.
 1491   ANS( function_cmp_up_to_constant( "cos(z)", "z" ) ) --  Accepts any
 1492     antiderivative of sin(z), e.g. sin(z+pi/2) + 5.
 1493 
 1494 =cut
 1495 
 1496 sub adaptive_function_cmp {
 1497   my $correctEqn = shift;
 1498   my %options = @_;
 1499   set_default_options(  \%options,
 1500       'vars'      =>  [qw( x y )],
 1501                   'params'    =>  [],
 1502                   'limits'    =>  [ [0,1], [0,1]],
 1503                   'reltol'    =>  $functRelPercentTolDefault,
 1504                   'numPoints'   =>  $functNumOfPoints,
 1505                   'zeroLevel'   =>  $functZeroLevelDefault,
 1506                   'zeroLevelTol'  =>  $functZeroLevelTolDefault,
 1507                   'debug'     =>  0,
 1508   );
 1509 
 1510     my $var_ref = $options{'vars'};
 1511     my $ra_params = $options{ 'params'};
 1512     my $limit_ref = $options{'limits'};
 1513     my $relPercentTol= $options{'reltol'};
 1514     my $numPoints = $options{'numPoints'};
 1515     my $zeroLevel = $options{'zeroLevel'};
 1516     my $zeroLevelTol = $options{'zeroLevelTol'};
 1517 
 1518   FUNCTION_CMP( 'correctEqn'          =>  $correctEqn,
 1519       'var'           =>  $var_ref,
 1520       'limits'          =>  $limit_ref,
 1521       'tolerance'         =>  $relPercentTol,
 1522       'tolType'         =>  'relative',
 1523       'numPoints'         =>  $numPoints,
 1524       'mode'            =>  'std',
 1525       'maxConstantOfIntegration'      =>  10**100,
 1526       'zeroLevel'         =>  $zeroLevel,
 1527       'zeroLevelTol'          =>  $zeroLevelTol,
 1528       'scale_norm'                      =>    1,
 1529       'params'                          =>    $ra_params,
 1530       'debug'               =>  $options{debug} ,
 1531   );
 1532 }
 1533 
 1534 sub function_cmp {
 1535   my ($correctEqn,$var,$llimit,$ulimit,$relPercentTol,$numPoints,$zeroLevel,$zeroLevelTol) = @_;
 1536 
 1537   if ( (scalar(@_) == 3) or (scalar(@_) > 8) or (scalar(@_) == 0) ) {
 1538     function_invalid_params( $correctEqn );
 1539   }
 1540   else {
 1541     FUNCTION_CMP( 'correctEqn'          =>  $correctEqn,
 1542         'var'           =>  $var,
 1543         'limits'          =>  [$llimit, $ulimit],
 1544         'tolerance'         =>  $relPercentTol,
 1545         'tolType'         =>  'relative',
 1546         'numPoints'         =>  $numPoints,
 1547         'mode'            =>  'std',
 1548         'maxConstantOfIntegration'      =>  0,
 1549         'zeroLevel'         =>  $zeroLevel,
 1550         'zeroLevelTol'          =>  $zeroLevelTol
 1551           );
 1552   }
 1553 }
 1554 
 1555 sub function_cmp_up_to_constant { ## for antiderivative problems
 1556   my ($correctEqn,$var,$llimit,$ulimit,$relPercentTol,$numPoints,$maxConstantOfIntegration,$zeroLevel,$zeroLevelTol) = @_;
 1557 
 1558   if ( (scalar(@_) == 3) or (scalar(@_) > 9) or (scalar(@_) == 0) ) {
 1559     function_invalid_params( $correctEqn );
 1560   }
 1561   else {
 1562     FUNCTION_CMP( 'correctEqn'          =>  $correctEqn,
 1563         'var'           =>  $var,
 1564         'limits'          =>  [$llimit, $ulimit],
 1565         'tolerance'         =>  $relPercentTol,
 1566         'tolType'         =>  'relative',
 1567         'numPoints'         =>  $numPoints,
 1568         'mode'            =>  'antider',
 1569         'maxConstantOfIntegration'      =>  $maxConstantOfIntegration,
 1570         'zeroLevel'         =>  $zeroLevel,
 1571         'zeroLevelTol'          =>  $zeroLevelTol
 1572           );
 1573   }
 1574 }
 1575 
 1576 sub function_cmp_abs {      ## similar to function_cmp but uses absolute tolerance
 1577   my ($correctEqn,$var,$llimit,$ulimit,$absTol,$numPoints) = @_;
 1578 
 1579   if ( (scalar(@_) == 3) or (scalar(@_) > 6) or (scalar(@_) == 0) ) {
 1580     function_invalid_params( $correctEqn );
 1581   }
 1582   else {
 1583     FUNCTION_CMP( 'correctEqn'      =>  $correctEqn,
 1584         'var'       =>  $var,
 1585         'limits'      =>  [$llimit, $ulimit],
 1586         'tolerance'     =>  $absTol,
 1587         'tolType'     =>  'absolute',
 1588         'numPoints'     =>  $numPoints,
 1589         'mode'        =>  'std',
 1590         'maxConstantOfIntegration'  =>  0,
 1591         'zeroLevel'     =>  0,
 1592         'zeroLevelTol'      =>  0
 1593     );
 1594   }
 1595 }
 1596 
 1597 
 1598 sub function_cmp_up_to_constant_abs  {  ## for antiderivative problems
 1599                     ## similar to function_cmp_up_to_constant
 1600                     ## but uses absolute tolerance
 1601   my ($correctEqn,$var,$llimit,$ulimit,$absTol,$numPoints,$maxConstantOfIntegration) = @_;
 1602 
 1603   if ( (scalar(@_) == 3) or (scalar(@_) > 7) or (scalar(@_) == 0) ) {
 1604     function_invalid_params( $correctEqn );
 1605   }
 1606 
 1607   else {
 1608     FUNCTION_CMP( 'correctEqn'          =>  $correctEqn,
 1609         'var'           =>  $var,
 1610         'limits'          =>  [$llimit, $ulimit],
 1611         'tolerance'         =>  $absTol,
 1612         'tolType'         =>  'absolute',
 1613         'numPoints'         =>  $numPoints,
 1614         'mode'            =>  'antider',
 1615         'maxConstantOfIntegration'      =>  $maxConstantOfIntegration,
 1616         'zeroLevel'         =>  0,
 1617         'zeroLevelTol'          =>  0
 1618     );
 1619   }
 1620 }
 1621 
 1622 ## The following answer evaluator for comparing multivarable functions was
 1623 ## contributed by Professor William K. Ziemer
 1624 ## (Note: most of the multivariable functionality provided by Professor Ziemer
 1625 ## has now been integrated into fun_cmp and FUNCTION_CMP)
 1626 ############################
 1627 # W.K. Ziemer, Sep. 1999
 1628 # Math Dept. CSULB
 1629 # email: wziemer@csulb.edu
 1630 ############################
 1631 
 1632 =head3 multivar_function_cmp
 1633 
 1634 NOTE: this function is maintained for compatibility. fun_cmp() is
 1635     slightly preferred.
 1636 
 1637 usage:
 1638 
 1639   multivar_function_cmp( $answer, $var_reference, options)
 1640     $answer       --  string, represents function of several variables
 1641     $var_reference    --  number (of variables), or list reference (e.g. ["var1","var2"] )
 1642   options:
 1643     $limit_reference  --  reference to list of lists (e.g. [[1,2],[3,4]])
 1644     $relPercentTol    --  relative percent tolerance in answer
 1645     $numPoints      --  number of points to sample in for each variable
 1646     $zeroLevel      --  if the correct answer is this close to zero, then zeroLevelTol applies
 1647     $zeroLevelTol   --  absolute tolerance to allow when answer is close to zero
 1648 
 1649 =cut
 1650 
 1651 sub multivar_function_cmp {
 1652   my ($correctEqn,$var_ref,$limit_ref,$relPercentTol,$numPoints,$zeroLevel,$zeroLevelTol) = @_;
 1653 
 1654   if ( (scalar(@_) > 7) or (scalar(@_) < 2) ) {
 1655     function_invalid_params( $correctEqn );
 1656   }
 1657 
 1658   FUNCTION_CMP( 'correctEqn'      =>  $correctEqn,
 1659       'var'       =>  $var_ref,
 1660       'limits'      =>  $limit_ref,
 1661       'tolerance'     =>  $relPercentTol,
 1662       'tolType'     =>  'relative',
 1663       'numPoints'     =>  $numPoints,
 1664       'mode'        =>  'std',
 1665       'maxConstantOfIntegration'  =>  0,
 1666       'zeroLevel'     =>  $zeroLevel,
 1667       'zeroLevelTol'      =>  $zeroLevelTol
 1668   );
 1669 }
 1670 
 1671 ## LOW-LEVEL ROUTINE -- NOT NORMALLY FOR END USERS -- USE WITH CAUTION
 1672 ## NOTE: PG_answer_eval is used instead of PG_restricted_eval in order to insure that the answer
 1673 ## evaluated within the context of the package the problem was originally defined in.
 1674 ## Includes multivariable modifications contributed by Professor William K. Ziemer
 1675 ##
 1676 ## IN:  a hash consisting of the following keys (error checking to be added later?)
 1677 ##      correctEqn      --  the correct equation as a string
 1678 ##      var       --  the variable name as a string,
 1679 ##                or a reference to an array of variables
 1680 ##      limits        --  reference to an array of arrays of type [lower,upper]
 1681 ##      tolerance     --  the allowable margin of error
 1682 ##      tolType       --  'relative' or 'absolute'
 1683 ##      numPoints     --  the number of points to evaluate the function at
 1684 ##      mode        --  'std' or 'antider'
 1685 ##      maxConstantOfIntegration  --  maximum size of the constant of integration
 1686 ##      zeroLevel     --  if the correct answer is this close to zero,
 1687 ##                        then zeroLevelTol applies
 1688 ##      zeroLevelTol      --  absolute tolerance to allow when answer is close to zero
 1689 
 1690 
 1691 sub FUNCTION_CMP {
 1692   my %func_params = @_;
 1693 
 1694   my $correctEqn          = $func_params{'correctEqn'};
 1695   my $var           = $func_params{'var'};
 1696   my $ra_limits         = $func_params{'limits'};
 1697   my $tol           = $func_params{'tolerance'};
 1698   my $tolType         = $func_params{'tolType'};
 1699   my $numPoints         = $func_params{'numPoints'};
 1700   my $mode          = $func_params{'mode'};
 1701   my $maxConstantOfIntegration      = $func_params{'maxConstantOfIntegration'};
 1702   my $zeroLevel         = $func_params{'zeroLevel'};
 1703   my $zeroLevelTol        = $func_params{'zeroLevelTol'};
 1704   my $ra_test_points    = $func_params{'test_points'};
 1705 
 1706 
 1707     # Check that everything is defined:
 1708     $func_params{debug} = 0 unless defined($func_params{debug});
 1709     $mode = 'std' unless defined($mode);
 1710     my @VARS = get_var_array( $var );
 1711   my @limits = get_limits_array( $ra_limits );
 1712   my @PARAMS = ();
 1713   @PARAMS = @{$func_params{'params'}} if defined($func_params{'params'});
 1714 
 1715   my (@evaluation_points);
 1716   if(defined($ra_test_points)) {
 1717     # see if this is the standard format
 1718     if( ref($ra_test_points->[0]) eq 'ARRAY') {
 1719       $numPoints = scalar(@{$ra_test_points->[0]});
 1720       # now a little sanity check
 1721       my $j;
 1722       for $j (@{$ra_test_points}) {
 1723         warn "Test points do not give the same number of values for each variable"
 1724           unless(scalar(@{$j}) == $numPoints);
 1725       }
 1726       warn "Test points do not match the number of variables"
 1727         unless scalar(@{$ra_test_points}) == scalar(@VARS);
 1728     } else { # we are got the one-variable format
 1729       $ra_test_points = [$ra_test_points];
 1730       $numPoints = scalar($ra_test_points->[0]);
 1731     }
 1732     # The input format for test points is the transpose of what is used
 1733     # internally below, so take care of that now.
 1734     my ($j1, $j2);
 1735     for ($j1=0; $j1<scalar(@{$ra_test_points}); $j1++) {
 1736       for ($j2=0; $j2<scalar(@{$ra_test_points->[$j1]}); $j2++) {
 1737         $evaluation_points[$j2][$j1] = $ra_test_points->[$j1][$j2];
 1738       }
 1739     }
 1740   } # end of handling of user supplied evaluation points
 1741 
 1742   if ($mode eq 'antider' ) {
 1743     # doctor the equation to allow addition of a constant
 1744     my $CONSTANT_PARAM = 'Q';  # unfortunately parameters must be single letters.
 1745                    # There is the possibility of conflict here.
 1746                    #  'Q' seemed less dangerous than  'C'.
 1747     $correctEqn = "( $correctEqn ) + $CONSTANT_PARAM";
 1748     push(@PARAMS, $CONSTANT_PARAM);
 1749   }
 1750     my $dim_of_param_space = @PARAMS;      # dimension of equivalence space
 1751 
 1752   if( $tolType eq 'relative' ) {
 1753     $tol = $functRelPercentTolDefault     unless defined $tol;
 1754     $tol *= .01;
 1755   }
 1756   else {
 1757     $tol = $functAbsTolDefault        unless defined $tol;
 1758   }
 1759 
 1760   #loop ensures that number of limits matches number of variables
 1761   for( my $i = 0; $i < scalar(@VARS); $i++ ) {
 1762     $limits[$i][0] = $functLLimitDefault      unless defined $limits[$i][0];
 1763     $limits[$i][1] = $functULimitDefault      unless defined $limits[$i][1];
 1764   }
 1765   $numPoints = $functNumOfPoints          unless defined $numPoints;
 1766   $maxConstantOfIntegration = $functMaxConstantOfIntegration  unless defined $maxConstantOfIntegration;
 1767   $zeroLevel = $functZeroLevelDefault       unless defined $zeroLevel;
 1768   $zeroLevelTol = $functZeroLevelTolDefault     unless defined $zeroLevelTol;
 1769 
 1770   $func_params{'var'}       = $var;
 1771       $func_params{'limits'}        = \@limits;
 1772       $func_params{'tolerance'}     = $tol;
 1773       $func_params{'tolType'}       = $tolType;
 1774       $func_params{'numPoints'}     = $numPoints;
 1775       $func_params{'mode'}        = $mode;
 1776       $func_params{'maxConstantOfIntegration'}  = $maxConstantOfIntegration;
 1777       $func_params{'zeroLevel'}     = $zeroLevel;
 1778       $func_params{'zeroLevelTol'}        =   $zeroLevelTol;
 1779 
 1780 ########################################################
 1781 #   End of cleanup of calling parameters
 1782 ########################################################
 1783   my $i;            #for use with loops
 1784   my $PGanswerMessage = "";
 1785   my $originalCorrEqn = $correctEqn;
 1786 
 1787 #prepare the correct answer and check it's syntax
 1788       my $rh_correct_ans = new AnswerHash;
 1789   $rh_correct_ans->input($correctEqn);
 1790   $rh_correct_ans = check_syntax($rh_correct_ans);
 1791   warn  $rh_correct_ans->{error_message} if $rh_correct_ans->{error_flag};
 1792   $rh_correct_ans->clear_error();
 1793   $rh_correct_ans = function_from_string2($rh_correct_ans, ra_vars => [ @VARS, @PARAMS ],
 1794                                                            store_in =>'rf_correct_ans',
 1795                                                            debug =>  $func_params{debug});
 1796   my $correct_eqn_sub = $rh_correct_ans->{rf_correct_ans};
 1797   warn $rh_correct_ans->{error_message} if $rh_correct_ans->{error_flag};
 1798 
 1799   if(not defined($ra_test_points)) {
 1800     #create the evaluation points
 1801     my $random_for_answers = new PGrandom($main::PG_original_problemSeed);
 1802     my $NUMBER_OF_STEPS_IN_RANDOM = 1000;    # determines the granularity of the random_for_answers number generator
 1803     for( my $count = 0; $count < @PARAMS+1+$numPoints; $count++ ) {
 1804       my (@vars,$iteration_limit);
 1805       for( my $i = 0; $i < @VARS; $i++ ) {
 1806         my $iteration_limit = 10;
 1807         while (  0 < --$iteration_limit ) {  # make sure that the endpoints of the interval are not included
 1808           $vars[$i] = $random_for_answers->random($limits[$i][0], $limits[$i][1], abs($limits[$i][1] - $limits[$i][0])/$NUMBER_OF_STEPS_IN_RANDOM );
 1809           last if $vars[$i]!=$limits[$i][0] and $vars[$i]!=$limits[$i][1];
 1810         }
 1811         warn "Unable to properly choose  evaluation points for this function in the interval ( $limits[$i][0] , $limits[$i][1] )"
 1812           if $iteration_limit == 0;
 1813       };
 1814 
 1815       push(@evaluation_points,\@vars);
 1816     }
 1817   }
 1818   my $evaluation_points = Matrix->new_from_array_ref(\@evaluation_points);
 1819 
 1820   #my $COEFFS = determine_param_coeffs($correct_eqn_sub,$evaluation_points[0],$numOfParameters);
 1821       #warn "coeff", join(" | ", @{$COEFFS});
 1822 
 1823 #construct the answer evaluator
 1824     my $answer_evaluator = new AnswerEvaluator;
 1825     $answer_evaluator->{debug} = $func_params{debug};
 1826     $answer_evaluator->ans_hash(  correct_ans     =>  $originalCorrEqn,
 1827           rf_correct_ans    =>  $rh_correct_ans->{rf_correct_ans},
 1828           evaluation_points =>  \@evaluation_points,
 1829           ra_param_vars     =>  \@PARAMS,
 1830           ra_vars     =>  \@VARS,
 1831           type      =>  'function',
 1832     );
 1833 
 1834     $answer_evaluator->install_pre_filter(\&check_syntax);
 1835     $answer_evaluator->install_pre_filter(\&function_from_string2, ra_vars => \@VARS,debug=>$func_params{debug},); # @VARS has been guaranteed to be an array, $var might be a single string.
 1836     $answer_evaluator->install_pre_filter(\&best_approx_parameters, %func_params, param_vars => \@PARAMS);
 1837     $answer_evaluator->install_evaluator(\&calculate_difference_vector, %func_params);
 1838     $answer_evaluator->install_evaluator(\&is_zero_array, tolerance => $tol );
 1839     $answer_evaluator->install_post_filter(sub {my $rh_ans = shift; $rh_ans->clear_error('SYNTAX'); $rh_ans;} );
 1840     $answer_evaluator->install_post_filter(
 1841             sub {my $rh_ans = shift;
 1842             if ($rh_ans->catch_error('EVAL') ) {
 1843               $rh_ans->{ans_message} = $rh_ans->{error_message};
 1844               $rh_ans->clear_error('EVAL');
 1845             }
 1846             $rh_ans;
 1847           }
 1848   );
 1849     $answer_evaluator;
 1850 }
 1851 
 1852 
 1853 ## LOW-LEVEL ROUTINE -- NOT NORMALLY FOR END USERS -- USE WITH CAUTION
 1854 ##
 1855 ## IN:  a hash containing the following items (error-checking to be added later?):
 1856 ##      correctAnswer --  the correct answer
 1857 ##      tolerance   --  the allowable margin of error
 1858 ##      tolType     --  'relative' or 'absolute'
 1859 ##      format      --  the display format of the answer
 1860 ##      mode      --  one of 'std', 'strict', 'arith', or 'frac';
 1861 ##                  determines allowable formats for the input
 1862 ##      zeroLevel   --  if the correct answer is this close to zero, then zeroLevelTol applies
 1863 ##      zeroLevelTol  --  absolute tolerance to allow when answer is close to zero
 1864 
 1865 
 1866 ##########################################################################
 1867 ##########################################################################
 1868 ## String answer evaluators
 1869 
 1870 =head2 String Answer Evaluators
 1871 
 1872 String answer evaluators compare a student string to the correct string.
 1873 Different filters can be applied to allow various degrees of variation.
 1874 Both the student and correct answers are subject to the same filters, to
 1875 ensure that there are no unexpected matches or rejections.
 1876 
 1877 String Filters
 1878 
 1879   remove_whitespace --  Removes all whitespace from the string.
 1880             It applies the following substitution
 1881             to the string:
 1882               $filteredAnswer =~ s/\s+//g;
 1883 
 1884   compress_whitespace --  Removes leading and trailing whitespace, and
 1885             replaces all other blocks of whitespace by a
 1886             single space. Applies the following substitutions:
 1887               $filteredAnswer =~ s/^\s*//;
 1888               $filteredAnswer =~ s/\s*$//;
 1889               $filteredAnswer =~ s/\s+/ /g;
 1890 
 1891   trim_whitespace   --  Removes leading and trailing whitespace.
 1892             Applies the following substitutions:
 1893               $filteredAnswer =~ s/^\s*//;
 1894               $filteredAnswer =~ s/\s*$//;
 1895 
 1896   ignore_case     --  Ignores the case of the string. More accurately,
 1897             it converts the string to uppercase (by convention).
 1898             Applies the following function:
 1899               $filteredAnswer = uc $filteredAnswer;
 1900 
 1901   ignore_order    --  Ignores the order of the letters in the string.
 1902             This is used for problems of the form "Choose all
 1903             that apply." Specifically, it removes all
 1904             whitespace and lexically sorts the letters in
 1905             ascending alphabetical order. Applies the following
 1906             functions:
 1907               $filteredAnswer = join( "", lex_sort(
 1908                 split( /\s*/, $filteredAnswer ) ) );
 1909 
 1910 =cut
 1911 
 1912 ################################
 1913 ## STRING ANSWER FILTERS
 1914 
 1915 ## IN:  --the string to be filtered
 1916 ##    --a list of the filters to use
 1917 ##
 1918 ## OUT: --the modified string
 1919 ##
 1920 ## Use this subroutine instead of the
 1921 ## individual filters below it
 1922 
 1923 sub str_filters {
 1924   my $stringToFilter = shift @_;
 1925   my @filters_to_use = @_;
 1926   my %known_filters = ( 'remove_whitespace'   =>  undef,
 1927         'compress_whitespace'   =>  undef,
 1928         'trim_whitespace'   =>  undef,
 1929         'ignore_case'     =>  undef,
 1930         'ignore_order'      =>  undef
 1931   );
 1932 
 1933   #test for unknown filters
 1934   my $filter;
 1935   foreach $filter (@filters_to_use) {
 1936     die "Unknown string filter $filter (try checking the parameters to str_cmp() )"
 1937                 unless exists $known_filters{$filter};
 1938   }
 1939 
 1940   if( grep( /remove_whitespace/i, @filters_to_use ) ) {
 1941     $stringToFilter = remove_whitespace( $stringToFilter );
 1942   }
 1943   if( grep( /compress_whitespace/i, @filters_to_use ) ) {
 1944     $stringToFilter = compress_whitespace( $stringToFilter );
 1945   }
 1946   if( grep( /trim_whitespace/i, @filters_to_use ) ) {
 1947     $stringToFilter = trim_whitespace( $stringToFilter );
 1948   }
 1949   if( grep( /ignore_case/i, @filters_to_use ) ) {
 1950     $stringToFilter = ignore_case( $stringToFilter );
 1951   }
 1952   if( grep( /ignore_order/i, @filters_to_use ) ) {
 1953     $stringToFilter = ignore_order( $stringToFilter );
 1954   }
 1955 
 1956   return $stringToFilter;
 1957 }
 1958 
 1959 sub remove_whitespace {
 1960   my $filteredAnswer = shift;
 1961 
 1962   $filteredAnswer =~ s/\s+//g;    # remove all whitespace
 1963 
 1964   return $filteredAnswer;
 1965 }
 1966 
 1967 sub compress_whitespace {
 1968   my $filteredAnswer = shift;
 1969 
 1970   $filteredAnswer =~ s/^\s*//;    # remove initial whitespace
 1971   $filteredAnswer =~ s/\s*$//;    # remove trailing whitespace
 1972   $filteredAnswer =~ s/\s+/ /g;   # replace spaces by single space
 1973 
 1974   return $filteredAnswer;
 1975 }
 1976 
 1977 sub trim_whitespace {
 1978   my $filteredAnswer = shift;
 1979 
 1980   $filteredAnswer =~ s/^\s*//;    # remove initial whitespace
 1981   $filteredAnswer =~ s/\s*$//;    # remove trailing whitespace
 1982 
 1983   return $filteredAnswer;
 1984 }
 1985 
 1986 sub ignore_case {
 1987   my $filteredAnswer = shift;
 1988   #warn "filtered answer is ", $filteredAnswer;
 1989   #$filteredAnswer = uc $filteredAnswer;  # this didn't work on webwork xmlrpc, but does elsewhere ????
 1990   $filteredAnswer =~ tr/a-z/A-Z/;
 1991 
 1992   return $filteredAnswer;
 1993 }
 1994 
 1995 sub ignore_order {
 1996   my $filteredAnswer = shift;
 1997 
 1998   $filteredAnswer = join( "", lex_sort( split( /\s*/, $filteredAnswer ) ) );
 1999 
 2000   return $filteredAnswer;
 2001 }
 2002 ################################
 2003 ## END STRING ANSWER FILTERS
 2004 
 2005 
 2006 =head3 str_cmp()
 2007 
 2008 Compares a string or a list of strings, using a named hash of options to set
 2009 parameters. This can make for more readable code than using the "mode"_str_cmp()
 2010 style, but some people find one or the other easier to remember.
 2011 
 2012 ANS( str_cmp( answer or answer_array_ref, options_hash ) );
 2013 
 2014   1. the correct answer or a reference to an array of answers
 2015   2. either a list of filters, or:
 2016      a hash consisting of
 2017     filters - a reference to an array of filters
 2018 
 2019   Returns an answer evaluator, or (if given a reference to an array of answers),
 2020   a list of answer evaluators
 2021 
 2022 FILTERS:
 2023 
 2024   remove_whitespace --  removes all whitespace
 2025   compress_whitespace --  removes whitespace from the beginning and end of the string,
 2026               and treats one or more whitespace characters in a row as a
 2027               single space (true by default)
 2028   trim_whitespace   --  removes whitespace from the beginning and end of the string
 2029   ignore_case   --  ignores the case of the letters (true by default)
 2030   ignore_order    --  ignores the order in which letters are entered
 2031 
 2032 EXAMPLES:
 2033 
 2034   str_cmp( "Hello" )  --  matches "Hello", "  hello" (same as std_str_cmp() )
 2035   str_cmp( ["Hello", "Goodbye"] ) --  same as std_str_cmp_list()
 2036   str_cmp( " hello ", trim_whitespace ) --  matches "hello", " hello  "
 2037   str_cmp( "ABC", filters => 'ignore_order' ) --  matches "ACB", "A B C", but not "abc"
 2038   str_cmp( "D E F", remove_whitespace, ignore_case )  --  matches "def" and "d e f" but not "fed"
 2039 
 2040 
 2041 =cut
 2042 
 2043 sub str_cmp {
 2044   my $correctAnswer = shift @_;
 2045   $correctAnswer = '' unless defined($correctAnswer);
 2046   my @options = @_;
 2047   my $ra_filters;
 2048 
 2049   # error-checking for filters occurs in the filters() subroutine
 2050   if( not defined( $options[0] ) ) {    # used with no filters as alias for std_str_cmp()
 2051     @options = ( 'compress_whitespace', 'ignore_case' );
 2052   }
 2053 
 2054   if( $options[0] eq 'filters' ) {    # using filters => [f1, f2, ...] notation
 2055     $ra_filters = $options[1];
 2056   }
 2057   else {            # using a list of filters
 2058     $ra_filters = \@options;
 2059   }
 2060 
 2061   # thread over lists
 2062   my @ans_list = ();
 2063 
 2064   if ( ref($correctAnswer) eq 'ARRAY' ) {
 2065     @ans_list = @{$correctAnswer};
 2066   }
 2067   else {
 2068     push( @ans_list, $correctAnswer );
 2069   }
 2070 
 2071   # final_answer;
 2072   my @output_list = ();
 2073 
 2074   foreach my $ans (@ans_list) {
 2075     push(@output_list, STR_CMP( 'correctAnswer' =>  $ans,
 2076             'filters' =>  $ra_filters,
 2077             'type'    =>  'str_cmp'
 2078          )
 2079     );
 2080   }
 2081 
 2082   return (wantarray) ? @output_list : $output_list[0] ;
 2083 }
 2084 
 2085 =head3 "mode"_str_cmp functions
 2086 
 2087 The functions of the the form "mode"_str_cmp() use different functions to
 2088 specify which filters to apply. They take no options except the correct
 2089 string. There are also versions which accept a list of strings.
 2090 
 2091  std_str_cmp( $correctString )
 2092  std_str_cmp_list( @correctStringList )
 2093   Filters: compress_whitespace, ignore_case
 2094 
 2095  std_cs_str_cmp( $correctString )
 2096  std_cs_str_cmp_list( @correctStringList )
 2097   Filters: compress_whitespace
 2098 
 2099  strict_str_cmp( $correctString )
 2100  strict_str_cmp_list( @correctStringList )
 2101   Filters: trim_whitespace
 2102 
 2103  unordered_str_cmp( $correctString )
 2104  unordered_str_cmp_list( @correctStringList )
 2105   Filters: ignore_order, ignore_case
 2106 
 2107  unordered_cs_str_cmp( $correctString )
 2108  unordered_cs_str_cmp_list( @correctStringList )
 2109   Filters: ignore_order
 2110 
 2111  ordered_str_cmp( $correctString )
 2112  ordered_str_cmp_list( @correctStringList )
 2113   Filters: remove_whitespace, ignore_case
 2114 
 2115  ordered_cs_str_cmp( $correctString )
 2116  ordered_cs_str_cmp_list( @correctStringList )
 2117   Filters: remove_whitespace
 2118 
 2119 Examples
 2120 
 2121   ANS( std_str_cmp( "W. Mozart" ) ) --  Accepts "W. Mozart", "W. MOZarT",
 2122     and so forth. Case insensitive. All internal spaces treated
 2123     as single spaces.
 2124   ANS( std_cs_str_cmp( "Mozart" ) ) --  Rejects "mozart". Same as
 2125     std_str_cmp() but case sensitive.
 2126   ANS( strict_str_cmp( "W. Mozart" ) )  --  Accepts only the exact string.
 2127   ANS( unordered_str_cmp( "ABC" ) ) --  Accepts "a c B", "CBA" and so forth.
 2128     Unordered, case insensitive, spaces ignored.
 2129   ANS( unordered_cs_str_cmp( "ABC" ) )  --  Rejects "abc". Same as
 2130     unordered_str_cmp() but case sensitive.
 2131   ANS( ordered_str_cmp( "ABC" ) ) --  Accepts "a b C", "A B C" and so forth.
 2132     Ordered, case insensitive, spaces ignored.
 2133   ANS( ordered_cs_str_cmp( "ABC" ) )  --  Rejects "abc", accepts "A BC" and
 2134     so forth. Same as ordered_str_cmp() but case sensitive.
 2135 
 2136 =cut
 2137 
 2138 sub std_str_cmp {         # compare strings
 2139   my $correctAnswer = shift @_;
 2140   my @filters = ( 'compress_whitespace', 'ignore_case' );
 2141   my $type = 'std_str_cmp';
 2142   STR_CMP(  'correctAnswer' =>  $correctAnswer,
 2143       'filters' =>  \@filters,
 2144       'type'    =>  $type
 2145   );
 2146 }
 2147 
 2148 sub std_str_cmp_list {        # alias for std_str_cmp
 2149   my @answerList = @_;
 2150   my @output;
 2151   while (@answerList) {
 2152     push( @output, std_str_cmp(shift @answerList) );
 2153   }
 2154   @output;
 2155 }
 2156 
 2157 sub std_cs_str_cmp {        # compare strings case sensitive
 2158   my $correctAnswer = shift @_;
 2159   my @filters = ( 'compress_whitespace' );
 2160   my $type = 'std_cs_str_cmp';
 2161   STR_CMP(  'correctAnswer' =>  $correctAnswer,
 2162       'filters' =>  \@filters,
 2163       'type'    =>  $type
 2164   );
 2165 }
 2166 
 2167 sub std_cs_str_cmp_list {     # alias for std_cs_str_cmp
 2168   my @answerList = @_;
 2169   my @output;
 2170   while (@answerList) {
 2171     push( @output, std_cs_str_cmp(shift @answerList) );
 2172   }
 2173   @output;
 2174 }
 2175 
 2176 sub strict_str_cmp {        # strict string compare
 2177   my $correctAnswer = shift @_;
 2178   my @filters = ( 'trim_whitespace' );
 2179   my $type = 'strict_str_cmp';
 2180   STR_CMP(  'correctAnswer' =>  $correctAnswer,
 2181       'filters' =>  \@filters,
 2182       'type'    =>  $type
 2183   );
 2184 }
 2185 
 2186 sub strict_str_cmp_list {     # alias for strict_str_cmp
 2187   my @answerList = @_;
 2188   my @output;
 2189   while (@answerList) {
 2190     push( @output, strict_str_cmp(shift @answerList) );
 2191   }
 2192   @output;
 2193 }
 2194 
 2195 sub unordered_str_cmp {       # unordered, case insensitive, spaces ignored
 2196   my $correctAnswer = shift @_;
 2197   my @filters = ( 'ignore_order', 'ignore_case' );
 2198   my $type = 'unordered_str_cmp';
 2199   STR_CMP(  'correctAnswer'   =>  $correctAnswer,
 2200       'filters'   =>  \@filters,
 2201       'type'      =>  $type
 2202   );
 2203 }
 2204 
 2205 sub unordered_str_cmp_list {    # alias for unordered_str_cmp
 2206   my @answerList = @_;
 2207   my @output;
 2208   while (@answerList) {
 2209     push( @output, unordered_str_cmp(shift @answerList) );
 2210   }
 2211   @output;
 2212 }
 2213 
 2214 sub unordered_cs_str_cmp {      # unordered, case sensitive, spaces ignored
 2215   my $correctAnswer = shift @_;
 2216   my @filters = ( 'ignore_order' );
 2217   my $type = 'unordered_cs_str_cmp';
 2218   STR_CMP(  'correctAnswer'   =>  $correctAnswer,
 2219       'filters'   =>  \@filters,
 2220       'type'      =>  $type
 2221   );
 2222 }
 2223 
 2224 sub unordered_cs_str_cmp_list {   # alias for unordered_cs_str_cmp
 2225   my @answerList = @_;
 2226   my @output;
 2227   while (@answerList) {
 2228     push( @output, unordered_cs_str_cmp(shift @answerList) );
 2229   }
 2230   @output;
 2231 }
 2232 
 2233 sub ordered_str_cmp {       # ordered, case insensitive, spaces ignored
 2234   my $correctAnswer = shift @_;
 2235   my @filters = ( 'remove_whitespace', 'ignore_case' );
 2236   my $type = 'ordered_str_cmp';
 2237   STR_CMP(  'correctAnswer' =>  $correctAnswer,
 2238       'filters' =>  \@filters,
 2239       'type'    =>  $type
 2240   );
 2241 }
 2242 
 2243 sub ordered_str_cmp_list {      # alias for ordered_str_cmp
 2244   my @answerList = @_;
 2245   my @output;
 2246   while (@answerList) {
 2247     push( @output, ordered_str_cmp(shift @answerList) );
 2248   }
 2249   @output;
 2250 }
 2251 
 2252 sub ordered_cs_str_cmp {      # ordered,  case sensitive, spaces ignored
 2253   my $correctAnswer = shift @_;
 2254   my @filters = ( 'remove_whitespace' );
 2255   my $type = 'ordered_cs_str_cmp';
 2256   STR_CMP(  'correctAnswer' =>  $correctAnswer,
 2257       'filters' =>  \@filters,
 2258       'type'    =>  $type
 2259   );
 2260 }
 2261 
 2262 sub ordered_cs_str_cmp_list {   # alias for ordered_cs_str_cmp
 2263   my @answerList = @_;
 2264   my @output;
 2265   while (@answerList) {
 2266     push( @output, ordered_cs_str_cmp(shift @answerList) );
 2267   }
 2268   @output;
 2269 }
 2270 
 2271 
 2272 ## LOW-LEVEL ROUTINE -- NOT NORMALLY FOR END USERS -- USE WITH CAUTION
 2273 ##
 2274 ## IN:  a hashtable with the following entries (error-checking to be added later?):
 2275 ##      correctAnswer --  the correct answer, before filtering
 2276 ##      filters     --  reference to an array containing the filters to be applied
 2277 ##      type      --  a string containing the type of answer evaluator in use
 2278 ## OUT: a reference to an answer evaluator subroutine
 2279 
 2280 sub STR_CMP {
 2281   my %str_params = @_;
 2282   $str_params{'correctAnswer'} = str_filters( $str_params{'correctAnswer'}, @{$str_params{'filters'}} );
 2283   my $answer_evaluator = sub {
 2284     my $in = shift @_;
 2285     $in = '' unless defined $in;
 2286     my $original_student_ans = $in;
 2287     $in = str_filters( $in, @{$str_params{'filters'}} );
 2288     my $correctQ = ( $in eq $str_params{'correctAnswer'} ) ? 1: 0;
 2289     my $ans_hash = new AnswerHash(    'score'       =>  $correctQ,
 2290               'correct_ans'     =>  $str_params{'correctAnswer'},
 2291               'student_ans'     =>  $in,
 2292               'ans_message'     =>  '',
 2293               'type'        =>  $str_params{'type'},
 2294               'preview_text_string'   =>  $in,
 2295               'preview_latex_string'    =>  $in,
 2296               'original_student_ans'    =>  $original_student_ans
 2297     );
 2298     return $ans_hash;
 2299   };
 2300   return $answer_evaluator;
 2301 }
 2302 
 2303 ##########################################################################
 2304 ##########################################################################
 2305 ## Miscellaneous answer evaluators
 2306 
 2307 =head2 Miscellaneous Answer Evaluators (Checkboxes and Radio Buttons)
 2308 
 2309 These evaluators do not fit any of the other categories.
 2310 
 2311 checkbox_cmp( $correctAnswer )
 2312 
 2313   $correctAnswer  --  a string containing the names of the correct boxes,
 2314             e.g. "ACD". Note that this means that individual
 2315             checkbox names can only be one character. Internally,
 2316             this is largely the same as unordered_cs_str_cmp().
 2317 
 2318 radio_cmp( $correctAnswer )
 2319 
 2320   $correctAnswer  --  a string containing the name of the correct radio
 2321             button, e.g. "Choice1". This is case sensitive and
 2322             whitespace sensitive, so the correct answer must match
 2323             the name of the radio button exactly.
 2324 
 2325 =cut
 2326 
 2327 # added 6/14/2000 by David Etlinger
 2328 # because of the conversion of the answer
 2329 # string to an array, I thought it better not
 2330 # to force STR_CMP() to work with this
 2331 
 2332 #added 2/26/2003 by Mike Gage
 2333 # handled the case where multiple answers are passed as an array reference
 2334 # rather than as a \0 delimited string.
 2335 sub checkbox_cmp {
 2336   my  $correctAnswer = shift @_;
 2337   $correctAnswer = str_filters( $correctAnswer, 'ignore_order' );
 2338 
 2339   my  $answer_evaluator = sub {
 2340     my $in = shift @_;
 2341     $in = '' unless defined $in;      #in case no boxes checked
 2342                         # multiple answers could come in two forms
 2343                         # either a \0 delimited string or
 2344                         # an array reference.  We handle both.
 2345         if (ref($in) eq 'ARRAY')   {
 2346           $in = join("",@{$in});              # convert array to single no-delimiter string
 2347         } else {
 2348       my @temp = split( "\0", $in );    #convert "\0"-delimited string to array...
 2349       $in = join( "", @temp );      #and then to a single no-delimiter string
 2350     }
 2351     my $original_student_ans = $in;     #well, almost original
 2352     $in = str_filters( $in, 'ignore_order' );
 2353 
 2354     my $correctQ = ($in eq $correctAnswer) ? 1: 0;
 2355 
 2356     my $ans_hash = new AnswerHash(
 2357               'score'     =>  $correctQ,
 2358               'correct_ans'   =>  "$correctAnswer",
 2359               'student_ans'   =>  $in,
 2360               'ans_message'   =>  "",
 2361               'type'      =>  "checkbox_cmp",
 2362               'preview_text_string' =>  $in,
 2363               'original_student_ans'  =>  $original_student_ans
 2364     );
 2365     return $ans_hash;
 2366 
 2367   };
 2368   return $answer_evaluator;
 2369 }
 2370 
 2371 #added 6/28/2000 by David Etlinger
 2372 #exactly the same as strict_str_cmp,
 2373 #but more intuitive to the user
 2374 sub radio_cmp {
 2375   strict_str_cmp( @_ );
 2376 }
 2377 
 2378 ##########################################################################
 2379 ##########################################################################
 2380 ## Text and e-mail routines
 2381 
 2382 sub store_ans_at {
 2383   my $answerStringRef = shift;
 2384   my %options = @_;
 2385   my $ans_eval= '';
 2386   if ( ref($answerStringRef) eq 'SCALAR' ) {
 2387     $ans_eval= sub {
 2388       my $text = shift;
 2389       $text = '' unless defined($text);
 2390       $$answerStringRef = $$answerStringRef  . $text;
 2391       my $ans_hash = new AnswerHash(
 2392                'score'      =>  1,
 2393                'correct_ans'      =>  '',
 2394                'student_ans'      =>  $text,
 2395                'ans_message'      =>  '',
 2396                'type'       =>  'store_ans_at',
 2397                'original_student_ans'   =>  $text,
 2398                'preview_text_string'    =>  ''
 2399       );
 2400 
 2401     return $ans_hash;
 2402     };
 2403   }
 2404   else {
 2405     die "Syntax error: \n The argument to store_ans_at() must be a pointer to a scalar.\n(e.g.  store_ans_at(~~\$MSG) )\n\n";
 2406   }
 2407 
 2408   return $ans_eval;
 2409 }
 2410 
 2411 #### subroutines used in producing a questionnaire
 2412 #### these are at least good models for other answers of this type
 2413 
 2414 my $QUESTIONNAIRE_ANSWERS=''; #  stores the answers until it is time to send them
 2415        #  this must be initialized before the answer evaluators are run
 2416        #  but that happens long after all of the text in the problem is
 2417        #  evaluated.
 2418 # this is a utility script for cleaning up the answer output for display in
 2419 #the answers.
 2420 
 2421 sub DUMMY_ANSWER {
 2422   my $num = shift;
 2423   qq{<INPUT TYPE="HIDDEN" NAME="answer$num" VALUE="">}
 2424 }
 2425 
 2426 sub escapeHTML {
 2427   my $string = shift;
 2428   $string =~ s/\n/$BR/ge;
 2429   $string;
 2430 }
 2431 
 2432 # these next three subroutines show how to modify the "store_ans_at()" answer
 2433 # evaluator to add extra information before storing the info
 2434 # They provide a good model for how to tweak answer evaluators in special cases.
 2435 
 2436 sub anstext {
 2437   my $num = shift;
 2438   my $ans_eval_template = store_ans_at(\$QUESTIONNAIRE_ANSWERS);
 2439   my $psvnNumber  = PG_restricted_eval($main::psvnNumber);
 2440   my $probNum  = PG_restricted_eval($main::probNum);
 2441   my $ans_eval = sub {
 2442          my $text = shift;
 2443          $text = '' unless defined($text);
 2444          my $new_text = "\npsvnNumber-Problem-$probNum-Question-$num:\n $text "; #  modify entered text
 2445          my $out = &$ans_eval_template($new_text);       # standard evaluator
 2446          #warn "$QUESTIONNAIRE_ANSWERS";
 2447          $out->{student_ans} = escapeHTML($text);  #  restore original entered text
 2448          $out->{correct_ans} = "Question  $num answered";
 2449          $out->{original_student_ans} = escapeHTML($text);
 2450          $out;
 2451     };
 2452    $ans_eval;
 2453 }
 2454 
 2455 sub ansradio {
 2456   my $num = shift;
 2457   my $psvnNumber  = PG_restricted_eval($main::psvnNumber);
 2458   my $probNum  = PG_restricted_eval($main::probNum);
 2459 
 2460   my $ans_eval_template = store_ans_at(\$QUESTIONNAIRE_ANSWERS);
 2461   my $ans_eval = sub {
 2462          my $text = shift;
 2463          $text = '' unless defined($text);
 2464          my $new_text = "\n$psvnNumber-Problem-$probNum-RADIO-$num:\n $text ";       # modify entered text
 2465          my $out = $ans_eval_template->($new_text);       # standard evaluator
 2466          $out->{student_ans} =escapeHTML($text);  # restore original entered text
 2467          $out->{original_student_ans} = escapeHTML($text);
 2468          $out;
 2469    };
 2470 
 2471    $ans_eval;
 2472 }
 2473 
 2474 sub anstext_non_anonymous {
 2475   ## this emails identifying information
 2476   my $num = shift;
 2477     my $psvnNumber  = PG_restricted_eval($main::psvnNumber);
 2478   my $probNum  = PG_restricted_eval($main::probNum);
 2479     my $studentLogin  = PG_restricted_eval($main::studentLogin);
 2480   my $studentID  = PG_restricted_eval($main::studentID);
 2481     my $studentName  = PG_restricted_eval($main::studentName);
 2482 
 2483 
 2484   my $ans_eval_template = store_ans_at(\$QUESTIONNAIRE_ANSWERS);
 2485   my $ans_eval = sub {
 2486          my $text = shift;
 2487          $text = '' unless defined($text);
 2488          my $new_text = "\n$psvnNumber-Problem-$probNum-Question-$num:\n$studentLogin $main::studentID $studentName\n$text "; # modify entered text
 2489          my $out = &$ans_eval_template($new_text);       # standard evaluator
 2490          #warn "$QUESTIONNAIRE_ANSWERS";
 2491          $out->{student_ans} = escapeHTML($text);  #  restore original entered text
 2492          $out->{correct_ans} = "Question  $num answered";
 2493          $out->{original_student_ans} = escapeHTML($text);
 2494          $out;
 2495     };
 2496    $ans_eval;
 2497 }
 2498 
 2499 
 2500 #  This is another example of how to modify an  answer evaluator to obtain
 2501 #  the desired behavior in a special case.  Here the object is to have
 2502 #  have the last answer trigger the send_mail_to subroutine which mails
 2503 #  all of the answers to the designated address.
 2504 #  (This address must be listed in PG_environment{'ALLOW_MAIL_TO'} or an error occurs.)
 2505 
 2506 # Fix me?? why is the body hard wired to the string QUESTIONNAIRE_ANSWERS?
 2507 
 2508 sub mail_answers_to {  #accepts the last answer and mails off the result
 2509   my $user_address = shift;
 2510   my $ans_eval = sub {
 2511 
 2512     # then mail out all of the answers, including this last one.
 2513 
 2514     send_mail_to( $user_address,
 2515           'subject'       =>  "$main::courseName WeBWorK questionnaire",
 2516           'body'          =>  $QUESTIONNAIRE_ANSWERS,
 2517           'ALLOW_MAIL_TO'   =>  $rh_envir->{ALLOW_MAIL_TO}
 2518     );
 2519 
 2520     my $ans_hash = new AnswerHash(  'score'   =>  1,
 2521             'correct_ans' =>  '',
 2522             'student_ans' =>  'Answer recorded',
 2523             'ans_message' =>  '',
 2524             'type'    =>  'send_mail_to',
 2525     );
 2526 
 2527     return $ans_hash;
 2528   };
 2529 
 2530   return $ans_eval;
 2531 }
 2532 
 2533 sub save_answer_to_file {  #accepts the last answer and mails off the result
 2534   my $fileID = shift;
 2535   my $ans_eval = new AnswerEvaluator;
 2536   $ans_eval->install_evaluator(
 2537       sub {
 2538          my $rh_ans = shift;
 2539 
 2540              unless ( defined( $rh_ans->{student_ans} ) ) {
 2541               $rh_ans->throw_error("save_answers_to_file","{student_ans} field not defined");
 2542               return $rh_ans;
 2543             }
 2544 
 2545         my $error;
 2546         my $string = '';
 2547         $string = qq![[<$main::studentLogin> $main::studentName /!. time() . qq!/]]\n!.
 2548           $rh_ans->{student_ans}. qq!\n\n============================\n\n!;
 2549 
 2550         if ($error = AnswerIO::saveAnswerToFile('preflight',$string) ) {
 2551           $rh_ans->throw_error("save_answers_to_file","Error:  $error");
 2552         } else {
 2553           $rh_ans->{'student_ans'} = 'Answer saved';
 2554           $rh_ans->{'score'} = 1;
 2555         }
 2556         $rh_ans;
 2557       }
 2558   );
 2559 
 2560   return $ans_eval;
 2561 }
 2562 
 2563 sub mail_answers_to2 {  #accepts the last answer and mails off the result
 2564   my $user_address = shift;
 2565   my $subject = shift;
 2566   $subject = "$main::courseName WeBWorK questionnaire" unless defined $subject;
 2567 
 2568   send_mail_to($user_address,
 2569       'subject'     => $subject,
 2570       'body'        => $QUESTIONNAIRE_ANSWERS,
 2571       'ALLOW_MAIL_TO'   => $rh_envir->{ALLOW_MAIL_TO}
 2572   );
 2573 }
 2574 
 2575 ##########################################################################
 2576 ##########################################################################
 2577 
 2578 
 2579 ###########################################################################
 2580 ### THE FOLLOWING ARE LOCAL SUBROUTINES THAT ARE MEANT TO BE CALLED ONLY FROM THIS SCRIPT.
 2581 
 2582 ## Internal routine that converts variables into the standard array format
 2583 ##
 2584 ## IN:  one of the following:
 2585 ##      an undefined value (i.e., no variable was specified)
 2586 ##      a reference to an array of variable names -- [var1, var2]
 2587 ##      a number (the number of variables desired) -- 3
 2588 ##      one or more variable names -- (var1, var2)
 2589 ## OUT: an array of variable names
 2590 
 2591 sub get_var_array {
 2592   my $in = shift @_;
 2593   my @out;
 2594 
 2595   if( not defined($in) ) {      #if nothing defined, build default array and return
 2596     @out = ( $functVarDefault );
 2597     return @out;
 2598   }
 2599   elsif( ref( $in ) eq 'ARRAY' ) {  #if given an array ref, dereference and return
 2600     return @{$in};
 2601   }
 2602   elsif( $in =~ /^\d+/ ) {      #if given a number, set up the array and return
 2603     if( $in == 1 ) {
 2604       $out[0] = 'x';
 2605     }
 2606     elsif( $in == 2 ) {
 2607       $out[0] = 'x';
 2608       $out[1] = 'y';
 2609     }
 2610     elsif( $in == 3 ) {
 2611       $out[0] = 'x';
 2612       $out[1] = 'y';
 2613       $out[2] = 'z';
 2614     }
 2615     else {  #default to the x_1, x_2, ... convention
 2616       my ($i, $tag);
 2617       for( $i=0; $i < $in; $i++ ) {
 2618               ## akp the above seems to be off by one 1/4/00
 2619         $tag = $i + 1;                            ## akp 1/4/00
 2620         $out[$i] = "${functVarDefault}_" . $tag;              ## akp 1/4/00
 2621       }
 2622     }
 2623     return @out;
 2624   }
 2625   else {            #if given one or more names, return as an array
 2626     unshift( @_, $in );
 2627     return @_;
 2628   }
 2629 }
 2630 
 2631 ## Internal routine that converts limits into the standard array of arrays format
 2632 ##  Some of the cases are probably unneccessary, but better safe than sorry
 2633 ##
 2634 ## IN:  one of the following:
 2635 ##      an undefined value (i.e., no limits were specified)
 2636 ##      a reference to an array of arrays of limits -- [[llim,ulim], [llim,ulim]]
 2637 ##      a reference to an array of limits -- [llim, ulim]
 2638 ##      an array of array references -- ([llim,ulim], [llim,ulim])
 2639 ##      an array of limits -- (llim,ulim)
 2640 ## OUT: an array of array references -- ([llim,ulim], [llim,ulim]) or ([llim,ulim])
 2641 
 2642 sub get_limits_array {
 2643   my $in = shift @_;
 2644   my @out;
 2645 
 2646   if( not defined($in) ) {        #if nothing defined, build default array and return
 2647     @out = ( [$functLLimitDefault, $functULimitDefault] );
 2648     return @out;
 2649   }
 2650   elsif( ref($in) eq 'ARRAY' ) {        #$in is either ref to array, or ref to array of refs
 2651     my @deref = @{$in};
 2652 
 2653     if( ref( $in->[0] ) eq 'ARRAY' ) {    #$in is a ref to an array of array refs
 2654       return @deref;
 2655     }
 2656     else {            #$in was just a ref to an array of numbers
 2657       @out = ( $in );
 2658       return @out;
 2659     }
 2660   }
 2661   else {              #$in was an array of references or numbers
 2662     unshift( @_, $in );
 2663 
 2664     if( ref($_[0]) eq 'ARRAY' ) {     #$in was an array of references, so just return it
 2665       return @_;
 2666     }
 2667     else {            #$in was an array of numbers
 2668       @out = ( \@_ );
 2669       return @out;
 2670     }
 2671   }
 2672 }
 2673 
 2674 #sub check_option_list {
 2675 # my $size = scalar(@_);
 2676 # if( ( $size % 2 ) != 0 ) {
 2677 #   warn "ERROR in answer evaluator generator:\n" .
 2678 #     "Usage: <CODE>str_cmp([\$ans1,  \$ans2],%options)</CODE>
 2679 #     or <CODE> num_cmp([\$num1, \$num2], %options)</CODE><BR>
 2680 #     A list of inputs must be inclosed in square brackets <CODE>[\$ans1, \$ans2]</CODE>";
 2681 # }
 2682 #}
 2683 
 2684 # simple subroutine to display an error message when
 2685 # function compares are called with invalid parameters
 2686 sub function_invalid_params {
 2687   my $correctEqn = shift @_;
 2688   my $error_response = sub {
 2689     my $PGanswerMessage = "Tell your professor that there is an error with the parameters " .
 2690             "to the function answer evaluator";
 2691     return ( 0, $correctEqn, "", $PGanswerMessage );
 2692   };
 2693   return $error_response;
 2694 }
 2695 
 2696 sub clean_up_error_msg {
 2697   my $msg = $_[0];
 2698   $msg =~ s/^\[[^\]]*\][^:]*://;
 2699   $msg =~ s/Unquoted string//g;
 2700   $msg =~ s/may\s+clash.*/does not make sense here/;
 2701   $msg =~ s/\sat.*line [\d]*//g;
 2702   $msg = 'error: '. $msg;
 2703 
 2704   return $msg;
 2705 }
 2706 
 2707 #formats the student and correct answer as specified
 2708 #format must be of a form suitable for sprintf (e.g. '%0.5g'),
 2709 #with the exception that a '#' at the end of the string
 2710 #will cause trailing zeros in the decimal part to be removed
 2711 sub prfmt {
 2712   my($number,$format) = @_;  # attention, the order of format and number are reversed
 2713   my $out;
 2714   if ($format) {
 2715     warn "Incorrect format used: $format. <BR> Format should look something like %4.5g<BR>"
 2716                 unless $format =~ /^\s*%\d*\.?\d*\w#?\s*$/;
 2717 
 2718     if( $format =~ s/#\s*$// ) {  # remove trailing zeros in the decimal
 2719       $out = sprintf( $format, $number );
 2720       $out =~ s/(\.\d*?)0+$/$1/;
 2721       $out =~ s/\.$//;      # in case all decimal digits were zero, remove the decimal
 2722       $out =~ s/e/E/g;        # only use capital E's for exponents. Little e is for 2.71828...
 2723     } elsif (is_a_number($number) ){
 2724       $out = sprintf( $format, $number );
 2725       $out =~ s/e/E/g;        # only use capital E's for exponents. Little e is for 2.71828...
 2726     } else { # number is probably a string representing an arithmetic expression
 2727       $out = $number;
 2728     }
 2729 
 2730   } else {
 2731     if (is_a_number($number)) {# only use capital E's for exponents. Little e is for 2.71828...
 2732       $out = $number;
 2733       $out =~ s/e/E/g;
 2734     } else { # number is probably a string representing an arithmetic expression
 2735       $out = $number;
 2736     }
 2737   }
 2738   return $out;
 2739 }
 2740 #########################################################################
 2741 # Filters for answer evaluators
 2742 #########################################################################
 2743 
 2744 =head2 Filters
 2745 
 2746 =pod
 2747 
 2748 A filter is a short subroutine with the following structure.  It accepts an
 2749 AnswerHash, followed by a hash of options.  It returns an AnswerHash
 2750 
 2751   $ans_hash = filter($ans_hash, %options);
 2752 
 2753 See the AnswerHash.pm file for a list of entries which can be expected to be found
 2754 in an AnswerHash, such as 'student_ans', 'score' and so forth.  Other entries
 2755 may be present for specialized answer evaluators.
 2756 
 2757 The hope is that a well designed set of filters can easily be combined to form
 2758 a new answer_evaluator and that this method will produce answer evaluators which are
 2759 are more robust than the method of copying existing answer evaluators and modifying them.
 2760 
 2761 Here is an outline of how a filter is constructed:
 2762 
 2763   sub filter{
 2764     my $rh_ans = shift;
 2765     my %options = @_;
 2766     assign_option_aliases(\%options,
 2767         'alias1'  => 'option5'
 2768         'alias2'  => 'option7'
 2769     );
 2770     set_default_options(\%options,
 2771         '_filter_name'  =>  'filter',
 2772         'option5'   =>  .0001,
 2773         'option7'   =>  'ascii',
 2774         'allow_unknown_options  =>  0,
 2775     }
 2776     .... body code of filter .......
 2777       if ($error) {
 2778         $rh_ans->throw_error("FILTER_ERROR", "Something went wrong");
 2779         # see AnswerHash.pm for details on using the throw_error method.
 2780 
 2781     $rh_ans;  #reference to an AnswerHash object is returned.
 2782   }
 2783 
 2784 =cut
 2785 
 2786 =head4 compare_numbers
 2787 
 2788 
 2789 =cut
 2790 
 2791 
 2792 sub compare_numbers {
 2793   my ($rh_ans, %options) = @_;
 2794   my ($inVal,$PG_eval_errors,$PG_full_error_report) = PG_answer_eval($rh_ans->{student_ans});
 2795   if ($PG_eval_errors) {
 2796     $rh_ans->throw_error('EVAL','There is a syntax error in your answer');
 2797     $rh_ans->{ans_message} = clean_up_error_msg($PG_eval_errors);
 2798     # return $rh_ans;
 2799   } else {
 2800     $rh_ans->{student_ans} = prfmt($inVal,$options{format});
 2801   }
 2802 
 2803   my $permitted_error;
 2804 
 2805   if ($rh_ans->{tolType} eq 'absolute') {
 2806     $permitted_error = $rh_ans->{tolerance};
 2807   }
 2808   elsif ( abs($rh_ans->{correct_ans}) <= $options{zeroLevel}) {
 2809       $permitted_error = $options{zeroLevelTol};  ## want $tol to be non zero
 2810   }
 2811   else {
 2812     $permitted_error = abs($rh_ans->{tolerance}*$rh_ans->{correct_ans});
 2813   }
 2814 
 2815   my $is_a_number = is_a_number($inVal);
 2816   $rh_ans->{score} = 1 if ( ($is_a_number) and
 2817       (abs( $inVal - $rh_ans->{correct_ans} ) <= $permitted_error) );
 2818   if (not $is_a_number) {
 2819     $rh_ans->{error_message} = "$rh_ans->{error_message}". 'Your answer does not evaluate to a number ';
 2820   }
 2821 
 2822   $rh_ans;
 2823 }
 2824 
 2825 =head4 std_num_filter
 2826 
 2827   std_num_filter($rh_ans, %options)
 2828   returns $rh_ans
 2829 
 2830 Replaces some constants using math_constants, then evaluates a perl expression.
 2831 
 2832 
 2833 =cut
 2834 
 2835 sub std_num_filter {
 2836   my $rh_ans = shift;
 2837   my %options = @_;
 2838   my $in = $rh_ans->input();
 2839   $in = math_constants($in);
 2840   $rh_ans->{type} = 'std_number';
 2841   my ($inVal,$PG_eval_errors,$PG_full_error_report);
 2842   if ($in =~ /\S/) {
 2843     ($inVal,$PG_eval_errors,$PG_full_error_report) = PG_answer_eval($in);
 2844   } else {
 2845     $PG_eval_errors = '';
 2846   }
 2847 
 2848   if ($PG_eval_errors) {        ##error message from eval or above
 2849     $rh_ans->{ans_message} = 'There is a syntax error in your answer';
 2850     $rh_ans->{student_ans} = clean_up_error_msg($PG_eval_errors);
 2851   } else {
 2852     $rh_ans->{student_ans} = $inVal;
 2853   }
 2854   $rh_ans;
 2855 }
 2856 
 2857 =head std_num_array_filter
 2858 
 2859   std_num_array_filter($rh_ans, %options)
 2860   returns $rh_ans
 2861 
 2862 Assumes the {student_ans} field is a numerical  array, and applies BOTH check_syntax and std_num_filter
 2863 to each element of the array.  Does it's best to generate sensible error messages for syntax errors.
 2864 A typical error message displayed in {studnet_ans} might be ( 56, error message, -4).
 2865 
 2866 =cut
 2867 
 2868 sub std_num_array_filter {
 2869   my $rh_ans= shift;
 2870   my %options = @_;
 2871   set_default_options(  \%options,
 2872         '_filter_name'  =>  'std_num_array_filter',
 2873     );
 2874   my @in = @{$rh_ans->{student_ans}};
 2875   my $temp_hash = new AnswerHash;
 2876   my @out=();
 2877   my $PGanswerMessage = '';
 2878   foreach my $item (@in)   {  # evaluate each number in the vector
 2879     $temp_hash->input($item);
 2880     $temp_hash = check_syntax($temp_hash);
 2881     if (defined($temp_hash->{error_flag}) and $temp_hash->{error_flag} eq 'SYNTAX') {
 2882       $PGanswerMessage .= $temp_hash->{ans_message};
 2883       $temp_hash->{ans_message} = undef;
 2884     } else {
 2885       #continue processing
 2886       $temp_hash = std_num_filter($temp_hash);
 2887       if (defined($temp_hash->{ans_message}) and $temp_hash->{ans_message} ) {
 2888         $PGanswerMessage .= $temp_hash->{ans_message};
 2889         $temp_hash->{ans_message} = undef;
 2890       }
 2891     }
 2892     push(@out, $temp_hash->input());
 2893 
 2894   }
 2895   if ($PGanswerMessage) {
 2896     $rh_ans->input( "( " . join(", ", @out ) . " )" );
 2897         $rh_ans->throw_error('SYNTAX', 'There is a syntax error in your answer.');
 2898   } else {
 2899     $rh_ans->input( [@out] );
 2900   }
 2901   $rh_ans;
 2902 }
 2903 
 2904 =head4 function_from_string2
 2905 
 2906 
 2907 
 2908 =cut
 2909 
 2910 sub function_from_string2 {
 2911     my $rh_ans = shift;
 2912     my %options = @_;
 2913   my $eqn = $rh_ans->{student_ans};
 2914   assign_option_aliases(\%options,
 2915         'vars'      => 'ra_vars',
 2916         'var'           => 'ra_vars',
 2917   );
 2918   set_default_options(  \%options,
 2919               'store_in'    =>      'rf_student_ans',
 2920           'ra_vars'   =>  [qw( x y )],
 2921           'debug'     =>  0,
 2922           '_filter_name'  =>  'function_from_string2',
 2923     );
 2924     $rh_ans->{_filter_name} = $options{_filter_name};
 2925     my @VARS = @{ $options{ 'ra_vars'}};
 2926     #warn "VARS = ", join("<>", @VARS) if defined($options{debug}) and $options{debug} ==1;
 2927     my $originalEqn = $eqn;
 2928     $eqn = &math_constants($eqn);
 2929     for( my $i = 0; $i < @VARS; $i++ ) {
 2930         #  This next line is a hack required for 5.6.0 -- it doesn't appear to be needed in 5.6.1
 2931         my ($temp,$er1,$er2) = PG_restricted_eval('"'. $VARS[$i] . '"');
 2932   #$eqn =~ s/\b$VARS[$i]\b/\$VARS[$i]/g;
 2933         $eqn  =~ s/\b$temp\b/\$VARS[$i]/g;
 2934 
 2935   }
 2936   #warn "equation evaluated = $eqn",$rh_ans->pretty_print(), "<br>\noptions<br>\n",
 2937   #     pretty_print(\%options)
 2938   #     if defined($options{debug}) and $options{debug} ==1;
 2939     my ($function_sub,$PG_eval_errors, $PG_full_errors) = PG_answer_eval( q!
 2940       sub {
 2941         my @VARS = @_;
 2942         my $input_str = '';
 2943         for( my $i=0; $i<@VARS; $i++ ) {
 2944           $input_str .= "\$VARS[$i] = $VARS[$i]; ";
 2945         }
 2946         my $PGanswerMessage;
 2947         $input_str .= '! . $eqn . q!';  # need the single quotes to keep the contents of $eqn from being
 2948                                         # evaluated when it is assigned to $input_str;
 2949         my ($out, $PG_eval_errors, $PG_full_errors) = PG_answer_eval($input_str); #Finally evaluated
 2950 
 2951         if ( defined($PG_eval_errors) and $PG_eval_errors =~ /\S/ ) {
 2952             $PGanswerMessage  = clean_up_error_msg($PG_eval_errors);
 2953 # This message seemed too verbose, but it does give extra information, we'll see if it is needed.
 2954 #                    "<br> There was an error in evaluating your function <br>
 2955 #           !. $originalEqn . q! <br>
 2956 #           at ( " . join(', ', @VARS) . " ) <br>
 2957 #            $PG_eval_errors
 2958 #           ";   # this message appears in the answer section which is not process by Latex2HTML so it must
 2959 #                # be in HTML.  That is why $BR is NOT used.
 2960 
 2961       }
 2962       (wantarray) ? ($out, $PGanswerMessage): $out;   # PGanswerMessage may be undefined.
 2963       };
 2964   !);
 2965 
 2966   if (defined($PG_eval_errors) and $PG_eval_errors =~/\S/ ) {
 2967         $PG_eval_errors = clean_up_error_msg($PG_eval_errors);
 2968 
 2969     my $PGanswerMessage = "There was an error in converting the expression
 2970       $BR $originalEqn $BR into a function.
 2971       $BR $PG_eval_errors.";
 2972     $rh_ans->{rf_student_ans} = $function_sub;
 2973     $rh_ans->{ans_message} = $PGanswerMessage;
 2974     $rh_ans->{error_message} = $PGanswerMessage;
 2975     $rh_ans->{error_flag} = 1;
 2976      # we couldn't compile the equation, we'll return an error message.
 2977   } else {
 2978 #     if (defined($options{store_in} )) {
 2979 #       $rh_ans ->{$options{store_in}} = $function_sub;
 2980 #     } else {
 2981 #         $rh_ans->{rf_student_ans} = $function_sub;
 2982 #       }
 2983       $rh_ans ->{$options{store_in}} = $function_sub;
 2984   }
 2985 
 2986     $rh_ans;
 2987 }
 2988 
 2989 =head4 is_zero_array
 2990 
 2991 
 2992 =cut
 2993 
 2994 
 2995 sub is_zero_array {
 2996     my $rh_ans = shift;
 2997     my %options = @_;
 2998     set_default_options(  \%options,
 2999         '_filter_name'  =>  'is_zero_array',
 3000         'tolerance' =>  0.000001,
 3001     );
 3002     my $array = $rh_ans -> {ra_differences};
 3003   my $num = @$array;
 3004   my $i;
 3005   my $max = 0; my $mm;
 3006   for ($i=0; $i< $num; $i++) {
 3007     $mm = $array->[$i] ;
 3008     if  (not is_a_number($mm) ) {
 3009       $max = $mm;  # break out if one of the elements is not a number
 3010       last;
 3011     }
 3012     $max = abs($mm) if abs($mm) > $max;
 3013   }
 3014   if (not is_a_number($max)) {
 3015     $rh_ans->{score} = 0;
 3016       my $error = "WeBWorK was unable evaluate your function. Please check that your
 3017                 expression doesn't take roots of negative numbers, or divide by zero.";
 3018     $rh_ans->throw_error('EVAL',$error);
 3019   } else {
 3020       $rh_ans->{score} = ($max < $options{tolerance} ) ? 1: 0;       # 1 if the array is close to 0;
 3021   }
 3022   $rh_ans;
 3023 }
 3024 
 3025 =head4 best_approx_parameters
 3026 
 3027   best_approx_parameters($rh_ans,%options);   #requires the following fields in $rh_ans
 3028                         {rf_student_ans}      # reference to the test answer
 3029                         {rf_correct_ans}      # reference to the comparison answer
 3030                         {evaluation_points},  # an array of row vectors indicating the points
 3031                                       # to evaluate when comparing the functions
 3032 
 3033                          %options       # debug => 1   gives more error answers
 3034                                     # param_vars => ['']  additional parameters used to adapt to function
 3035                          )
 3036 
 3037 
 3038 The parameters for the comparison function which best approximates the test_function are stored
 3039 in the field {ra_parameters}.
 3040 
 3041 
 3042 The last $dim_of_parms_space variables are assumed to be parameters, and it is also
 3043 assumed that the function \&comparison_fun
 3044 depends linearly on these variables.  This function finds the  values for these parameters which minimizes the
 3045 Euclidean distance (L2 distance) between the test function and the comparison function and the test points specified
 3046 by the array reference  \@rows_of_test_points.  This is assumed to be an array of arrays, with the inner arrays
 3047 determining a test point.
 3048 
 3049 The comparison function should have $dim_of_params_space more input variables than the test function.
 3050 
 3051 
 3052 
 3053 
 3054 
 3055 =cut
 3056 
 3057 # Used internally:
 3058 #
 3059 #   &$determine_param_coeff( $rf_comparison_function # a reference to the correct answer function
 3060 #                    $ra_variables                   # an array of the active input variables to the functions
 3061 #                    $dim_of_params_space            # indicates the number of parameters upon which the
 3062 #                                                    # the comparison function depends linearly.  These are assumed to
 3063 #                                                    # be the last group of inputs to the comparison function.
 3064 #
 3065 #                    %options                        # $options{debug} gives more error messages
 3066 #
 3067 #                                                    # A typical function might look like
 3068 #                                                    # f(x,y,z,a,b) = x^2+a*cos(xz) + b*sin(x) with a parameter
 3069 #                                                    # space of dimension 2 and a variable space of dimension 3.
 3070 #                   )
 3071 #         # returns a list of coefficients
 3072 
 3073 sub best_approx_parameters {
 3074     my $rh_ans = shift;
 3075     my %options = @_;
 3076     set_default_options(\%options,
 3077         '_filter_name'      =>  'best_approx_paramters',
 3078         'allow_unknown_options' =>  1,
 3079     );
 3080     my $errors = undef;
 3081     # This subroutine for the determining the coefficents of the parameters at a given point
 3082     # is pretty specialized, so it is included here as a sub-subroutine.
 3083     my $determine_param_coeffs  = sub {
 3084     my ($rf_fun, $ra_variables, $dim_of_params_space, %options) =@_;
 3085     my @zero_params=();
 3086     for(my $i=1;$i<=$dim_of_params_space;$i++){push(@zero_params,0); }
 3087     my @vars = @$ra_variables;
 3088     my @coeff = ();
 3089     my @inputs = (@vars,@zero_params);
 3090     my ($f0, $f1, $err);
 3091     ($f0, $err) = &{$rf_fun}(@inputs);
 3092     if (defined($err) ) {
 3093       $errors .= "$err ";
 3094     } else {
 3095       for (my $i=@vars;$i<@inputs;$i++) {
 3096         $inputs[$i]=1;  # set one parameter to 1;
 3097         my($f1,$err) = &$rf_fun(@inputs);
 3098         if (defined($err) ) {
 3099           $errors .= " $err ";
 3100         } else {
 3101           push(@coeff, $f1-$f0);
 3102         }
 3103         $inputs[$i]=0;  # set it back
 3104       }
 3105     }
 3106     (\@coeff, $errors);
 3107   };
 3108     my $rf_fun = $rh_ans->{rf_student_ans};
 3109     my $rf_correct_fun = $rh_ans->{rf_correct_ans};
 3110     my $ra_vars_matrix = $rh_ans->{evaluation_points};
 3111     my $dim_of_param_space = @{$options{param_vars}};
 3112     # Short cut.  Bail if there are no param_vars
 3113     unless ($dim_of_param_space >0) {
 3114     $rh_ans ->{ra_parameters} = [];
 3115     return $rh_ans;
 3116     }
 3117     # inputs are row arrays in this case.
 3118     my @zero_params=();
 3119 
 3120     for(my $i=1;$i<=$dim_of_param_space;$i++){push(@zero_params,0); }
 3121     my @rows_of_vars = @$ra_vars_matrix;
 3122     warn "input rows ", pretty_print(\@rows_of_vars) if defined($options{debug}) and $options{debug};
 3123     my $rows = @rows_of_vars;
 3124     my $matrix =new Matrix($rows,$dim_of_param_space);
 3125     my $rhs_vec = new Matrix($rows, 1);
 3126     my $row_num = 1;
 3127     my ($ra_coeff,$val2, $val1, $err1,$err2,@inputs,@vars);
 3128     my $number_of_data_points = $dim_of_param_space +2;
 3129     while (@rows_of_vars and $row_num <= $number_of_data_points) {
 3130      # get one set of data points from the test function;
 3131       @vars = @{ shift(@rows_of_vars) };
 3132       ($val2, $err1) = &{$rf_fun}(@vars);
 3133       $errors .= " $err1 "  if defined($err1);
 3134       @inputs = (@vars,@zero_params);
 3135       ($val1, $err2) = &{$rf_correct_fun}(@inputs);
 3136       $errors .= " $err2 " if defined($err2);
 3137 
 3138       unless (defined($err1) or defined($err2) ) {
 3139           $rhs_vec->assign($row_num,1, $val2-$val1 );
 3140 
 3141     # warn "rhs data  val1=$val1, val2=$val2, val2 - val1 = ", $val2 - $val1 if $options{debug};
 3142     # warn "vars ", join(" | ", @vars) if $options{debug};
 3143 
 3144       ($ra_coeff, $err1) = &{$determine_param_coeffs}($rf_correct_fun,\@vars,$dim_of_param_space,%options);
 3145       if (defined($err1) ) {
 3146         $errors .= " $err1 ";
 3147       } else {
 3148         my @coeff = @$ra_coeff;
 3149         my $col_num=1;
 3150           while(@coeff) {
 3151             $matrix->assign($row_num,$col_num, shift(@coeff) );
 3152             $col_num++;
 3153           }
 3154         }
 3155       }
 3156       $row_num++;
 3157       last if $errors;  # break if there are any errors.
 3158                       # This cuts down on the size of error messages.
 3159                       # However it impossible to check for equivalence at 95% of points
 3160             # which might be useful for functions that are not defined at some points.
 3161   }
 3162     warn "<br> best_approx_parameters: matrix1 <br>  ", " $matrix " if $options{debug};
 3163     warn "<br> best_approx_parameters: vector <br>  ", " $rhs_vec " if $options{debug};
 3164 
 3165    # we have   Matrix * parameter = data_vec + perpendicular vector
 3166    # where the matrix has column vectors defining the span of the parameter space
 3167    # multiply both sides by Matrix_transpose and solve for the parameters
 3168    # This is exactly what the method proj_coeff method does.
 3169    my @array;
 3170    if (defined($errors) ) {
 3171     @array = ();   #     new Matrix($dim_of_param_space,1);
 3172    } else {
 3173     @array = $matrix->proj_coeff($rhs_vec)->list();
 3174    }
 3175   # check size (hack)
 3176   my $max = 0;
 3177   foreach my $val (@array ) {
 3178     $max = abs($val) if  $max < abs($val);
 3179     if (not is_a_number($val) ) {
 3180       $max = "NaN: $val";
 3181       last;
 3182     }
 3183   }
 3184   if ($max =~/NaN/) {
 3185     $errors .= "WeBWorK was unable evaluate your function. Please check that your
 3186                 expression doesn't take roots of negative numbers, or divide by zero.";
 3187   } elsif ($max > $options{maxConstantOfIntegration} ) {
 3188     $errors .= "At least one of the adapting parameters
 3189              (perhaps the constant of integration) is too large: $max,
 3190              ( the maximum allowed is $options{maxConstantOfIntegration} )";
 3191   }
 3192 
 3193     $rh_ans->{ra_parameters} = \@array;
 3194     $rh_ans->throw_error('EVAL', $errors) if defined($errors);
 3195     $rh_ans;
 3196 }
 3197 
 3198 =head4 calculate_difference_vector
 3199 
 3200   calculate_difference_vector( $ans_hash, %options);
 3201 
 3202                 {rf_student_ans},     # a reference to the test function
 3203                                {rf_correct_ans},      # a reference to the correct answer function
 3204                                {evaluation_points},   # an array of row vectors indicating the points
 3205                                           # to evaluate when comparing the functions
 3206                                {ra_parameters}        # these are the (optional) additional inputs to
 3207                                                       # the comparison function which adapt it properly
 3208                                                       # to the problem at hand.
 3209 
 3210                                %options               # mode => 'rel'  specifies that each element in the
 3211                                                       # difference matrix is divided by the correct answer.
 3212                                                       # unless the correct answer is nearly 0.
 3213                               )
 3214 
 3215 =cut
 3216 
 3217 sub calculate_difference_vector {
 3218   my $rh_ans = shift;
 3219   my %options = @_;
 3220   # initialize
 3221   my $rf_fun = $rh_ans -> {rf_student_ans};
 3222   my $rf_correct_fun = $rh_ans -> {rf_correct_ans};
 3223   my $ra_parameters = $rh_ans ->{ra_parameters};
 3224   my @evaluation_points = @{$rh_ans->{evaluation_points} };
 3225   my @parameters = ();
 3226   @parameters = @$ra_parameters if defined($ra_parameters) and ref($ra_parameters) eq 'ARRAY';
 3227   my $errors = undef;
 3228   my @zero_params=();
 3229   for(my $i=1;$i<=@{$ra_parameters};$i++){push(@zero_params,0); }
 3230   my @differences = ();
 3231   my @student_values;
 3232   my @adjusted_student_values;
 3233   my @instructorVals;
 3234   my ($diff,$instructorVal);
 3235   # calculate the vector of differences between the test function and the comparison function.
 3236   while (@evaluation_points) {
 3237     my ($err1, $err2,$err3);
 3238     my @vars = @{ shift(@evaluation_points) };
 3239     my @inputs = (@vars, @parameters);
 3240     my ($inVal,  $correctVal);
 3241     ($inVal, $err1) = &{$rf_fun}(@vars);
 3242     $errors .= " $err1 "  if defined($err1);
 3243     $errors .= " Error detected evaluating student input at (".join(' , ',@vars) ." ) " if  defined($options{debug}) and $options{debug}=1 and defined($err1);
 3244     ($correctVal, $err2) =&{$rf_correct_fun}(@inputs);
 3245     $errors .= " There is an error in WeBWorK's answer to this problem, please alert your instructor.<br> $err2 " if defined($err2);
 3246     $errors .= " Error detected evaluating correct adapted answer  at (".join(' , ',@inputs) ." ) " if defined($options{debug}) and $options{debug}=1 and defined($err2);
 3247     ($instructorVal,$err3)= &$rf_correct_fun(@vars, @zero_params);
 3248     $errors .= " There is an error in WeBWorK's answer to this problem, please alert your instructor.<br> $err3 " if defined($err3);
 3249     $errors .= " Error detected evaluating instructor answer  at (".join(' , ',@vars, @zero_params) ." ) " if defined($options{debug}) and $options{debug}=1 and defined($err3);
 3250     unless (defined($err1) or defined($err2) or defined($err3) ) {
 3251       $diff = ( $inVal - ($correctVal -$instructorVal ) ) - $instructorVal;  #prevents entering too high a number?
 3252       #warn "taking the difference of ", $inVal, " and ", $correctVal, " is ", $diff;
 3253       if (defined($options{tolType}) and $options{tolType} eq 'relative' ) {  #relative tolerance
 3254         #warn "diff = $diff";
 3255         #$diff = ( $inVal - ($correctVal-$instructorVal ) )/abs($instructorVal) -1    if abs($instructorVal) > $options{zeroLevel};
 3256         $diff = ( $inVal - ($correctVal-$instructorVal ) )/$instructorVal -1    if abs($instructorVal) > $options{zeroLevel};
 3257         #$diff = ( $inVal - ($correctVal-$instructorVal- $instructorVal ) )/abs($instructorVal)    if abs($instructorVal) > $options{zeroLevel};
 3258         #warn "diff = $diff,   ", abs( &$rf_correct_fun(@inputs) ) , "-- $correctVal";
 3259       }
 3260     }
 3261     last if $errors;  # break if there are any errors.
 3262                   # This cuts down on the size of error messages.
 3263                   # However it impossible to check for equivalence at 95% of points
 3264                   # which might be useful for functions that are not defined at some points.
 3265         push(@student_values,$inVal);
 3266         push(@adjusted_student_values,(  $inVal - ($correctVal -$instructorVal) ) );
 3267     push(@differences, $diff);
 3268     push(@instructorVals,$instructorVal);
 3269   }
 3270   $rh_ans ->{ra_differences} = \@differences;
 3271   $rh_ans ->{ra_student_values} = \@student_values;
 3272   $rh_ans ->{ra_adjusted_student_values} = \@adjusted_student_values;
 3273   $rh_ans->{ra_instructor_values}=\@instructorVals;
 3274   $rh_ans->throw_error('EVAL', $errors) if defined($errors);
 3275   $rh_ans;
 3276 }
 3277 
 3278 =head4 fix_answer_for_display
 3279 
 3280 =cut
 3281 
 3282 sub fix_answers_for_display {
 3283   my ($rh_ans, %options) = @_;
 3284   if ( $rh_ans->{answerIsString} ==1) {
 3285     $rh_ans = evaluatesToNumber ($rh_ans, %options);
 3286   }
 3287   if (defined ($rh_ans->{student_units})) {
 3288     $rh_ans->{student_ans} = $rh_ans->{student_ans}. ' '. $rh_ans->{student_units};
 3289   }
 3290   $rh_ans->{correct_ans} = $rh_ans->{original_correct_ans};
 3291 
 3292   $rh_ans;
 3293 }
 3294 
 3295 =head4 evaluatesToNumber
 3296 
 3297 =cut
 3298 
 3299 sub evaluatesToNumber {
 3300   my ($rh_ans, %options) = @_;
 3301   if (is_a_numeric_expression($rh_ans->{student_ans})) {
 3302     my ($inVal,$PG_eval_errors,$PG_full_error_report) = PG_answer_eval($rh_ans->{student_ans});
 3303     if ($PG_eval_errors) { # this if statement should never be run
 3304       # change nothing
 3305     } else {
 3306       # change this
 3307       $rh_ans->{student_ans} = prfmt($inVal,$options{format});
 3308     }
 3309   }
 3310   $rh_ans;
 3311 }
 3312 
 3313 =head4 is_numeric_expression
 3314 
 3315 =cut
 3316 
 3317 sub is_a_numeric_expression {
 3318   my $testString = shift;
 3319   my $is_a_numeric_expression = 0;
 3320   my ($inVal,$PG_eval_errors,$PG_full_error_report) = PG_answer_eval($testString);
 3321   if ($PG_eval_errors) {
 3322     $is_a_numeric_expression = 0;
 3323   } else {
 3324     $is_a_numeric_expression = 1;
 3325   }
 3326   $is_a_numeric_expression;
 3327 }
 3328 
 3329 =head4 is_a_number
 3330 
 3331 =cut
 3332 
 3333 sub is_a_number {
 3334   my ($num,%options) =  @_;
 3335   my $process_ans_hash = ( ref( $num ) eq 'AnswerHash' ) ? 1 : 0 ;
 3336   my ($rh_ans);
 3337   if ($process_ans_hash) {
 3338     $rh_ans = $num;
 3339     $num = $rh_ans->{student_ans};
 3340   }
 3341 
 3342   my $is_a_number = 0;
 3343   return $is_a_number unless defined($num);
 3344   $num =~ s/^\s*//; ## remove initial spaces
 3345   $num =~ s/\s*$//; ## remove trailing spaces
 3346 
 3347   ## the following is copied from the online perl manual
 3348   if ($num =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/){
 3349     $is_a_number = 1;
 3350   }
 3351 
 3352   if ($process_ans_hash)   {
 3353         if ($is_a_number == 1 ) {
 3354           $rh_ans->{student_ans}=$num;
 3355           return $rh_ans;
 3356         } else {
 3357           $rh_ans->{student_ans} = "Incorrect number format:  You must enter a number, e.g. -6, 5.3, or 6.12E-3";
 3358           $rh_ans->throw_error('NUMBER', 'You must enter a number, e.g. -6, 5.3, or 6.12E-3');
 3359           return $rh_ans;
 3360         }
 3361   } else {
 3362     return $is_a_number;
 3363   }
 3364 }
 3365 
 3366 =head4 is_a_fraction
 3367 
 3368 =cut
 3369 
 3370 sub is_a_fraction {
 3371   my ($num,%options) =  @_;
 3372   my $process_ans_hash = ( ref( $num ) eq 'AnswerHash' ) ? 1 : 0 ;
 3373   my ($rh_ans);
 3374   if ($process_ans_hash) {
 3375     $rh_ans = $num;
 3376     $num = $rh_ans->{student_ans};
 3377   }
 3378 
 3379   my $is_a_fraction = 0;
 3380   return $is_a_fraction unless defined($num);
 3381   $num =~ s/^\s*//; ## remove initial spaces
 3382   $num =~ s/\s*$//; ## remove trailing spaces
 3383 
 3384   if ($num =~ /^\s*\-?\s*[\/\d\.Ee\s]*$/) {
 3385     $is_a_fraction = 1;
 3386   }
 3387 
 3388     if ($process_ans_hash)   {
 3389       if ($is_a_fraction == 1 ) {
 3390         $rh_ans->{student_ans}=$num;
 3391         return $rh_ans;
 3392       } else {
 3393         $rh_ans->{student_ans} = "Not a number of fraction: You must enter a number or fraction, e.g. -6 or 7/13";
 3394         $rh_ans->throw_error('NUMBER', 'You must enter a number, e.g. -6, 5.3, or 6.12E-3');
 3395         return $rh_ans;
 3396       }
 3397 
 3398       } else {
 3399     return $is_a_fraction;
 3400   }
 3401 }
 3402 
 3403 =head4 phase_pi
 3404   I often discovered that the answers I was getting, when using the arctan function would be off by phases of
 3405   pi, which for the tangent function, were equivalent values. This method allows for this.
 3406 =cut
 3407 
 3408 sub phase_pi {
 3409   my ($num,%options) =  @_;
 3410   my $process_ans_hash = ( ref( $num ) eq 'AnswerHash' ) ? 1 : 0 ;
 3411   my ($rh_ans);
 3412   if ($process_ans_hash) {
 3413     $rh_ans = $num;
 3414     $num = $rh_ans->{correct_ans};
 3415   }
 3416   while( ($rh_ans->{correct_ans}) >  3.14159265358979/2 ){
 3417     $rh_ans->{correct_ans} -= 3.14159265358979;
 3418   }
 3419   while( ($rh_ans->{correct_ans}) <= -3.14159265358979/2 ){
 3420     $rh_ans->{correct_ans} += 3.14159265358979;
 3421   }
 3422   $rh_ans;
 3423 }
 3424 
 3425 =head4 is_an_arithemetic_expression
 3426 
 3427 =cut
 3428 
 3429 sub is_an_arithmetic_expression {
 3430   my ($num,%options) =  @_;
 3431   my $process_ans_hash = ( ref( $num ) eq 'AnswerHash' ) ? 1 : 0 ;
 3432   my ($rh_ans);
 3433   if ($process_ans_hash) {
 3434     $rh_ans = $num;
 3435     $num = $rh_ans->{student_ans};
 3436   }
 3437 
 3438   my $is_an_arithmetic_expression = 0;
 3439   return $is_an_arithmetic_expression unless defined($num);
 3440   $num =~ s/^\s*//; ## remove initial spaces
 3441   $num =~ s/\s*$//; ## remove trailing spaces
 3442 
 3443   if ($num =~ /^[+\-*\/\^\(\)\[\]\{\}\s\d\.Ee]*$/) {
 3444     $is_an_arithmetic_expression =  1;
 3445   }
 3446 
 3447     if ($process_ans_hash)   {
 3448       if ($is_an_arithmetic_expression == 1 ) {
 3449         $rh_ans->{student_ans}=$num;
 3450         return $rh_ans;
 3451       } else {
 3452 
 3453     $rh_ans->{student_ans} = "Not an arithmetic expression: You must enter an arithmetic expression, e.g. -6 or (2.3*4+5/3)^2";
 3454         $rh_ans->throw_error('NUMBER', 'You must enter an arithmetic expression, e.g. -6 or (2.3*4+5/3)^2');
 3455         return $rh_ans;
 3456       }
 3457 
 3458       } else {
 3459     return $is_an_arithmetic_expression;
 3460   }
 3461 }
 3462 
 3463 #
 3464 
 3465 =head4 math_constants
 3466 
 3467 replaces pi, e, and ^ with their Perl equivalents
 3468 if useBaseTenLog is non-zero, convert log to logten
 3469 
 3470 =cut
 3471 
 3472 sub math_constants {
 3473   my($in,%options) = @_;
 3474   my $rh_ans;
 3475   my $process_ans_hash = ( ref( $in ) eq 'AnswerHash' ) ? 1 : 0 ;
 3476   if ($process_ans_hash) {
 3477     $rh_ans = $in;
 3478     $in = $rh_ans->{student_ans};
 3479   }
 3480   # The code fragment above allows this filter to be used when the input is simply a string
 3481   # as well as when the input is an AnswerHash, and options.
 3482   $in =~s/\bpi\b/(4*atan2(1,1))/ge;
 3483   $in =~s/\be\b/(exp(1))/ge;
 3484   $in =~s/\^/**/g;
 3485   if($main::useBaseTenLog) {
 3486     $in =~ s/\blog\b/logten/g;
 3487   }
 3488 
 3489   if ($process_ans_hash)   {
 3490       $rh_ans->{student_ans}=$in;
 3491       return $rh_ans;
 3492     } else {
 3493     return $in;
 3494   }
 3495 }
 3496 
 3497 
 3498 
 3499 =head4 is_array
 3500 
 3501   is_array($rh_ans)
 3502     returns: $rh_ans.   Throws error "NOTARRAY" if this is not an array
 3503 
 3504 =cut
 3505 
 3506 sub is_array  {
 3507   my $rh_ans = shift;
 3508     # return if the result is an array
 3509   return($rh_ans) if  ref($rh_ans->{student_ans}) eq 'ARRAY' ;
 3510   $rh_ans->throw_error("NOTARRAY","The answer is not an array");
 3511   $rh_ans;
 3512 }
 3513 
 3514 =head4 check_syntax
 3515 
 3516   check_syntax( $rh_ans, %options)
 3517     returns an answer hash.
 3518 
 3519 latex2html preview code are installed in the answer hash.
 3520 The input has been transformed, changing 7pi to 7*pi  or 7x to 7*x.
 3521 Syntax error messages may be generated and stored in student_ans
 3522 Additional syntax error messages are stored in {ans_message} and duplicated in {error_message}
 3523 
 3524 
 3525 =cut
 3526 
 3527 sub check_syntax {
 3528         my $rh_ans = shift;
 3529         my %options = @_;
 3530         unless ( defined( $rh_ans->{student_ans} ) ) {
 3531           warn "Check_syntax requires an equation in the field {student_ans} or input";
 3532           $rh_ans->throw_error("1","{student_ans} field not defined");
 3533           return $rh_ans;
 3534         }
 3535         my $in = $rh_ans->{student_ans};
 3536     my $parser = new AlgParserWithImplicitExpand;
 3537     my $ret = $parser -> parse($in);      #for use with loops
 3538 
 3539     if ( ref($ret) )  {   ## parsed successfully
 3540       $parser -> tostring();
 3541       $parser -> normalize();
 3542       $rh_ans->input( $parser -> tostring() );
 3543       $rh_ans->{preview_text_string} = $in;
 3544       $rh_ans->{preview_latex_string} = $parser -> tolatex();
 3545 
 3546     } else {          ## error in parsing
 3547 
 3548       $rh_ans->{'student_ans'}      = 'syntax error:'. $parser->{htmlerror},
 3549       $rh_ans->{'ans_message'}      = $parser -> {error_msg},
 3550       $rh_ans->{'preview_text_string'}  = '',
 3551       $rh_ans->{'preview_latex_string'} = '',
 3552       $rh_ans->throw_error('SYNTAX',  'syntax error in answer:'. $parser->{htmlerror} . "$BR" .$parser -> {error_msg});
 3553     }
 3554 $rh_ans;
 3555 
 3556 }
 3557 
 3558 =head4 check_strings
 3559 
 3560   check_strings ($rh_ans, %options)
 3561     returns $rh_ans
 3562 
 3563 =cut
 3564 
 3565 sub check_strings {
 3566   my ($rh_ans, %options) = @_;
 3567 
 3568   # if the student's answer is a number, simply return the answer hash (unchanged).
 3569 
 3570   #  we allow constructions like -INF to be treated as a string. Thus we ignore an initial
 3571   # - in deciding whether the student's answer is a number or string
 3572 
 3573   my $temp_ans = $rh_ans->{student_ans};
 3574   $temp_ans =~ s/^\s*\-//;   # remove an initial -
 3575 
 3576   if  ( $temp_ans =~ m/[\d+\-*\/^(){}\[\]]|^\s*e\s*$|^\s*pi\s*$/)   {
 3577   # if ( $rh_ans->{answerIsString} == 1) {
 3578   #     #$rh_ans->throw_error('STRING','Incorrect Answer'); # student's answer is a number
 3579   # }
 3580     return $rh_ans;
 3581   }
 3582   # the student's answer is recognized as a string
 3583   my $ans = $rh_ans->{student_ans};
 3584 
 3585 # OVERVIEW of reminder of function:
 3586 # if answer is correct, return correct.  (adjust score to 1)
 3587 # if answer is incorect:
 3588 # 1) determine if the answer is sensible.  if it is, return incorrect.
 3589 # 2) if the answer is not sensible (and incorrect), then return an error message indicating so.
 3590 # no matter what:  throw a 'STRING' error to skip numerical evaluations.  (error flag skips remainder of pre_filters and evaluators)
 3591 # last: 'STRING' post_filter will clear the error (avoiding pink screen.)
 3592 
 3593   my $sensibleAnswer = 0;
 3594   $ans = str_filters( $ans, 'compress_whitespace' );  # remove trailing, leading, and double spaces.
 3595   my ($ans_eval) = str_cmp($rh_ans->{correct_ans});
 3596   my $temp_ans_hash = &$ans_eval($ans);
 3597   $rh_ans->{test} = $temp_ans_hash;
 3598   if ($temp_ans_hash->{score} ==1 ) {     # students answer matches the correct answer.
 3599     $rh_ans->{score} = 1;
 3600     $sensibleAnswer = 1;
 3601   } else {            # students answer does not match the correct answer.
 3602     my $legalString = '';       # find out if string makes sense
 3603     my @legalStrings = @{$options{strings}};
 3604     foreach $legalString (@legalStrings) {
 3605       if ( uc($ans) eq uc($legalString) ) {
 3606         $sensibleAnswer = 1;
 3607         last;
 3608         }
 3609       }
 3610     $sensibleAnswer = 1 unless $ans =~ /\S/;  ## empty answers are sensible
 3611     $rh_ans->throw_error('EVAL', "Your answer is not a recognized answer") unless ($sensibleAnswer);
 3612     # $temp_ans_hash -> setKeys( 'ans_message' => 'Your answer is not a recognized answer' ) unless ($sensibleAnswer);
 3613     # $temp_ans_hash -> setKeys( 'student_ans' => uc($ans) );
 3614   }
 3615   $rh_ans->{student_ans} = $ans;
 3616   if ($sensibleAnswer) {
 3617     $rh_ans->throw_error('STRING', "The student's answer $rh_ans->{student_ans} is interpreted as a string.");
 3618   }
 3619   # warn ("\$rh_ans->{answerIsString} = $rh_ans->{answerIsString}");
 3620   $rh_ans;
 3621 }
 3622 
 3623 =head4 check_units
 3624 
 3625   check_strings ($rh_ans, %options)
 3626     returns $rh_ans
 3627 
 3628 
 3629 =cut
 3630 
 3631 sub check_units {
 3632   my ($rh_ans, %options) = @_;
 3633   my %correct_units = %{$rh_ans-> {rh_correct_units}};
 3634   my $ans = $rh_ans->{student_ans};
 3635   # $ans = '' unless defined ($ans);
 3636   $ans = str_filters ($ans, 'trim_whitespace');
 3637   my $original_student_ans = $ans;
 3638   $rh_ans->{original_student_ans} = $original_student_ans;
 3639 
 3640   # it surprises me that the match below works since the first .* is greedy.
 3641   my ($num_answer, $units) = $ans =~ /^(.*)\s+([^\s]*)$/;
 3642 
 3643   unless ( defined($num_answer) && $units ) {
 3644     # there is an error reading the input
 3645     if ( $ans =~ /\S/ )  {  # the answer is not blank
 3646       $rh_ans -> setKeys( 'ans_message' => "The answer \"$ans\" could not be interpreted " .
 3647         "as a number or an arithmetic expression followed by a unit specification. " .
 3648         "Your answer must contain units." );
 3649       $rh_ans->throw_error('UNITS', "The answer \"$ans\" could not be interpreted " .
 3650         "as a number or an arithmetic expression followed by a unit specification. " .
 3651         "Your answer must contain units." );
 3652     }
 3653     return $rh_ans;
 3654   }
 3655 
 3656   # we have been able to parse the answer into a numerical part and a unit part
 3657 
 3658   # $num_answer = $1;   #$1 and $2 from the regular expression above
 3659   # $units    = $2;
 3660 
 3661   my %units = Units::evaluate_units($units);
 3662   if ( defined( $units{'ERROR'} ) ) {
 3663      # handle error condition
 3664           $units{'ERROR'} = clean_up_error_msg($units{'ERROR'});
 3665     $rh_ans -> setKeys( 'ans_message' => "$units{'ERROR'}" );
 3666     $rh_ans -> throw_error('UNITS', "$units{'ERROR'}");
 3667     return $rh_ans;
 3668   }
 3669 
 3670   my $units_match = 1;
 3671   my $fund_unit;
 3672   foreach $fund_unit (keys %correct_units) {
 3673     next if $fund_unit eq 'factor';
 3674     $units_match = 0 unless $correct_units{$fund_unit} == $units{$fund_unit};
 3675   }
 3676 
 3677   if ( $units_match ) {
 3678         # units are ok.  Evaluate the numerical part of the answer
 3679     $rh_ans->{'tolerance'} = $rh_ans->{'tolerance'}* $correct_units{'factor'}/$units{'factor'}  if
 3680           $rh_ans->{'tolType'} eq 'absolute'; # the tolerance is in the units specified by the instructor.
 3681     $rh_ans->{correct_ans} =  prfmt($rh_ans->{correct_ans}*$correct_units{'factor'}/$units{'factor'});
 3682     $rh_ans->{student_units} = $units;
 3683     $rh_ans->{student_ans} = $num_answer;
 3684 
 3685   } else {
 3686         $rh_ans -> setKeys( ans_message => 'There is an error in the units for this answer.' );
 3687         $rh_ans -> throw_error ( 'UNITS', 'There is an error in the units for this answer.' );
 3688   }
 3689 
 3690   return $rh_ans;
 3691 }
 3692 
 3693 
 3694 
 3695 =head2 Filter utilities
 3696 
 3697 These two subroutines can be used in filters to set default options.  They
 3698 help make filters perform in uniform, predictable ways, and also make it
 3699 easy to recognize from the code which options a given filter expects.
 3700 
 3701 
 3702 =head4 assign_option_aliases
 3703 
 3704 Use this to assign aliases for the standard options.  It must come before set_default_options
 3705 within the subroutine.
 3706 
 3707     assign_option_aliases(\%options,
 3708         'alias1'  => 'option5'
 3709         'alias2'  => 'option7'
 3710     );
 3711 
 3712 
 3713 If the subroutine is called with an option  " alias1 => 23 " it will behave as if it had been
 3714 called with the option " option5 => 23 "
 3715 
 3716 =cut
 3717 
 3718 
 3719 
 3720 sub assign_option_aliases {
 3721   my $rh_options = shift;
 3722   warn "The first entry to set_default_options must be a reference to the option hash" unless ref($rh_options) eq 'HASH';
 3723   my @option_aliases = @_;
 3724   while (@option_aliases) {
 3725     my $alias = shift @option_aliases;
 3726     my $option_key = shift @option_aliases;
 3727 
 3728     if (defined($rh_options->{$alias} )) {                       # if the alias appears in the option list
 3729       if (not defined($rh_options->{$option_key}) ) {          # and the option itself is not defined,
 3730         $rh_options->{$option_key} = $rh_options->{$alias};  # insert the value defined by the alias into the option value
 3731                                                              # the FIRST alias for a given option takes precedence
 3732                                                              # (after the option itself)
 3733       } else {
 3734         warn "option $option_key is already defined as", $rh_options->{$option_key}, "<br>\n",
 3735              "The attempt to override this option with the alias $alias with value ", $rh_options->{$alias},
 3736              " was ignored.";
 3737       }
 3738     }
 3739     delete($rh_options->{$alias});                               # remove the alias from the initial list
 3740   }
 3741 
 3742 }
 3743 
 3744 =head4 set_default_options
 3745 
 3746     set_default_options(\%options,
 3747         '_filter_name'  =>  'filter',
 3748         'option5'   =>  .0001,
 3749         'option7'   =>  'ascii',
 3750         'allow_unknown_options  =>  0,
 3751     }
 3752 
 3753 Note that the first entry is a reference to the options with which the filter was called.
 3754 
 3755 The option5 is set to .0001 unless the option is explicitly set when the subroutine is called.
 3756 
 3757 The B<'_filter_name'> option should always be set, although there is no error if it is missing.
 3758 It is used mainly for debugging answer evaluators and allows
 3759 you to keep track of which filter is currently processing the answer.
 3760 
 3761 If B<'allow_unknown_options'> is set to 0 then if the filter is called with options which do NOT appear in the
 3762 set_default_options list an error will be signaled and a warning message will be printed out.  This provides
 3763 error checking against misspelling an option and is generally what is desired for most filters.
 3764 
 3765 Occasionally one wants to write a filter which accepts a long list of options, not all of which are known in advance,
 3766 but only uses a subset of the options
 3767 provided.  In this case, setting 'allow_unkown_options' to 1 prevents the error from being signaled.
 3768 
 3769 =cut
 3770 
 3771 sub set_default_options {
 3772   my $rh_options = shift;
 3773   warn "The first entry to set_default_options must be a reference to the option hash" unless ref($rh_options) eq 'HASH';
 3774   my %default_options = @_;
 3775   unless ( defined($default_options{allow_unknown_options}) and $default_options{allow_unknown_options} == 1 ) {
 3776     foreach  my $key1 (keys %$rh_options) {
 3777       warn "This option |$key1| is not recognized in this subroutine<br> ", pretty_print($rh_options) unless exists($default_options{$key1});
 3778     }
 3779   }
 3780   foreach my $key (keys %default_options) {
 3781     if  ( not defined($rh_options->{$key} ) and defined( $default_options{$key} )  ) {
 3782       $rh_options->{$key} = $default_options{$key};  #this allows     tol   => undef to allow the tol option, but doesn't define
 3783                                                      # this key unless tol is explicitly defined.
 3784     }
 3785   }
 3786 }
 3787 
 3788 =head2 Problem Grader Subroutines
 3789 
 3790 =cut
 3791 
 3792 ## Problem Grader Subroutines
 3793 
 3794 #####################################
 3795 # This is a model for plug-in problem graders
 3796 #####################################
 3797 sub install_problem_grader {
 3798   my $rf_problem_grader = shift;
 3799   PG_restricted_eval(q!$main::PG_FLAGS{PROBLEM_GRADER_TO_USE} = $rf_problem_grader!);
 3800 }
 3801 
 3802 =head4 std_problem_grader
 3803 
 3804 This is an all-or-nothing grader.  A student must get all parts of the problem write
 3805 before receiving credit.  You should make sure to use this grader on multiple choice
 3806 and true-false questions, otherwise students will be able to deduce how many
 3807 answers are correct by the grade reported by webwork.
 3808 
 3809 
 3810   install_problem_grader(~~&std_problem_grader);
 3811 
 3812 =cut
 3813 
 3814 sub std_problem_grader {
 3815   my $rh_evaluated_answers = shift;
 3816   my $rh_problem_state = shift;
 3817   my %form_options = @_;
 3818   my %evaluated_answers = %{$rh_evaluated_answers};
 3819   #  The hash $rh_evaluated_answers typically contains:
 3820   #    'answer1' => 34, 'answer2'=> 'Mozart', etc.
 3821 
 3822   # By default the  old problem state is simply passed back out again.
 3823   my %problem_state = %$rh_problem_state;
 3824 
 3825   # %form_options might include
 3826   # The user login name
 3827   # The permission level of the user
 3828   # The studentLogin name for this psvn.
 3829   # Whether the form is asking for a refresh or is submitting a new answer.
 3830 
 3831   # initial setup of the answer
 3832   my %problem_result = ( score    => 0,
 3833                errors   => '',
 3834              type   => 'std_problem_grader',
 3835              msg    => '',
 3836   );
 3837   # Checks
 3838 
 3839   my $ansCount = keys %evaluated_answers;  # get the number of answers
 3840 
 3841   unless ($ansCount > 0 ) {
 3842 
 3843     $problem_result{msg} = "This problem did not ask any questions.";
 3844     return(\%problem_result,\%problem_state);
 3845   }
 3846 
 3847   if ($ansCount > 1 ) {
 3848     $problem_result{msg} = 'In order to get credit for this problem all answers must be correct.' ;
 3849   }
 3850 
 3851   unless ($form_options{answers_submitted} == 1) {
 3852     return(\%problem_result,\%problem_state);
 3853   }
 3854 
 3855   my $allAnswersCorrectQ=1;
 3856   foreach my $ans_name (keys %evaluated_answers) {
 3857   # I'm not sure if this check is really useful.
 3858     if ( ( ref($evaluated_answers{$ans_name} ) eq 'HASH' ) or ( ref($evaluated_answers{$ans_name}) eq 'AnswerHash' ) )  {
 3859       $allAnswersCorrectQ = 0 unless( 1 == $evaluated_answers{$ans_name}->{score} );
 3860     }
 3861     else {
 3862       die "Error at file ",__FILE__,"line ", __LINE__,":  Answer |$ans_name| is not a hash reference\n".
 3863          $evaluated_answers{$ans_name} .
 3864          "This probably means that the answer evaluator for this answer\n" .
 3865          "is not working correctly.";
 3866       $problem_result{error} = "Error: Answer $ans_name is not a hash: $evaluated_answers{$ans_name}";
 3867     }
 3868   }
 3869   # report the results
 3870   $problem_result{score} = $allAnswersCorrectQ;
 3871 
 3872   # I don't like to put in this bit of code.
 3873   # It makes it hard to construct error free problem graders
 3874   # I would prefer to know that the problem score was numeric.
 3875   unless (defined($problem_state{recorded_score}) and $problem_state{recorded_score} =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/ ) {
 3876     $problem_state{recorded_score} = 0;  # This gets rid of non-numeric scores
 3877   }
 3878   #
 3879   if ($allAnswersCorrectQ == 1 or $problem_state{recorded_score} == 1) {
 3880     $problem_state{recorded_score} = 1;
 3881   }
 3882   else {
 3883     $problem_state{recorded_score} = 0;
 3884   }
 3885 
 3886   $problem_state{num_of_correct_ans}++ if $allAnswersCorrectQ == 1;
 3887   $problem_state{num_of_incorrect_ans}++ if $allAnswersCorrectQ == 0;
 3888   (\%problem_result, \%problem_state);
 3889 }
 3890 
 3891 =head4 std_problem_grader2
 3892 
 3893 This is an all-or-nothing grader.  A student must get all parts of the problem write
 3894 before receiving credit.  You should make sure to use this grader on multiple choice
 3895 and true-false questions, otherwise students will be able to deduce how many
 3896 answers are correct by the grade reported by webwork.
 3897 
 3898 
 3899   install_problem_grader(~~&std_problem_grader2);
 3900 
 3901 The only difference between the two versions
 3902 is at the end of the subroutine, where std_problem_grader2
 3903 records the attempt only if there have been no syntax errors,
 3904 whereas std_problem_grader records it regardless.
 3905 
 3906 =cut
 3907 
 3908 
 3909 
 3910 sub std_problem_grader2 {
 3911   my $rh_evaluated_answers = shift;
 3912   my $rh_problem_state = shift;
 3913   my %form_options = @_;
 3914   my %evaluated_answers = %{$rh_evaluated_answers};
 3915   #  The hash $rh_evaluated_answers typically contains:
 3916   #    'answer1' => 34, 'answer2'=> 'Mozart', etc.
 3917 
 3918   # By default the  old problem state is simply passed back out again.
 3919   my %problem_state = %$rh_problem_state;
 3920 
 3921   # %form_options might include
 3922   # The user login name
 3923   # The permission level of the user
 3924   # The studentLogin name for this psvn.
 3925   # Whether the form is asking for a refresh or is submitting a new answer.
 3926 
 3927   # initial setup of the answer
 3928   my %problem_result = ( score        => 0,
 3929              errors       => '',
 3930              type       => 'std_problem_grader',
 3931              msg        => '',
 3932   );
 3933 
 3934   # syntax errors are not counted.
 3935   my $record_problem_attempt = 1;
 3936   # Checks
 3937 
 3938   my $ansCount = keys %evaluated_answers;  # get the number of answers
 3939   unless ($ansCount > 0 ) {
 3940     $problem_result{msg} = "This problem did not ask any questions.";
 3941     return(\%problem_result,\%problem_state);
 3942   }
 3943 
 3944   if ($ansCount > 1 ) {
 3945     $problem_result{msg} = 'In order to get credit for this problem all answers must be correct.' ;
 3946   }
 3947 
 3948   unless ($form_options{answers_submitted} == 1) {
 3949     return(\%problem_result,\%problem_state);
 3950   }
 3951 
 3952   my  $allAnswersCorrectQ=1;
 3953   foreach my $ans_name (keys %evaluated_answers) {
 3954   # I'm not sure if this check is really useful.
 3955     if ( ( ref($evaluated_answers{$ans_name} ) eq 'HASH' ) or ( ref($evaluated_answers{$ans_name}) eq 'AnswerHash' ) )  {
 3956       $allAnswersCorrectQ = 0 unless( 1 == $evaluated_answers{$ans_name}->{score} );
 3957     }
 3958     else {
 3959       die "Error at file ",__FILE__,"line ", __LINE__,":  Answer |$ans_name| is not a hash reference\n".
 3960          $evaluated_answers{$ans_name} .
 3961          "This probably means that the answer evaluator for this answer\n" .
 3962          "is not working correctly.";
 3963       $problem_result{error} = "Error: Answer $ans_name is not a hash: $evaluated_answers{$ans_name}";
 3964     }
 3965   }
 3966   # report the results
 3967   $problem_result{score} = $allAnswersCorrectQ;
 3968 
 3969   # I don't like to put in this bit of code.
 3970   # It makes it hard to construct error free problem graders
 3971   # I would prefer to know that the problem score was numeric.
 3972   unless ($problem_state{recorded_score} =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/ ) {
 3973     $problem_state{recorded_score} = 0;  # This gets rid of non-numeric scores
 3974   }
 3975   #
 3976   if ($allAnswersCorrectQ == 1 or $problem_state{recorded_score} == 1) {
 3977     $problem_state{recorded_score} = 1;
 3978   }
 3979   else {
 3980     $problem_state{recorded_score} = 0;
 3981   }
 3982   # record attempt only if there have been no syntax errors.
 3983 
 3984   if ($record_problem_attempt == 1) {
 3985     $problem_state{num_of_correct_ans}++ if $allAnswersCorrectQ == 1;
 3986     $problem_state{num_of_incorrect_ans}++ if $allAnswersCorrectQ == 0;
 3987   }
 3988   else {
 3989     $problem_result{show_partial_correct_answers} = 0 ;  # prevent partial correct answers from being shown for syntax errors.
 3990   }
 3991   (\%problem_result, \%problem_state);
 3992 }
 3993 
 3994 =head4 avg_problem_grader
 3995 
 3996 This grader gives a grade depending on how many questions from the problem are correct.  (The highest
 3997 grade is the one that is kept.  One can never lower the recorded grade on a problem by repeating it.)
 3998 Many professors (and almost all students :-)  ) prefer this grader.
 3999 
 4000 
 4001   install_problem_grader(~~&avg_problem_grader);
 4002 
 4003 =cut
 4004 
 4005 
 4006 sub avg_problem_grader {
 4007     my $rh_evaluated_answers = shift;
 4008   my $rh_problem_state = shift;
 4009   my %form_options = @_;
 4010   my %evaluated_answers = %{$rh_evaluated_answers};
 4011   #  The hash $rh_evaluated_answers typically contains:
 4012   #    'answer1' => 34, 'answer2'=> 'Mozart', etc.
 4013 
 4014   # By default the  old problem state is simply passed back out again.
 4015   my %problem_state = %$rh_problem_state;
 4016 
 4017 
 4018   # %form_options might include
 4019   # The user login name
 4020   # The permission level of the user
 4021   # The studentLogin name for this psvn.
 4022   # Whether the form is asking for a refresh or is submitting a new answer.
 4023 
 4024   # initial setup of the answer
 4025   my  $total=0;
 4026   my %problem_result = ( score        => 0,
 4027              errors       => '',
 4028              type       => 'avg_problem_grader',
 4029              msg        => '',
 4030   );
 4031   my $count = keys %evaluated_answers;
 4032   $problem_result{msg} = 'You can earn partial credit on this problem.' if $count >1;
 4033   # Return unless answers have been submitted
 4034   unless ($form_options{answers_submitted} == 1) {
 4035     return(\%problem_result,\%problem_state);
 4036   }
 4037 
 4038   # Answers have been submitted -- process them.
 4039   foreach my $ans_name (keys %evaluated_answers) {
 4040     # I'm not sure if this check is really useful.
 4041     if ( ( ref($evaluated_answers{$ans_name} ) eq 'HASH' ) or ( ref($evaluated_answers{$ans_name}) eq 'AnswerHash' ) )  {
 4042       $total += $evaluated_answers{$ans_name}->{score};
 4043     }
 4044     else {
 4045       die "Error: Answer |$ans_name| is not a hash reference\n".
 4046          $evaluated_answers{$ans_name} .
 4047          "This probably means that the answer evaluator for this answer\n" .
 4048          "is not working correctly.";
 4049       $problem_result{error} = "Error: Answer $ans_name is not a hash: $evaluated_answers{$ans_name}";
 4050     }
 4051   }
 4052   # Calculate score rounded to three places to avoid roundoff problems
 4053   $problem_result{score} = $total/$count if $count;
 4054   # increase recorded score if the current score is greater.
 4055   $problem_state{recorded_score} = $problem_result{score} if $problem_result{score} > $problem_state{recorded_score};
 4056 
 4057 
 4058   $problem_state{num_of_correct_ans}++ if $total == $count;
 4059   $problem_state{num_of_incorrect_ans}++ if $total < $count ;
 4060   warn "Error in grading this problem the total $total is larger than $count" if $total > $count;
 4061   (\%problem_result, \%problem_state);
 4062 }
 4063 
 4064 =head2 Utility subroutines
 4065 
 4066 =head4
 4067 
 4068   warn pretty_print( $rh_hash_input)
 4069 
 4070 This can be very useful for printing out messages about objects while debugging
 4071 
 4072 =cut
 4073 
 4074 sub pretty_print {
 4075     my $r_input = shift;
 4076     my $out = '';
 4077     if ( not ref($r_input) ) {
 4078       $out = $r_input;    # not a reference
 4079     } elsif ("$r_input" =~/hash/i) {  # this will pick up objects whose '$self' is hash and so works better than ref($r_iput).
 4080       local($^W) = 0;
 4081     $out .= "$r_input " ."<TABLE border = \"2\" cellpadding = \"3\" BGCOLOR = \"#FFFFFF\">";
 4082     foreach my $key (lex_sort( keys %$r_input )) {
 4083       $out .= "<tr><TD> $key</TD><TD>=&gt;</td><td>&nbsp;".pretty_print($r_input->{$key}) . "</td></tr>";
 4084     }
 4085     $out .="</table>";
 4086   } elsif (ref($r_input) eq 'ARRAY' ) {
 4087     my @array = @$r_input;
 4088     $out .= "( " ;
 4089     while (@array) {
 4090       $out .= pretty_print(shift @array) . " , ";
 4091     }
 4092     $out .= " )";
 4093   } elsif (ref($r_input) eq 'CODE') {
 4094     $out = "$r_input";
 4095   } else {
 4096     $out = $r_input;
 4097   }
 4098     $out;
 4099 }
 4100 
 4101 1;

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9