[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 32 - (view) (download) (as text)

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

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9