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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 5392 - (download) (as text) (annotate)
Sun Aug 19 21:50:23 2007 UTC (12 years, 6 months ago) by dpvc
File size: 17308 byte(s)
Move the context creation to the _init routine so that modifications
to main:: occur at initialization time, not when the file is loaded.

    1 loadMacros("MathObjects.pl");
    2 
    3 =head3 MultiAnswer
    4 
    5  ######################################################################
    6  #
    7  #  MultiAnswer objects let you tie several answer blanks to a single
    8  #  answer checker, so you can have the answer in one blank influence
    9  #  the answer in another.  The MultiAnswer can produce either a single
   10  #  result in the answer results area, or a separate result for each
   11  #  blank.
   12  #
   13  #  To create a MultiAnswer pass a list of answers to MultiAnswer() in the
   14  #  order they will appear in the problem.  For example:
   15  #
   16  #    $mp = MultiAnswer("x^2",-1,1);
   17  #
   18  #  or
   19  #
   20  #    $mp = MultiAnswer(Vector(1,1,1),Vector(2,2,2))->with(singleResult=>1);
   21  #
   22  #  Then, use $mp->ans_rule to create answer blanks for the various parts
   23  #  just as you would ans_rule.  You can pass the width of the blank, which
   24  #  defaults to 20 otherwise.  For example:
   25  #
   26  #    BEGIN_TEXT
   27  #      \(f(x)\) = \{$mp->ans_rule(20)\} produces the same value
   28  #      at \(x\) = \{$mp->ans_rule(10)\} as it does at \(x\) = \{$mp->ans_rule(10)\}.
   29  #    END_TEXT
   30  #
   31  #  Finally, call $mp->cmp to produce the answer checker(s) used in the MultiAnswer.
   32  #  You need to provide a checker routine that will be called to determine if the
   33  #  answers are correct or not.  The checker will only be called if the student
   34  #  answers have no syntax errors and their types match the types of the professor's
   35  #  answers, so you don't have to worry about handling bad data from the student
   36  #  (at least as far as typechecking goes).
   37  #
   38  #  The checker routine should accept four parameters:  a reference to the array
   39  #  of correct answers, a reference to the array of student answers, a reference
   40  #  to the MultiAnswer itself, and a reference to the answer hash.  It should do
   41  #  whatever checking it needs to do and then return a score for the MultiAnswer
   42  #  as a whole (every answer blank will be given the same score), or a reference
   43  #  to an array of scores, one for each blank.  The routine can set error messages
   44  #  via the MultiAnswer's setMessage() method (e.g.,
   45  #
   46  #     $mp->setMessage(1,"The function can't be the identity");
   47  #
   48  #  would set the message for the first answer blank of the MultiAnswer), or can
   49  #  call Value::Error() to generate an error and die.
   50  #
   51  #  The checker routine can be supplied either when the MultiAnswer is created, or
   52  #  when the cmp() method is called.  For example:
   53  #
   54  #      $mp = MultiAnswer("x^2",1,-1)->with(
   55  #        singleResult => 1,
   56  #        checker => sub {
   57  #          my ($correct,$student,$self) = @_;  # get the parameters
   58  #          my ($f,$x1,$x2) = @{$student};      # extract the student answers
   59  #          Value::Error("Function can't be the identity") if ($f == 'x');
   60  #          Value::Error("Function can't be constant") if ($f->isConstant);
   61  #          return $f->eval(x=>$x1) == $f->eval(x=>$x2);
   62  #        },
   63  #      );
   64  #           .
   65  #           .
   66  #           .
   67  #      ANS($mp->cmp);
   68  #
   69  #  or
   70  #
   71  #      $mp = MultiAnswer("x^2",1,-1)->with(singleResult=>1);
   72  #      sub check {
   73  #        my ($correct,$student,$self) = @_;  # get the parameters
   74  #        my ($f,$x1,$x2) = @{$student};      # extract the student answers
   75  #        Value::Error("Function can't be the identity") if ($f == 'x');
   76  #        Value::Error("Function can't be constant") if ($f->isConstant);
   77  #        return $f->eval(x=>$x1) == $f->eval(x=>$x2);
   78  #      };
   79  #           .
   80  #           .
   81  #           .
   82  #      ANS($mp->cmp(checker=>~~&check));
   83  #
   84  ######################################################################
   85 
   86 =cut
   87 
   88 sub _parserMultiAnswer_init {
   89   main::PG_restricted_eval('sub MultiAnswer {MultiAnswer->new(@_)}');
   90 }
   91 
   92 ##################################################
   93 
   94 package MultiAnswer;
   95 our @ISA = qw(Value);
   96 
   97 our $count = 0;                      # counter for unique identifier for multi-parts
   98 our $answerPrefix = "MuLtIaNsWeR";   # answer rule prefix
   99 our $separator = ';';                # separator for singleResult previews
  100 
  101 =pod
  102 
  103  #
  104  #  Create a new MultiAnswer item from a list of items.
  105  #  The items are converted if Value items, if they aren't already.
  106  #  You can set the following fields of the resulting item:
  107  #
  108  #      checker => code            a subroutine to be called to check the
  109  #                                 student answers.  The routine is passed
  110  #                                 four parameters: a reference to the array
  111  #                                 or correct answers, a reference to the
  112  #                                 array of student answers, a reference to the
  113  #                                 MultiAnswer object itself, and a reference to
  114  #                                 the checker's answer hash.  The routine
  115  #                                 should return either a score or a reference
  116  #                                 to an array of scores (one for each answer).
  117  #
  118  #      singleResult => 0 or 1     whether to show only one entry in the
  119  #                                 results area at the top of the page,
  120  #                                 or one for each answer rule.
  121  #                                 (Default: 0)
  122  #
  123  #      namedRules => 0 or 1       whether to use named rules or default
  124  #                                 rule names.  Use named rules if you need
  125  #                                 to intersperse other rules with the
  126  #                                 ones for the MultiAnswer, in which case
  127  #                                 you must use NAMED_ANS not ANS.
  128  #                                 (Default: 0)
  129  #
  130  #      checkTypes => 0 or 1       whether the types of the student and
  131  #                                 professor's answers must match exactly
  132  #                                 or just pass the usual type-match error
  133  #                                 checking (in which case, you should check
  134  #                                 the types before you use the data).
  135  #                            (Default: 1)
  136  #
  137  #      allowBlankAnswers=>0 or 1  whether to remove the blank-check prefilter
  138  #                                 from the answer checkers for the answer
  139  #                                 checkers used for type checking the student's
  140  #                                 answers.
  141  #                                 (Default: 0)
  142  #
  143  #      separator => string        the string to use between entries in the
  144  #                                 results area when singleResult is set.
  145  #                                 (Default: semicolon)
  146  #
  147  #      tex_separator => string    same, but for the preview area.
  148  #                                 (Default: semicolon followed by thinspace)
  149  #
  150  #      format => string           an sprintf-style string used to format the
  151  #                                 students answers for the results area
  152  #                                 when singleResults is true.  If undefined,
  153  #                                 the separator parameter (above) is used to
  154  #                                 form the string.
  155  #                                 (Default: undef)
  156  #
  157  #      tex_format => string       an sprintf-style string used to format the
  158  #                                 students answer previews when singleResults
  159  #                                 mode is in effect.  If undefined, the
  160  #                                 tex_separator (above) is used to form the
  161  #                                 string.
  162  #                                 (Default: undef)
  163  #
  164 
  165 =cut
  166 
  167 my @ans_defaults = (
  168   checker => sub {0},
  169   showCoordinateHints => 0,
  170   showEndpointHints => 0,
  171   showEndTypeHints => 0,
  172 );
  173 
  174 sub new {
  175   my $self = shift; my $class = ref($self) || $self;
  176   my $context = (Value::isContext($_[0]) ? shift : $self->context);
  177   my @data = @_; my @cmp;
  178   Value::Error("%s lists can't be empty",$class) if scalar(@data) == 0;
  179   foreach my $x (@data) {
  180     $x = Value::makeValue($x,context=>$context) unless Value::isValue($x);
  181     push(@cmp,$x->cmp(@ans_defaults));
  182   }
  183   bless {
  184     data => [@data], cmp => [@cmp], ans => [], isValue => 1,
  185     part => 0, singleResult => 0, namedRules => 0,
  186     checkTypes => 1, allowBlankAnswers => 0,
  187     tex_separator => $separator.'\,', separator => $separator.' ',
  188     tex_format => undef, format => undef,
  189     context => $context, id => $answerPrefix.($count++),
  190   }, $class;
  191 }
  192 
  193 #
  194 #  Creates an answer checker (or array of same) to be passed
  195 #  to ANS() or NAMED_ANS().  Any parameters are passed to
  196 #  the individual answer checkers.
  197 #
  198 sub cmp {
  199   my $self = shift; my %options = @_;
  200   foreach my $id ('checker','separator') {
  201     if (defined($options{$id})) {
  202       $self->{$id} = $options{$id};
  203       delete $options{$id};
  204     }
  205   }
  206   die "You must supply a checker subroutine" unless ref($self->{checker}) eq 'CODE';
  207   if ($self->{allowBlankAnswers}) {
  208     foreach my $cmp (@{$self->{cmp}}) {
  209       $cmp->install_pre_filter('erase');
  210       $cmp->install_pre_filter(sub {
  211   my $ans = shift;
  212   $ans->{student_ans} =~ s/^\s+//g;
  213   $ans->{student_ans} =~ s/\s+$//g;
  214   return $ans;
  215       });
  216     }
  217   }
  218   my @cmp = ();
  219   if ($self->{singleResult}) {
  220     push(@cmp,$self->ANS_NAME(0)) if $self->{namedRules};
  221     push(@cmp,$self->single_cmp(%options));
  222   } else {
  223     foreach my $i (0..$self->length-1) {
  224       push(@cmp,$self->ANS_NAME($i)) if $self->{namedRules};
  225       push(@cmp,$self->entry_cmp($i,%options));
  226     }
  227   }
  228   return @cmp;
  229 }
  230 
  231 ######################################################################
  232 
  233 #
  234 #  Get the answer checker used for when all the answers are treated
  235 #  as a single result.
  236 #
  237 sub single_cmp {
  238   my $self = shift; my @correct;
  239   foreach my $cmp (@{$self->{cmp}}) {push(@correct,$cmp->{rh_ans}{correct_ans})}
  240   my $ans = new AnswerEvaluator;
  241   $ans->ans_hash(
  242     correct_ans => join($self->{separator},@correct),
  243     type        => "MultiAnswer",
  244     @_,
  245   );
  246   $ans->install_evaluator(sub {my $ans = shift; (shift)->single_check($ans)},$self);
  247   $ans->install_pre_filter('erase'); # don't do blank check
  248   return $ans;
  249 }
  250 
  251 #
  252 #  Check the answers when they are treated as a single result.
  253 #
  254 #    First, call individual answer checkers to get any type-check errors
  255 #    Then perform the user's checker routine
  256 #    Finally collect the individual answers and errors and combine
  257 #      them for the single result.
  258 #
  259 sub single_check {
  260   my $self = shift; my $ans = shift; $ans->{_filter_name} = "MultiAnswer Single Check";
  261   my $inputs = $main::inputs_ref;
  262   $self->{ans}[0] = $self->{cmp}[0]->evaluate($ans->{student_ans});
  263   foreach my $i (1..$self->length-1)
  264     {$self->{ans}[$i] = $self->{cmp}[$i]->evaluate($inputs->{$self->ANS_NAME($i)})}
  265   my $score = 0; my (@errors,@student,@latex,@text);
  266   my $i = 0; my $nonblank = 0;
  267   if ($self->perform_check($ans)) {
  268     push(@errors,'<TR><TD STYLE="text-align:left" COLSPAN="2">'.$self->{ans}[0]{ans_message}.'</TD></TR>');
  269     $self->{ans}[0]{ans_message} = "";
  270   }
  271   foreach my $result (@{$self->{ans}}) {
  272     $i++; $nonblank |= ($result->{student_ans} =~ m/\S/);
  273     push(@latex,'{'.check_string($result->{preview_latex_string},'\_\_').'}');
  274     push(@text,check_string($result->{preview_text_string},'__'));
  275     push(@student,check_string($result->{student_ans},'__'));
  276     if ($result->{ans_message}) {
  277       push(@errors,'<TR VALIGN="TOP"><TD STYLE="text-align:right; border:0px" NOWRAP>' .
  278                    "<I>In answer $i</I>:&nbsp;</TD>".
  279                    '<TD STYLE="text-align:left; border:0px">'.$result->{ans_message}.'</TD></TR>');
  280     } else {$score += $result->{score}}
  281   }
  282   $ans->score($score/$self->length);
  283   $ans->{ans_message} = $ans->{error_message} = "";
  284   if (scalar(@errors)) {
  285     $ans->{ans_message} = $ans->{error_message} =
  286       '<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="0" CLASS="ArrayLayout">' .
  287        join('<TR><TD HEIGHT="4"></TD></TR>',@errors).
  288       '</TABLE>';
  289   }
  290   if ($nonblank) {
  291     $ans->{preview_latex_string} =
  292       (defined($self->{tex_format}) ? sprintf($self->{tex_format},@latex) : join($self->{tex_separator},@latex));
  293     $ans->{preview_text_string} =
  294       (defined($self->{format}) ? sprintf($self->{format},@text) : join($self->{separator},@text));
  295     $ans->{student_ans} =
  296       (defined($self->{format}) ? sprintf($self->{format},@student) : join($self->{separator},@student));
  297   }
  298   return $ans;
  299 }
  300 
  301 #
  302 #  Return a given string or a default if it is empty or not defined
  303 #
  304 sub check_string {
  305   my $s = shift;
  306   $s = shift unless defined($s) && $s =~ m/\S/;
  307   return $s;
  308 }
  309 
  310 ######################################################################
  311 
  312 #
  313 #  Answer checker to use for individual entries when singleResult
  314 #  is not in effect.
  315 #
  316 sub entry_cmp {
  317   my $self = shift; my $i = shift;
  318   my $ans = new AnswerEvaluator;
  319   $ans->ans_hash(
  320     correct_ans => $self->{cmp}[$i]{rh_ans}{correct_ans},
  321     part        => $i,
  322     type        => "MultiAnswer($i)",
  323     @_,
  324   );
  325   $ans->install_evaluator(sub {my $ans = shift; (shift)->entry_check($ans)},$self);
  326   $ans->install_pre_filter('erase'); # don't do blank check
  327   return $ans;
  328 }
  329 
  330 #
  331 #  Call the correct answser's checker to check for syntax and type errors.
  332 #  If this is the last one, perform the user's checker routine as well
  333 #  Return the individual answer (our answer hash is discarded).
  334 #
  335 sub entry_check {
  336   my $self = shift; my $ans = shift; $ans->{_filter_name} = "MultiAnswer Entry Check";
  337   my $i = $ans->{part};
  338   $self->{ans}[$i] = $self->{cmp}[$i]->evaluate($ans->{student_ans});
  339   $self->{ans}[$i]->score(0);
  340   $self->perform_check($ans) if ($i == $self->length - 1);
  341   return $self->{ans}[$i];
  342 }
  343 
  344 ######################################################################
  345 
  346 #
  347 #  Collect together the correct and student answers, and call the
  348 #  user's checker routine.
  349 #
  350 #  If any of the answers produced errors or the types don't match
  351 #    don't call the user's routine.
  352 #  Otherwise, call it, and if there was an error, report that.
  353 #  Set the individual scores based on the result from the user's routine.
  354 #
  355 sub perform_check {
  356   my $self = shift; my $rh_ans = shift;
  357   $self->context->clearError;
  358   my @correct; my @student;
  359   foreach my $ans (@{$self->{ans}}) {
  360     push(@correct,$ans->{correct_value});
  361     push(@student,$ans->{student_value});
  362     return if $ans->{ans_message} ne "" || !defined($ans->{student_value});
  363     return if $self->{checkTypes} && $ans->{student_value}->type ne $ans->{correct_value}->type &&
  364               !($self->{allowBlankAnswers} && $ans->{student_ans} !~ m/\S/) ;
  365   }
  366   my $inputs = $main::inputs_ref;
  367   $rh_ans->{isPreview} = $inputs->{previewAnswers} ||
  368                          ($inputs_{action} && $inputs->{action} =~ m/^Preview/);
  369   my @result = Value::cmp_compare([@correct],[@student],$self,$rh_ans);
  370   if (!@result && $self->context->{error}{flag}) {$self->cmp_error($self->{ans}[0]); return 1}
  371   my $result = (scalar(@result) > 1 ? [@result] : $result[0] || 0);
  372   if (ref($result) eq 'ARRAY') {
  373     die "Checker subroutine returned the wrong number of results"
  374       if (scalar(@{$result}) != $self->length);
  375     foreach my $i (0..$self->length-1) {$self->{ans}[$i]->score($result->[$i])}
  376   } elsif (Value::matchNumber($result)) {
  377     foreach my $ans (@{$self->{ans}}) {$ans->score($result)}
  378   } else {
  379     die "Checker subroutine should return a number or array of numbers ($result)";
  380   }
  381   return;
  382 }
  383 
  384 ######################################################################
  385 
  386 #
  387 #  The user's checker can call setMessage(n,message) to set the error message
  388 #  for the n-th answer blank.
  389 #
  390 sub setMessage {
  391   my $self = shift; my $i = (shift)-1; my $message = shift;
  392   $self->{ans}[$i]->{ans_message} = $self->{ans}[$i]->{error_message} = $message;
  393 }
  394 
  395 
  396 ######################################################################
  397 
  398 #
  399 #  Produce the name for a named answer blank
  400 #
  401 sub ANS_NAME {
  402   my $self = shift; my $i = shift;
  403   $self->{id}.'_'.$i;
  404 }
  405 
  406 #
  407 #  Record an answer-blank name (when using extensions)
  408 #
  409 sub NEW_NAME {
  410   my $self = shift;
  411   main::RECORD_FORM_LABEL(shift);
  412 }
  413 
  414 #
  415 #  Produce an answer rule for the next item in the list,
  416 #    taking care to use names or extensions as needed
  417 #    by the settings of the MultiAnswer.
  418 #
  419 sub ans_rule {
  420   my $self = shift; my $size = shift || 20;
  421   my $data = $self->{data}[$self->{part}];
  422   my $name = $self->ANS_NAME($self->{part}++);
  423   return $data->named_ans_rule_extension($self->NEW_NAME($name),$size,@_)
  424     if ($self->{singleResult} && $self->{part} > 1);
  425   return $data->ans_rule($size,@_) unless $self->{namedRules};
  426   return $data->named_ans_rule($name,$size,@_);
  427 }
  428 
  429 #
  430 #  Do the same, but for answer arrays, which are generated by the
  431 #    Value objects automatically sized to suit their data.
  432 #    Reset the correct_ans once the array is made
  433 #
  434 sub ans_array {
  435   my $self = shift; my $size = shift || 5; my $HTML;
  436   my $data = $self->{data}[$self->{part}];
  437   my $name = $self->ANS_NAME($self->{part}++);
  438   if ($self->{singleResult} && $self->{part} > 1) {
  439     $HTML = $data->named_ans_array_extension($self->NEW_NAME($name),$size,@_);
  440   } elsif (!$self->{namedRules}) {
  441     $HTML = $data->ans_array($size,@_);
  442   } else {
  443     $HTML = $data->named_ans_array($name,$size,@_);
  444   }
  445   $self->{cmp}[$self->{part}-1] = $data->cmp(@ans_defaults);
  446   return $HTML;
  447 }
  448 
  449 ######################################################################
  450 
  451 1;

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9