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

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9