[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 3814 - (download) (as text) (annotate)
Wed Dec 14 17:47:00 2005 UTC (14 years, 2 months ago) by sh002i
File size: 176742 byte(s)
Really fix fun_cmp equivalence warning message.

We show the equivalence message when: we're not in preview mode AND the
answers are equivalent AND the answers are not identical. We DON'T CARE
whether the answers are correct or not, because that leaks information
in multipart questions when $showPartialCorrectAnswers is off.

Both the Parser-version (FUNCTION_CMP) and the non-Parser-version
(ORIGINAL_FUNCTION_CMP) behave as descibed above now.

And this time we test *before* we commit...

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

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9