[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 5329 - (download) (as text) (annotate)
Wed Aug 15 04:03:57 2007 UTC (12 years, 6 months ago) by dpvc
File size: 15641 byte(s)
USe filter names for the answer checkers to identify them in debugging
message more easily.  Mark the MultiAnswer as a Value object.  Handle
allowBlankAnswers properly.

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

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9