[system] / trunk / webwork / system / courseScripts / PGanswermacros.pl Repository:
ViewVC logotype

Annotation of /trunk/webwork/system/courseScripts/PGanswermacros.pl

Parent Directory Parent Directory | Revision Log Revision Log


Revision 22 - (view) (download) (as text)

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

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9