[system] / trunk / pg / lib / Value / AnswerChecker.pm Repository:
ViewVC logotype

View of /trunk/pg/lib/Value/AnswerChecker.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 5989 - (download) (as text) (annotate)
Thu Feb 5 14:55:26 2009 UTC (11 years ago) by dpvc
File size: 70470 byte(s)
Minor changes

    1 
    2 =head1 DESCRIPTION
    3 
    4  #############################################################
    5  #
    6  #  Implements the ->cmp method for Value objects.
    7  #  Otherwise known as MathObjects.  This produces
    8  #  an answer checker appropriate for the type of object.
    9  #  Additional options can be passed to the cmp method to
   10  #  modify its action.
   11  #
   12  #   Usage:  $num = Real(3.45); # Real can be replaced by any other MathObject
   13  #       ANS($num->cmp(compareOptionName => compareOptionValue, ... ))
   14  #
   15  #  The individual Value packages are modified below to add the
   16  #  needed methods.
   17  #
   18  #############################################################
   19 
   20 =cut
   21 
   22 package Value;
   23 
   24 #
   25 #  Context can add default values to the answer checkers by class;
   26 #
   27 $Value::defaultContext->{cmpDefaults} = {};
   28 
   29 =head5 $mathObject->cmp_defaults()
   30 
   31 #  Internal use.
   32 #  Set default flags for the answer checker in this object
   33 #       showTypeWarnings         => 1
   34 #       showEqualErrors          => 1
   35 #       ignoreStrings            => 1
   36 #       studentsMustReduceUnions => 1
   37 #       showUnionReduceWarnings  => 1
   38 #
   39 
   40 =cut
   41 
   42 sub cmp_defaults {(
   43   showTypeWarnings => 1,
   44   showEqualErrors  => 1,
   45   ignoreStrings    => 1,
   46   studentsMustReduceUnions => 1,
   47   showUnionReduceWarnings => 1,
   48 )}
   49 
   50 
   51 #
   52 #  Special Context flags to be set for the student answer
   53 #
   54 
   55 sub cmp_contextFlags {
   56   my $self = shift; my $ans = shift;
   57   return (
   58     StringifyAsTeX => 0,                 # reset this, just in case.
   59     no_parameters => 1,                  # don't let students enter parameters
   60     showExtraParens => 2,                # make student answer painfully unambiguous
   61     reduceConstants => 0,                # don't combine student constants
   62     reduceConstantFunctions => 0,        # don't reduce constant functions
   63     ($ans->{studentsMustReduceUnions} ?
   64       (reduceUnions => 0, reduceSets => 0,
   65        reduceUnionsForComparison => $ans->{showUnionReduceWarnings},
   66        reduceSetsForComparison => $ans->{showUnionReduceWarnings}) :
   67       (reduceUnions => 1, reduceSets => 1,
   68        reduceUnionsForComparison => 1, reduceSetsForComparison => 1)),
   69     ($ans->{requireParenMatch}? (): ignoreEndpointTypes => 1),  # for Intervals
   70   );
   71 }
   72 
   73 
   74 #
   75 #  Create an answer checker for the given type of object
   76 #
   77 
   78 sub cmp {
   79   my $self = shift;
   80   my $ans = new AnswerEvaluator;
   81   my $correct = preformat($self->{correct_ans});
   82   $correct = $self->correct_ans unless defined($correct);
   83   $self->{context} = Value->context unless defined($self->{context});
   84   $ans->ans_hash(
   85     type => "Value (".$self->class.")",
   86     correct_ans => $correct,
   87     correct_value => $self,
   88     $self->cmp_defaults(@_),
   89     %{$self->{context}{cmpDefaults}{$self->class} || {}},  # context-specified defaults
   90     @_,
   91   );
   92   $ans->{debug} = $ans->{rh_ans}{debug};
   93   $ans->install_evaluator(sub {
   94      my $ans = shift;
   95      $ans->{_filter_name} = "MathObjects answer checker";
   96      $ans->{correct_value}->cmp_parse($ans);
   97   });
   98   $ans->install_pre_filter('erase') if $self->{ans_name}; # don't do blank check if answer_array
   99   $self->cmp_diagnostics($ans);
  100   return $ans;
  101 }
  102 
  103 sub correct_ans {preformat(shift->string)}
  104 sub cmp_diagnostics {}
  105 
  106 #
  107 #  Parse the student answer and compute its value,
  108 #    produce the preview strings, and then compare the
  109 #    student and professor's answers for equality.
  110 #
  111 sub cmp_parse {
  112   my $self = shift; my $ans = shift;
  113   #
  114   #  Do some setup
  115   #
  116   my $current = Value->context; # save it for later
  117   my $context = $ans->{correct_value}{context} || $current;
  118   Parser::Context->current(undef,$context); # change to correct answser's context
  119   my $flags = contextSet($context,$self->cmp_contextFlags($ans)); # save old context flags
  120   my $inputs = $self->getPG('$inputs_ref');
  121   $ans->{isPreview} = $inputs->{previewAnswers} || ($inputs->{action} =~ m/^Preview/);
  122   $ans->{cmp_class} = $self->cmp_class($ans) unless $ans->{cmp_class};
  123   $ans->{error_message} = $ans->{ans_message} = ''; # clear any old messages
  124   $ans->{preview_latex_string} = $ans->{preview_text_string} = '';
  125   $context->clearError();
  126   $context->{answerHash} = $ans; # values here can override context flags
  127 
  128   #
  129   #  Parse and evaluate the student answer
  130   #
  131   $ans->score(0);  # assume failure
  132   $ans->{student_value} = $ans->{student_formula} = Parser::Formula($ans->{student_ans});
  133   $ans->{student_value} = Parser::Evaluate($ans->{student_formula})
  134     if defined($ans->{student_formula}) && $ans->{student_formula}->isConstant;
  135 
  136   #
  137   #  If it parsed OK, save the output forms and check if it is correct
  138   #   otherwise report an error
  139   #
  140   if (defined $ans->{student_value}) {
  141     $ans->{student_value} = $self->Package("Formula")->new($ans->{student_value})
  142        unless Value::isValue($ans->{student_value});
  143     $ans->{student_value}{isStudent} = 1;
  144     $ans->{preview_latex_string} = $ans->{student_formula}->TeX;
  145     $ans->{preview_text_string}  = preformat($ans->{student_formula}->string);
  146     #
  147     #  Get the string for the student answer
  148     #
  149     for ($self->getFlag('formatStudentAnswer')) {
  150       /evaluated/i  and do {$ans->{student_ans} = preformat($ans->{student_value}->string); last};
  151       /parsed/i     and do {$ans->{student_ans} = $ans->{preview_text_string}; last};
  152       /reduced/i    and do {
  153   my $oldFlags = contextSet($context,reduceConstants=>1,reduceConstantFunctions=>0);
  154   $ans->{student_ans} = preformat($ans->{student_formula}->substitute()->string);
  155   contextSet($context,%{$oldFags}); last;
  156       };
  157       warn "Unkown student answer format |$ans->{formatStudentAnswer}|";
  158     }
  159     if ($self->cmp_collect($ans)) {
  160       $self->cmp_preprocess($ans);
  161       $self->cmp_equal($ans);
  162       $self->cmp_postprocess($ans) if !$ans->{error_message} && !$ans->{typeError};
  163       $self->cmp_diagnostics($ans);
  164     }
  165   } else {
  166     $self->cmp_collect($ans);
  167     $self->cmp_error($ans);
  168   }
  169   $context->{answerHash} = undef;
  170   contextSet($context,%{$flags});            # restore context values
  171   Parser::Context->current(undef,$current);  # put back the old context
  172   return $ans;
  173 }
  174 
  175 #
  176 #  Check if the object has an answer array and collect the results
  177 #  Build the combined student answer and set the preview values
  178 #
  179 sub cmp_collect {
  180   my $self = shift; my $ans = shift;
  181   return 1 unless $self->{ans_name};
  182   $ans->{preview_latex_string} = $ans->{preview_text_string} = "";
  183   my $OK = $self->ans_collect($ans);
  184   $ans->{student_ans} = $self->format_matrix($ans->{student_formula},@{$self->{format_options}},tth_delims=>1);
  185   return 0 unless $OK;
  186   my $array = $ans->{student_formula};
  187   if ($self->{ColumnVector}) {
  188     my @V = (); foreach my $x (@{$array}) {push(@V,$x->[0])}
  189     $array = [@V];
  190   } elsif (scalar(@{$array}) == 1) {$array = $array->[0]}
  191   my $type = $self;
  192   $type = $self->Package($self->{tree}->type) if $self->isFormula;
  193   $ans->{student_formula} = eval {$type->new($array)->with(ColumnVector=>$self->{ColumnVector})};
  194   if (!defined($ans->{student_formula}) || $self->context->{error}{flag})
  195     {Parser::reportEvalError($@); $self->cmp_error($ans); return 0}
  196   $ans->{student_value} = $ans->{student_formula};
  197   $ans->{preview_text_string} = $ans->{student_ans};
  198   $ans->{preview_latex_string} = $ans->{student_formula}->TeX;
  199   if (Value::isFormula($ans->{student_formula}) && $ans->{student_formula}->isConstant) {
  200     $ans->{student_value} = Parser::Evaluate($ans->{student_formula});
  201     return 0 unless $ans->{student_value};
  202   }
  203   return 1;
  204 }
  205 
  206 #
  207 #  Check if the parsed student answer equals the professor's answer
  208 #
  209 sub cmp_equal {
  210   my $self = shift; my $ans = shift;
  211   my $correct = $ans->{correct_value};
  212   my $student = $ans->{student_value};
  213   if ($correct->typeMatch($student,$ans)) {
  214     $self->context->clearError();
  215     my $equal = $correct->cmp_compare($student,$ans);
  216     if ($self->context->{error}{flag} != $CMP_MESSAGE &&
  217         (defined($equal) || !$ans->{showEqualErrors})) {$ans->score(1) if $equal; return}
  218     $self->cmp_error($ans);
  219   } else {
  220     return if $ans->{ignoreStrings} && (!Value::isValue($student) || $student->type eq 'String');
  221     $ans->{typeError} = 1;
  222     $ans->{ans_message} = $ans->{error_message} =
  223       "Your answer isn't ".lc($ans->{cmp_class})."\n".
  224         "(it looks like ".lc($student->showClass).")"
  225      if !$ans->{isPreview} && $ans->{showTypeWarnings} && !$ans->{error_message};
  226   }
  227 }
  228 
  229 #
  230 #  Perform the comparison, either using the checker supplied
  231 #  by the answer evaluator, or the overloaded == operator.
  232 #
  233 
  234 our $CMP_ERROR = 2;   # a fatal error was detected
  235 our $CMP_WARNING = 3; # a warning was produced
  236 our $CMP_MESSAGE = 4; # an message should be reported for this check
  237 
  238 sub cmp_compare {
  239   my $self = shift; my $other = shift; my $ans = shift; my $nth = shift || '';
  240   my $context = (Value::isValue($self) ? $self->context : Value->context);
  241   return eval {$self == $other} unless ref($ans->{checker}) eq 'CODE';
  242   my @equal = eval {&{$ans->{checker}}($self,$other,$ans,$nth,@_)};
  243   if (!defined($equal) && $@ ne '' && (!$context->{error}{flag} || $ans->{showAllErrors})) {
  244     $nth = "" if ref($nth) eq 'AnswerHash';
  245     $context->setError(["<I>An error occurred while checking your$nth answer:</I>\n".
  246       '<DIV STYLE="margin-left:1em">%s</DIV>',$@],'',undef,undef,$CMP_ERROR);
  247     warn "Please inform your instructor that an error occurred while checking your answer";
  248   }
  249   return (wantarray ? @equal : $equal[0]);
  250 }
  251 
  252 sub cmp_list_compare {Value::List::cmp_list_compare(@_)}
  253 
  254 #
  255 #  Check if types are compatible for equality check
  256 #
  257 sub typeMatch {
  258   my $self = shift;  my $other = shift;
  259   return 1 unless ref($other);
  260   $self->type eq $other->type && !$other->isFormula;
  261 }
  262 
  263 #
  264 #  Class name for cmp error messages
  265 #
  266 sub cmp_class {
  267   my $self = shift; my $ans = shift;
  268   my $class = $self->showClass; $class =~ s/Real //;
  269   return $class if $class =~ m/Formula/;
  270   return "an Interval, Set or Union" if $self->isSetOfReals;
  271   return $class;
  272 }
  273 
  274 #
  275 #  Student answer evaluation failed.
  276 #  Report the error, with formatting, if possible.
  277 #
  278 sub cmp_error {
  279   my $self = shift; my $ans = shift;
  280   my $error = $self->context->{error};
  281   my $message = $error->{message};
  282   if ($error->{pos}) {
  283     my $string = $error->{string};
  284     my ($s,$e) = @{$error->{pos}};
  285     $message =~ s/; see.*//;  # remove the position from the message
  286     $ans->{student_ans} =
  287        protectHTML(substr($string,0,$s)) .
  288        '<SPAN CLASS="parsehilight">' .
  289          protectHTML(substr($string,$s,$e-$s)) .
  290        '</SPAN>' .
  291        protectHTML(substr($string,$e));
  292   }
  293   $self->cmp_Error($ans,$message);
  294 }
  295 
  296 #
  297 #  Set the error message
  298 #
  299 sub cmp_Error {
  300   my $self = shift; my $ans = shift;
  301   return unless scalar(@_) > 0;
  302   $ans->score(0);
  303   $ans->{ans_message} = $ans->{error_message} = join("\n",@_);
  304 }
  305 
  306 #
  307 #  Force a message into the results message column and die
  308 #  (To be used when overriding Parser classes that need
  309 #  to report errors to the student but can't do it in
  310 #  the overridden == since errors are trapped.)
  311 #
  312 sub cmp_Message {
  313   my $message = shift; my $context = Value->context;
  314   $message = [$message,@_] if scalar(@_) > 0;
  315   $context->setError($message,'',undef,undef,$CMP_MESSAGE);
  316   $message = $context->{error}{message};
  317   die $message . traceback() if $context->flags('showTraceback');
  318   die $message . getCaller();
  319 }
  320 
  321 #
  322 #  filled in by sub-classes
  323 #
  324 sub cmp_preprocess {}
  325 sub cmp_postprocess {}
  326 
  327 #
  328 #  Check for unreduced reduced Unions and Sets
  329 #
  330 sub cmp_checkUnionReduce {
  331   my $self = shift; my $student = shift; my $ans = shift; my $nth = shift || '';
  332   return unless $ans->{studentsMustReduceUnions} &&
  333                 $ans->{showUnionReduceWarnings} &&
  334                 !$ans->{isPreview} && !Value::isFormula($student);
  335   return unless $student->isSetOfReals;
  336   my ($result,$error) = $student->isReduced;
  337   return unless $error;
  338   return {
  339     "overlaps" => "Your$nth union contains overlapping intervals",
  340     "overlaps in sets" => "Your$nth union contains sets and intervals that overlap",
  341     "uncombined intervals" => "Your$nth union can be simplified by combining intervals",
  342     "uncombined sets" => "Your$nth union can be simplified by combining some sets",
  343     "repeated elements in set" => "Your$nth union contains sets with repeated elements",
  344     "repeated elements" => "Your$nth set should have no repeated elements",
  345   }->{$error};
  346 }
  347 
  348 #
  349 #  create answer rules of various types
  350 #
  351 sub ans_rule {shift; pgCall('ans_rule',@_)}
  352 sub named_ans_rule {shift; pgCall('NAMED_ANS_RULE',@_)}
  353 sub named_ans_rule_extension {shift; pgCall('NAMED_ANS_RULE_EXTENSION',@_)}
  354 sub ans_array {shift->ans_rule(@_)};
  355 sub named_ans_array {shift->named_ans_rule(@_)};
  356 sub named_ans_array_extension {shift->named_ans_rule_extension(@_)};
  357 
  358 sub pgCall {my $call = shift; &{WeBWorK::PG::Translator::PG_restricted_eval('\&'.$call)}(@_)}
  359 sub pgRef {WeBWorK::PG::Translator::PG_restricted_eval('\&'.shift)}
  360 
  361 our $answerPrefix = "MaTrIx";
  362 
  363 #
  364 #  Lay out a matrix of answer rules
  365 #
  366 sub ans_matrix {
  367   my $self = shift;
  368   my ($extend,$name,$rows,$cols,$size,$open,$close,$sep) = @_;
  369   my $named_extension = pgRef('NAMED_ANS_RULE_EXTENSION');
  370   my $new_name = pgRef('RECORD_FORM_LABEL');
  371   my $HTML = ""; my $ename = $name;
  372   if ($name eq '') {
  373     my $n = pgCall('inc_ans_rule_count');
  374     $name = pgCall('NEW_ANS_NAME',$n);
  375     $ename = $answerPrefix.$n;
  376   }
  377   $self->{ans_name} = $ename;
  378   $self->{ans_rows} = $rows;
  379   $self->{ans_cols} = $cols;
  380   my @array = ();
  381   foreach my $i (0..$rows-1) {
  382     my @row = ();
  383     foreach my $j (0..$cols-1) {
  384       if ($i == 0 && $j == 0) {
  385   if ($extend) {push(@row,&$named_extension(&$new_name($name),$size))}
  386           else {push(@row,pgCall('NAMED_ANS_RULE',$name,$size))}
  387       } else {
  388   push(@row,&$named_extension(&$new_name(ANS_NAME($ename,$i,$j)),$size));
  389       }
  390     }
  391     push(@array,[@row]);
  392   }
  393   $self->format_matrix([@array],open=>$open,close=>$close,sep=>$sep);
  394 }
  395 
  396 sub ANS_NAME {
  397   my ($name,$i,$j) = @_;
  398   $name.'_'.$i.'_'.$j;
  399 }
  400 
  401 
  402 #
  403 #  Lay out an arbitrary matrix
  404 #
  405 sub format_matrix {
  406   my $self = shift; my $array = shift;
  407   my $displayMode = $self->getPG('$displayMode');
  408   $array = [$array] unless ref($array->[0]) eq 'ARRAY';
  409   return $self->format_matrix_tex($array,@_) if ($displayMode eq 'TeX');
  410   return $self->format_matrix_HTML($array,@_);
  411 }
  412 
  413 sub format_matrix_tex {
  414   my $self = shift; my $array = shift;
  415   my %options = (open=>'.',close=>'.',sep=>'',@_);
  416   $self->{format_options} = [%options] unless $self->{format_options};
  417   my ($open,$close,$sep) = ($options{open},$options{close},$options{sep});
  418   my ($rows,$cols) = (scalar(@{$array}),scalar(@{$array->[0]}));
  419   my $tex = ""; my @rows = ();
  420   $open = '\\'.$open if $open =~ m/[{}]/; $close = '\\'.$close if $close =~ m/[{}]/;
  421   $tex .= '\(\left'.$open;
  422   $tex .= '\setlength{\arraycolsep}{2pt}', $sep = '\,'.$sep if $sep;
  423   $tex .= '\begin{array}{'.('c'x$cols).'}';
  424   foreach my $i (0..$rows-1) {push(@rows,join($sep.'&',@{$array->[$i]}))}
  425   $tex .= join('\cr'."\n",@rows);
  426   $tex .= '\end{array}\right'.$close.'\)';
  427   return $tex;
  428 }
  429 
  430 sub format_matrix_HTML {
  431   my $self = shift; my $array = shift;
  432   my %options = (open=>'',close=>'',sep=>'',tth_delims=>0,@_);
  433   $self->{format_options} = [%options] unless $self->{format_options};
  434   my ($open,$close,$sep) = ($options{open},$options{close},$options{sep});
  435   my ($rows,$cols) = (scalar(@{$array}),scalar(@{$array->[0]}));
  436   my $HTML = "";
  437   if ($sep) {$sep = '</TD><TD STYLE="padding: 0px 1px">'.$sep.'</TD><TD>'}
  438        else {$sep = '</TD><TD WIDTH="8px"></TD><TD>'}
  439   foreach my $i (0..$rows-1) {
  440     $HTML .= '<TR><TD HEIGHT="6px"></TD></TR>' if $i;
  441     $HTML .= '<TR ALIGN="MIDDLE"><TD>'.join($sep,EVALUATE(@{$array->[$i]})).'</TD></TR>'."\n";
  442   }
  443   $open = $self->format_delimiter($open,$rows,$options{tth_delims});
  444   $close = $self->format_delimiter($close,$rows,$options{tth_delims});
  445   if ($open ne '' || $close ne '') {
  446     $HTML = '<TR ALIGN="MIDDLE">'
  447           . '<TD>'.$open.'</TD>'
  448           . '<TD WIDTH="2"></TD>'
  449           . '<TD><TABLE BORDER="0" CELLSPACING="0" CELLPADDING="0" CLASS="ArrayLayout">'
  450           .   $HTML
  451           . '</TABLE></TD>'
  452           . '<TD WIDTH="4"></TD>'
  453           . '<TD>'.$close.'</TD>'
  454           . '</TR>'."\n";
  455   }
  456   return '<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="0" CLASS="ArrayLayout"'
  457           . ' STYLE="display:inline;vertical-align:-'.(1.1*$rows-.6).'em">'
  458           . $HTML
  459           . '</TABLE>';
  460 }
  461 
  462 sub EVALUATE {map {(Value::isFormula($_) && $_->isConstant? $_->eval: $_)} @_}
  463 
  464 sub VERBATIM {
  465   my $string = shift;
  466   my $displayMode = Value->getPG('$displayMode');
  467   $string = '\end{verbatim}'.$string.'\begin{verbatim}' if $displayMode eq 'TeX';
  468   return $string;
  469 }
  470 
  471 #
  472 #  Create a tall delimiter to match the line height
  473 #
  474 sub format_delimiter {
  475   my $self = shift; my $delim = shift; my $rows = shift; my $tth = shift;
  476   return '' if $delim eq '' || $delim eq '.';
  477   my $displayMode = $self->getPG('$displayMode');
  478   return $self->format_delimiter_tth($delim,$rows,$tth)
  479     if $tth || $displayMode eq 'HTML_tth' || $displayMode !~ m/^HTML_/;
  480   my $rule = '\vrule width 0pt height '.(.8*$rows).'em depth 0pt';
  481   $rule = '\rule 0pt '.(.8*$rows).'em 0pt' if $displayMode eq 'HTML_jsMath';
  482   $delim = '\\'.$delim if $delim eq '{' || $delim eq '}';
  483   return '\(\left'.$delim.$rule.'\right.\)';
  484 }
  485 
  486 #
  487 #  Data for tth delimiters [top,mid,bot,rep]
  488 #
  489 my %tth_delim = (
  490   '[' => ['&#xF8EE;','','&#xF8F0;','&#xF8EF;'],
  491   ']' => ['&#xF8F9;','','&#xF8FB;','&#xF8FA;'],
  492   '(' => ['&#xF8EB;','','&#xF8ED;','&#xF8EC;'],
  493   ')' => ['&#xF8F6;','','&#xF8F8;','&#xF8F7;'],
  494   '{' => ['&#xF8F1;','&#xF8F2;','&#xF8F3;','&#xF8F4;'],
  495   '}' => ['&#xF8FC;','&#xF8FD;','&#xF8FE;','&#xF8F4;'],
  496   '|' => ['|','','|','|'],
  497   '<' => ['&lt;'],
  498   '>' => ['&gt;'],
  499   '\lgroup' => ['&#xF8F1;','','&#xF8F3;','&#xF8F4;'],
  500   '\rgroup' => ['&#xF8FC;','','&#xF8FE;','&#xF8F4;'],
  501 );
  502 
  503 #
  504 #  Make delimiters as stacks of characters
  505 #
  506 sub format_delimiter_tth {
  507   my $self = shift;
  508   my $delim = shift; my $rows = shift; my $tth = shift;
  509   return '' if $delim eq '' || !defined($tth_delim{$delim});
  510   my $c = $delim; $delim = $tth_delim{$delim};
  511   $c = $delim->[0] if scalar(@{$delim}) == 1;
  512   my $size = ($tth? "": "font-size:175%; ");
  513   return '<SPAN STYLE="'.$size.'margin:0px 2px">'.$c.'</SPAN>'
  514     if $rows == 1 || scalar(@{$delim}) == 1;
  515   my $HTML = "";
  516   if ($delim->[1] eq '') {
  517     $HTML = join('<BR>',$delim->[0],($delim->[3])x(2*($rows-1)),$delim->[2]);
  518   } else {
  519     $HTML = join('<BR>',$delim->[0],($delim->[3])x($rows-1),
  520             $delim->[1],($delim->[3])x($rows-1),
  521             $delim->[2]);
  522   }
  523   return '<DIV STYLE="line-height:90%; margin: 0px 2px">'.$HTML.'</DIV>';
  524 }
  525 
  526 
  527 #
  528 #  Look up the values of the answer array entries, and check them
  529 #  for syntax and other errors.  Build the student answer
  530 #  based on these, and keep track of error messages.
  531 #
  532 
  533 my @ans_cmp_defaults = (showCoodinateHints => 0, checker => sub {0});
  534 
  535 sub ans_collect {
  536   my $self = shift; my $ans = shift;
  537   my $inputs = $self->getPG('$inputs_ref');
  538   my $blank = ($self->getPG('$displayMode') eq 'TeX') ? '\_\_' : '__';
  539   my ($rows,$cols) = ($self->{ans_rows},$self->{ans_cols});
  540   my @array = (); my $data = [$self->value]; my $errors = []; my $OK = 1;
  541   if ($self->{ColumnVector}) {foreach my $x (@{$data}) {$x = [$x]}}
  542   $data = [$data] unless ref($data->[0]) eq 'ARRAY';
  543   foreach my $i (0..$rows-1) {
  544     my @row = (); my $entry;
  545     foreach my $j (0..$cols-1) {
  546       if ($i || $j) {
  547   $entry = $inputs->{ANS_NAME($self->{ans_name},$i,$j)};
  548       } else {
  549   $entry = $ans->{original_student_ans};
  550   $ans->{student_formula} = $ans->{student_value} = undef unless $entry =~ m/\S/;
  551       }
  552       my $result = $data->[$i][$j]->cmp(@ans_cmp_defaults)->evaluate($entry);
  553       $OK &= entryCheck($result,$blank);
  554       push(@row,$result->{student_formula});
  555       entryMessage($result->{ans_message},$errors,$i,$j,$rows,$cols);
  556     }
  557     push(@array,[@row]);
  558   }
  559   $ans->{student_formula} = [@array];
  560   $ans->{ans_message} = $ans->{error_message} = "";
  561   if (scalar(@{$errors})) {
  562     $ans->{ans_message} = $ans->{error_message} =
  563       '<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="0" CLASS="ArrayLayout">'.
  564       join('<TR><TD HEIGHT="4"></TD></TR>',@{$errors}).
  565       '</TABLE>';
  566     $OK = 0;
  567   }
  568   return $OK;
  569 }
  570 
  571 sub entryMessage {
  572   my $message = shift; return unless $message;
  573   my ($errors,$i,$j,$rows,$cols) = @_; $i++; $j++;
  574   my $title;
  575   if ($rows == 1) {$title = "In entry $j"}
  576   elsif ($cols == 1) {$title = "In entry $i"}
  577   else {$title = "In entry ($i,$j)"}
  578   push(@{$errors},"<TR VALIGN=\"TOP\"><TD NOWRAP STYLE=\"text-align:right; border:0px\"><I>$title</I>:&nbsp;</TD>".
  579                   "<TD STYLE=\"text-align:left; border:0px\">$message</TD></TR>");
  580 }
  581 
  582 sub entryCheck {
  583   my $ans = shift; my $blank = shift;
  584   return 1 if defined($ans->{student_value});
  585   if (!defined($ans->{student_formula})) {
  586     $ans->{student_formula} = $ans->{student_ans};
  587     $ans->{student_formula} = $blank unless $ans->{student_formula};
  588   }
  589   return 0
  590 }
  591 
  592 
  593 #
  594 #  Get and Set values in context
  595 #
  596 sub contextSet {
  597   my $context = shift; my %set = (@_);
  598   my $flags = $context->{flags}; my $get = {};
  599   foreach my $id (keys %set) {$get->{$id} = $flags->{$id}; $flags->{$id} = $set{$id}}
  600   return $get;
  601 }
  602 
  603 #
  604 #  Quote HTML characters
  605 #
  606 sub protectHTML {
  607   my $string = shift;
  608   return unless defined($string);
  609   return $string if eval ('$main::displayMode') eq 'TeX';
  610   $string =~ s/&/\&amp;/g;
  611   $string =~ s/</\&lt;/g;
  612   $string =~ s/>/\&gt;/g;
  613   $string;
  614 }
  615 
  616 #
  617 #  Convert newlines to <BR>
  618 #
  619 sub preformat {
  620   my $string = protectHTML(shift);
  621   $string =~ s!\n!<br />!g unless eval('$main::displayMode') eq 'TeX';
  622   $string;
  623 }
  624 
  625 #
  626 #  names for numbers
  627 #
  628 sub NameForNumber {
  629   my $self = shift; my $n = shift;
  630   my $name =  ('zeroth','first','second','third','fourth','fifth',
  631                'sixth','seventh','eighth','ninth','tenth')[$n];
  632   $name = "$n-th" if ($n > 10);
  633   return $name;
  634 }
  635 
  636 #
  637 #  Get a value from the safe compartment
  638 #
  639 sub getPG {
  640   my $self = shift;
  641 #  (WeBWorK::PG::Translator::PG_restricted_eval(shift))[0];
  642   eval ('package main; '.shift);  # faster
  643 }
  644 
  645 #############################################################
  646 #############################################################
  647 
  648 =head3 Value::Real
  649 
  650   Usage ANS( Real(3.56)->cmp() )
  651     Compares response to a real value using 'fuzzy' comparison
  652     compareOptions and default values:
  653         showTypeWarnings => 1,
  654         showEqualErrors  => 1,
  655         ignoreStrings    => 1,
  656 
  657 =cut
  658 
  659 
  660 package Value::Real;
  661 
  662 sub cmp_defaults {(
  663   shift->SUPER::cmp_defaults(@_),
  664   ignoreInfinity => 1,
  665 )}
  666 
  667 sub typeMatch {
  668   my $self = shift; my $other = shift; my $ans = shift;
  669   return 1 unless ref($other);
  670   return 0 if Value::isFormula($other);
  671   return 1 if $other->type eq 'Infinity' && $ans->{ignoreInfinity};
  672   $self->type eq $other->type;
  673 }
  674 
  675 #############################################################
  676 
  677 package Value::Infinity;
  678 
  679 sub cmp_class {'a Number'};
  680 
  681 sub typeMatch {
  682   my $self = shift; my $other = shift; my $ans = shift;
  683   return 1 unless ref($other);
  684   return 0 if Value::isFormula($other);
  685   return 1 if $other->type eq 'Number';
  686   $self->type eq $other->type;
  687 }
  688 
  689 #############################################################
  690 
  691 =head3 Value::String
  692 
  693   Usage:  $s = String("pole");
  694     ANS($s->cmp(typeMatch => Complex("4+i")));
  695         # compare to response 'pole', don't complain about complex number responses.
  696 
  697     compareOptions and default values:
  698       showTypeWarnings => 1,
  699       showEqualErrors  => 1,
  700       ignoreStrings    => 1   # don't complain about string-valued responses
  701       typeMatch        => 'Value::Real'
  702 
  703   Initial and final spaces are ignored when comparing strings.
  704 
  705 =cut
  706 
  707 package Value::String;
  708 
  709 sub cmp_defaults {(
  710   Value::Real->cmp_defaults(@_),
  711   typeMatch => 'Value::Real',
  712 )}
  713 
  714 sub cmp_class {
  715   my $self = shift; my $ans = shift; my $typeMatch = $ans->{typeMatch};
  716   return 'a Word' if !Value::isValue($typeMatch) || $typeMatch->classMatch('String');
  717   return $typeMatch->cmp_class;
  718 };
  719 
  720 sub typeMatch {
  721   my $self = shift; my $other = shift; my $ans = shift;
  722   my $typeMatch = $ans->{typeMatch};
  723   return &$typeMatch($other,$ans) if ref($typeMatch) eq 'CODE';
  724   return 1 if !Value::isValue($typeMatch) || $typeMatch->classMatch('String') ||
  725                  $self->type eq $other->type;
  726   return $typeMatch->typeMatch($other,$ans);
  727 }
  728 
  729 #
  730 #  Remove the blank-check prefilter when the string is empty,
  731 #  and add a filter that removes leading and trailing whitespace.
  732 #
  733 sub cmp {
  734   my $self = shift;
  735   my $cmp = $self->SUPER::cmp(@_);
  736   if ($self->value =~ m/^\s*$/) {
  737     $cmp->install_pre_filter('erase');
  738     $cmp->install_pre_filter(sub {
  739       my $ans = shift;
  740       $ans->{student_ans} =~ s/^\s+//g;
  741       $ans->{student_ans} =~ s/\s+$//g;
  742       return $ans;
  743     });
  744   }
  745   return $cmp;
  746 }
  747 
  748 #############################################################
  749 
  750 =head3 Value::Point
  751 
  752   Usage: $pt = Point("(3,6)"); # preferred
  753          or $pt = Point(3,6);
  754          or $pt = Point([3,6]);
  755          ANS($pt->cmp());
  756 
  757     compareOptions:
  758       showTypeWarnings => 1,   # warns if student response is of incorrect type
  759       showEqualErrors  => 1,
  760       ignoreStrings    => 1,
  761       showDimensionHints => 1, # reports incorrect number of coordinates
  762       showCoordinateHints =>1, # flags individual coordinates that are incorrect
  763 
  764 =cut
  765 
  766 package Value::Point;
  767 
  768 sub cmp_defaults {(
  769   shift->SUPER::cmp_defaults(@_),
  770   showDimensionHints => 1,
  771   showCoordinateHints => 1,
  772 )}
  773 
  774 sub typeMatch {
  775   my $self = shift; my $other = shift; my $ans = shift;
  776   return ref($other) && $other->type eq 'Point' && !$other->isFormula;
  777 }
  778 
  779 #
  780 #  Check for dimension mismatch and incorrect coordinates
  781 #
  782 sub cmp_postprocess {
  783   my $self = shift; my $ans = shift;
  784   return unless $ans->{score} == 0 && !$ans->{isPreview};
  785   my $student = $ans->{student_value};
  786   return if $ans->{ignoreStrings} && (!Value::isValue($student) || $student->type eq 'String');
  787   if ($ans->{showDimensionHints} && $self->length != $student->length) {
  788     $self->cmp_Error($ans,"The number of coordinates is incorrect"); return;
  789   }
  790   if ($ans->{showCoordinateHints}) {
  791     my @errors;
  792     foreach my $i (1..$self->length) {
  793       push(@errors,"The ".$self->NameForNumber($i)." coordinate is incorrect")
  794   if ($self->{data}[$i-1] != $student->{data}[$i-1]);
  795     }
  796     $self->cmp_Error($ans,@errors); return;
  797   }
  798 }
  799 
  800 sub correct_ans {
  801   my $self = shift;
  802   return $self->SUPER::correct_ans unless $self->{ans_name};
  803   Value::VERBATIM($self->format_matrix([[@{$self->{data}}]],@{$self->{format_options}},tth_delims=>1));
  804 }
  805 
  806 sub ANS_MATRIX {
  807   my $self = shift;
  808   my $extend = shift; my $name = shift;
  809   my $size = shift || 5;
  810   my $def = $self->context->lists->get('Point');
  811   my $open = $self->{open} || $def->{open}; my $close = $self->{close} || $def->{close};
  812   $self->ans_matrix($extend,$name,1,$self->length,$size,$open,$close,',');
  813 }
  814 
  815 sub ans_array {my $self = shift; $self->ANS_MATRIX(0,'',@_)}
  816 sub named_ans_array {my $self = shift; $self->ANS_MATRIX(0,@_)}
  817 sub named_ans_array_extension {my $self = shift; $self->ANS_MATRIX(1,@_)}
  818 
  819 #############################################################
  820 
  821 =head3 Value::Vector
  822 
  823   Usage:  $vec = Vector("<3,6,7>");
  824           or $vec = Vector(3,6,7);
  825           or $vec = Vector([3,6,7]);
  826           ANS($vec->cmp());
  827 
  828     compareOptions:
  829       showTypeWarnings    => 1,   # warns if student response is of incorrect type
  830       showEqualErrors     => 1,
  831       ignoreStrings       => 1,
  832       showDimensionHints  => 1, # reports incorrect number of coordinates
  833       showCoordinateHints => 1, # flags individual coordinates which are incorrect
  834       promotePoints       => 0, # allow students to enter vectors as points (3,5,6)
  835       parallel            => 1, # response is correct if it is parallel to correct answer
  836       sameDirection       => 1, # response is correct if it has same orientation as correct answer
  837                                 #  (only has an effect when parallel => 1 is specified)
  838 
  839 
  840 =cut
  841 
  842 package Value::Vector;
  843 
  844 sub cmp_defaults {(
  845   shift->SUPER::cmp_defaults(@_),
  846   showDimensionHints => 1,
  847   showCoordinateHints => 1,
  848   promotePoints => 0,
  849   parallel => 0,
  850   sameDirection => 0,
  851 )}
  852 
  853 sub typeMatch {
  854   my $self = shift; my $other = shift; my $ans = shift;
  855   return 0 unless ref($other) && !$other->isFormula;
  856   return $other->type eq 'Vector' ||
  857      ($ans->{promotePoints} && $other->type eq 'Point');
  858 }
  859 
  860 #
  861 #  check for dimension mismatch
  862 #        for parallel vectors, and
  863 #        for incorrect coordinates
  864 #
  865 sub cmp_postprocess {
  866   my $self = shift; my $ans = shift;
  867   return unless $ans->{score} == 0 && !$ans->{isPreview};
  868   my $student = $ans->{student_value};
  869   return if $ans->{ignoreStrings} && (!Value::isValue($student) || $student->type eq 'String');
  870   if ($self->length != $student->length) {
  871     ($self,$student) = $self->cmp_pad($student);
  872     if ($ans->{showDimensionHints} && $self->length != $student->length) {
  873       $self->cmp_Error($ans,"The number of coordinates is incorrect"); return;
  874     }
  875   }
  876   if ($ans->{parallel} && !$student->isFormula && !$student->classMatch('String') &&
  877       $self->isParallel($student,$ans->{sameDirection})) {
  878     $ans->score(1); return;
  879   }
  880   if ($ans->{showCoordinateHints} && !$ans->{parallel}) {
  881     my @errors;
  882     foreach my $i (1..$self->length) {
  883       push(@errors,"The ".$self->NameForNumber($i)." coordinate is incorrect")
  884   if ($self->{data}[$i-1] != $student->{data}[$i-1]);
  885     }
  886     $self->cmp_Error($ans,@errors); return;
  887   }
  888 }
  889 
  890 #
  891 #  Pad the student or correct answer if either is in ijk notation
  892 #  and they are not the same dimension.  Only add zeros when the other one
  893 #  also has zeros in those places.
  894 #
  895 sub cmp_pad {
  896   my $self = shift; my $student = shift;
  897   if (($self->getFlag("ijk") || $student->getFlag("ijk")) && $self->getFlag("ijkAnyDimension")) {
  898     $self = $self->copy; $student = $student->copy;
  899     while ($self->length > $student->length && $self->{data}[$student->length] == 0)
  900       {push(@{$student->{data}},Value::Real->new(0))}
  901     while ($self->length < $student->length && $student->{data}[$self->length] == 0)
  902       {push(@{$self->{data}},Value::Real->new(0))}
  903   }
  904   return ($self,$student);
  905 }
  906 
  907 sub correct_ans {
  908   my $self = shift;
  909   return $self->SUPER::correct_ans unless $self->{ans_name};
  910   return Value::VERBATIM($self->format_matrix([[$self->value]],@{$self->{format_options}},tth_delims=>1))
  911     unless $self->{ColumnVector};
  912   my @array = (); foreach my $x ($self->value) {push(@array,[$x])}
  913   return Value::VERBATIM($self->format_matrix([@array],@{$self->{format_options}},tth_delims=>1));
  914 }
  915 
  916 sub ANS_MATRIX {
  917   my $self = shift;
  918   my $extend = shift; my $name = shift;
  919   my $size = shift || 5; my ($def,$open,$close);
  920   $def = $self->context->lists->get('Matrix');
  921   $open = $self->{open} || $def->{open}; $close = $self->{close} || $def->{close};
  922   return $self->ans_matrix($extend,$name,$self->length,1,$size,$open,$close)
  923     if ($self->{ColumnVector});
  924   $def = $self->context->lists->get('Vector');
  925   $open = $self->{open} || $def->{open}; $close = $self->{close} || $def->{close};
  926   $self->ans_matrix($extend,$name,1,$self->length,$size,$open,$close,',');
  927 }
  928 
  929 sub ans_array {my $self = shift; $self->ANS_MATRIX(0,'',@_)}
  930 sub named_ans_array {my $self = shift; $self->ANS_MATRIX(0,@_)}
  931 sub named_ans_array_extension {my $self = shift; $self->ANS_MATRIX(1,@_)}
  932 
  933 
  934 #############################################################
  935 
  936 =head3 Value::Matrix
  937 
  938   Usage   $ma = Matrix([[3,6],[2,5]]) or $ma =Matrix([3,6],[2,5])
  939           ANS($ma->cmp());
  940 
  941     compareOptions:
  942 
  943       showTypeWarnings    => 1, # warns if student response is of incorrect type
  944       showEqualErrors     => 1, # reports messages that occur during element comparisons
  945       ignoreStrings       => 1,
  946       showDimensionHints  => 1, # reports incorrect number of coordinates
  947       showCoordinateHints => 1, # flags individual coordinates which are incorrect
  948 
  949 
  950 =cut
  951 
  952 package Value::Matrix;
  953 
  954 sub cmp_defaults {(
  955   shift->SUPER::cmp_defaults(@_),
  956   showDimensionHints => 1,
  957   showEqualErrors => 0,
  958 )}
  959 
  960 sub typeMatch {
  961   my $self = shift; my $other = shift; my $ans = shift;
  962   return 0 unless ref($other) && !$other->isFormula;
  963   return $other->type eq 'Matrix' ||
  964     ($other->type =~ m/^(Point|list)$/ &&
  965      $other->{open}.$other->{close} eq $self->{open}.$self->{close});
  966 }
  967 
  968 sub cmp_preprocess {
  969   my $self = shift; my $ans = shift;
  970   my $student = $ans->{student_value};
  971   return if $student->type ne 'Matrix';
  972   my @d1 = $self->dimensions; my @d2 = $student->dimensions;
  973   $ans->{student_value} = $student->make([$student->value])
  974     if (scalar(@d2) == 1 && scalar(@d1) == 2);
  975 }
  976 
  977 sub cmp_postprocess {
  978   my $self = shift; my $ans = shift;
  979   return unless $ans->{score} == 0 &&
  980     !$ans->{isPreview} && $ans->{showDimensionHints};
  981   my $student = $ans->{student_value};
  982   return if $ans->{ignoreStrings} && (!Value::isValue($student) || $student->type eq 'String');
  983   my @d1 = $self->dimensions; my @d2 = $student->dimensions;
  984   if (scalar(@d1) != scalar(@d2)) {
  985     $self->cmp_Error($ans,"Matrix dimension is not correct");
  986     return;
  987   } else {
  988     foreach my $i (0..scalar(@d1)-1) {
  989       if ($d1[$i] != $d2[$i]) {
  990   $self->cmp_Error($ans,"Matrix dimension is not correct");
  991   return;
  992       }
  993     }
  994   }
  995 }
  996 
  997 sub correct_ans {
  998   my $self = shift;
  999   return $self->SUPER::correct_ans unless $self->{ans_name};
 1000   my @array = $self->value; @array = ([@array]) if $self->isRow;
 1001   Value::VERBATIM($self->format_matrix([$self->value],@{$self->{format_options}},tth_delims=>1));
 1002 }
 1003 
 1004 sub ANS_MATRIX {
 1005   my $self = shift;
 1006   my $extend = shift; my $name = shift;
 1007   my $size = shift || 5;
 1008   my $def = $self->context->lists->get('Matrix');
 1009   my $open = $self->{open} || $def->{open}; my $close = $self->{close} || $def->{close};
 1010   my @d = $self->dimensions;
 1011   Value::Error("Can't create ans_array for %d-dimensional matrix",scalar(@d))
 1012     if (scalar(@d) > 2);
 1013   @d = (1,@d) if (scalar(@d) == 1);
 1014   $self->ans_matrix($extend,$name,@d,$size,$open,$close,'');
 1015 }
 1016 
 1017 sub ans_array {my $self = shift; $self->ANS_MATRIX(0,'',@_)}
 1018 sub named_ans_array {my $self = shift; $self->ANS_MATRIX(0,@_)}
 1019 sub named_ans_array_extension {my $self = shift; $self->ANS_MATRIX(1,@_)}
 1020 
 1021 #############################################################
 1022 
 1023 =head3   Value::Interval
 1024 
 1025   Usage:    $interval = Interval("(1,2]");
 1026             or $interval = Interval('(',1,2,']');
 1027             ANS($inteval->cmp);
 1028 
 1029       compareOptions and defaults:
 1030       showTypeWarnings  => 1,
 1031       showEqualErrors   => 1,
 1032       ignoreStrings     => 1,
 1033       showEndpointHints => 1, # show hints about which end point values are correct
 1034       showEndTypeHints  => 1, # show hints about endpoint types
 1035       requireParenMatch => 1,
 1036 
 1037 
 1038 =cut
 1039 
 1040 package Value::Interval;
 1041 
 1042 sub cmp_defaults {(
 1043   shift->SUPER::cmp_defaults(@_),
 1044   showEndpointHints => 1,
 1045   showEndTypeHints => 1,
 1046   requireParenMatch => 1,
 1047 )}
 1048 
 1049 sub typeMatch {
 1050   my $self = shift; my $other = shift;
 1051   return 0 if !Value::isValue($other) || $other->isFormula;
 1052   return $other->canBeInUnion;
 1053 }
 1054 
 1055 #
 1056 #  Check for unreduced sets and unions
 1057 #
 1058 sub cmp_compare {
 1059   my $self = shift; my $student = shift; my $ans = shift;
 1060   my $error = $self->cmp_checkUnionReduce($student,$ans,@_);
 1061   if ($error) {$self->context->setError($error,'',undef,undef,$CMP_WARNING); return}
 1062   $self->SUPER::cmp_compare($student,$ans,@_);
 1063 }
 1064 
 1065 #
 1066 #  Check for wrong enpoints and wrong type of endpoints
 1067 #
 1068 sub cmp_postprocess {
 1069   my $self = shift; my $ans = shift;
 1070   return unless $ans->{score} == 0 && !$ans->{isPreview};
 1071   my $other = $ans->{student_value};
 1072   return if $ans->{ignoreStrings} && (!Value::isValue($other) || $other->type eq 'String');
 1073   return unless $other->classMatch('Interval');
 1074   my @errors;
 1075   if ($ans->{showEndpointHints}) {
 1076     push(@errors,"Your left endpoint is incorrect")
 1077       if ($self->{data}[0] != $other->{data}[0]);
 1078     push(@errors,"Your right endpoint is incorrect")
 1079       if ($self->{data}[1] != $other->{data}[1]);
 1080   }
 1081   if (scalar(@errors) == 0 && $ans->{showEndTypeHints} && $ans->{requireParenMatch}) {
 1082     push(@errors,"The type of interval is incorrect")
 1083       if ($self->{open}.$self->{close} ne $other->{open}.$other->{close});
 1084   }
 1085   $self->cmp_Error($ans,@errors);
 1086 }
 1087 
 1088 #############################################################
 1089 
 1090 =head3 Value::Set
 1091 
 1092   Usage:   $set = Set(5,6,'a', 'b')
 1093         or $set = Set("{5, 6, a, b}")
 1094 
 1095         The object is a finite set of real numbers. It can be used with Union and
 1096         Interval.
 1097 
 1098   Examples:  Interval("(-inf,inf)") - Set(0)
 1099              Compute("R-{0}")   # in Interval context: Context("Interval");
 1100 
 1101 =cut
 1102 
 1103 package Value::Set;
 1104 
 1105 sub typeMatch {
 1106   my $self = shift; my $other = shift;
 1107   return 0 if !Value::isValue($other) || $other->isFormula;
 1108   return $other->canBeInUnion;
 1109 }
 1110 
 1111 #
 1112 #  Use the List checker for sets, in order to get
 1113 #  partial credit.  Set the various types for error
 1114 #  messages.
 1115 #
 1116 sub cmp_defaults {(
 1117   Value::List::cmp_defaults(@_),
 1118   typeMatch => 'Value::Real',
 1119   list_type => 'a set',
 1120   entry_type => 'a number',
 1121   removeParens => 0,
 1122   showParenHints => 1,
 1123   implicitList => 0,
 1124 )}
 1125 
 1126 #
 1127 #  Use the list checker if the student answer is a set
 1128 #    otherwise use the standard compare (to get better
 1129 #    error messages).
 1130 #
 1131 sub cmp_equal {
 1132   my ($self,$ans) = @_;
 1133   return $self->SUPER::cmp_equal($ans) unless $ans->{student_value}->type eq 'Set';
 1134   my $error = $self->cmp_checkUnionReduce($ans->{student_value},$ans);
 1135   if ($error) {$self->cmp_Error($ans,$error); return}
 1136   return Value::List::cmp_equal(@_);
 1137 }
 1138 
 1139 #
 1140 #  Check for unreduced sets and unions
 1141 #
 1142 sub cmp_compare {
 1143   my $self = shift; my $student = shift; my $ans = shift;
 1144   my $error = $self->cmp_checkUnionReduce($student,$ans,@_);
 1145   if ($error) {$self->context->setError($error,'',undef,undef,$CMP_WARNING); return}
 1146   $self->SUPER::cmp_compare($student,$ans,@_);
 1147 }
 1148 
 1149 #############################################################
 1150 
 1151 =head3 Value::Union
 1152 
 1153   Usage: $union = Union("[4,5] U [6,7]");
 1154          or $union = Union(Interval("[4,5]",Interval("[6,7]"));
 1155          ANS($union->cmp());
 1156 
 1157 
 1158 =cut
 1159 
 1160 package Value::Union;
 1161 
 1162 sub typeMatch {
 1163   my $self = shift; my $other = shift;
 1164   return 0 unless ref($other) && !$other->isFormula;
 1165   return $other->length == 2 &&
 1166          ($other->{open} eq '(' || $other->{open} eq '[') &&
 1167          ($other->{close} eq ')' || $other->{close} eq ']')
 1168      if $other->type =~ m/^(Point|List)$/;
 1169   $other->isSetOfReals;
 1170 }
 1171 
 1172 #
 1173 #  Use the List checker for unions, in order to get
 1174 #  partial credit.  Set the various types for error
 1175 #  messages.
 1176 #
 1177 my $typeMatchInterval = Value::Interval->make(0,1);
 1178 sub cmp_defaults {(
 1179   Value::List::cmp_defaults(@_),
 1180   typeMatch => $typeMatchInterval,
 1181   list_type => 'an interval, set or union',
 1182   short_type => 'a union',
 1183   entry_type => 'an interval or set',
 1184 )}
 1185 
 1186 sub cmp_equal {
 1187   my $self = shift; my $ans = shift;
 1188   my $error = $self->cmp_checkUnionReduce($ans->{student_value},$ans);
 1189   if ($error) {$self->cmp_Error($ans,$error); return}
 1190   Value::List::cmp_equal($self,$ans);
 1191 }
 1192 
 1193 #
 1194 #  Check for unreduced sets and unions
 1195 #
 1196 sub cmp_compare {
 1197   my $self = shift; my $student = shift; my $ans = shift;
 1198   my $error = $self->cmp_checkUnionReduce($student,$ans,@_);
 1199   if ($error) {$self->context->setError($error,'',undef,undef,$CMP_WARNING); return}
 1200   $self->SUPER::cmp_compare($student,$ans,@_);
 1201 }
 1202 
 1203 #############################################################
 1204 
 1205 =head3 Value::List
 1206 
 1207   Usage:  $lst = List("1, x, <4,5,6>"); # list of a real, a formula and a vector.
 1208           or $lst = List(Real(1), Formula("x"), Vector(4,5,6));
 1209           ANS($lst->cmp(showHints=>1));
 1210 
 1211     compareOptions and defaults:
 1212       showTypeWarnings => 1,
 1213       showEqualErrors  => 1,         # show errors produced when checking equality of entries
 1214       ignoreStrings    => 1,         # don't show type warnings for strings
 1215       studentsMustReduceUnions => 1,
 1216       showUnionReduceWarnings => 1,
 1217       showHints => undef,            # automatically set to 1 if $showPartialCorrectAnswers == 1
 1218       showLengthHints => undef,      # automatically set to 1 if $showPartialCorrectAnswers == 1
 1219       showParenHints => undef,       # automatically set to 1 if $showPartialCorrectAnswers == 1
 1220       partialCredit => undef,        # automatically set to 1 if $showPartialCorrectAnswers == 1
 1221       ordered => 0,                  # 1 = must be in same order as correct answer
 1222       entry_type => undef,           # determined from first entry
 1223       list_type => undef,            # determined automatically
 1224       typeMatch => $element,         # used for type checking the entries
 1225       firstElement => $element,
 1226       extra => undef,                # used to check syntax of incorrect answers
 1227       requireParenMatch => 1,        # student parens must match correct parens
 1228       removeParens => 1,             # remove outermost parens, if any
 1229       implicitList => 1,             # force single answers to be lists (even if they ARE lists)
 1230 
 1231 
 1232 =cut
 1233 
 1234 package Value::List;
 1235 
 1236 sub cmp_defaults {
 1237   my $self = shift;
 1238   my %options = (@_);
 1239   my $element = Value::makeValue($self->{data}[0],context=>$self->context);
 1240   $element = $self->Package("Formula")->new($element) unless Value::isValue($element);
 1241   return (
 1242     Value::Real->cmp_defaults(@_),
 1243     showHints => undef,
 1244     showLengthHints => undef,
 1245     showParenHints => undef,
 1246     partialCredit => undef,
 1247     ordered => 0,
 1248     entry_type => undef,
 1249     list_type => undef,
 1250     typeMatch => $element,
 1251     firstElement => $element,
 1252     extra => undef,
 1253     requireParenMatch => 1,
 1254     removeParens => 1,
 1255     implicitList => 1,
 1256   );
 1257 }
 1258 
 1259 #
 1260 #  Match anything but formulas
 1261 #
 1262 sub typeMatch {return !ref($other) || !$other->isFormula}
 1263 
 1264 #
 1265 #  Handle removal of outermost parens in correct answer.
 1266 #
 1267 sub cmp {
 1268   my $self = shift;
 1269   my %params = @_;
 1270   my $cmp = $self->SUPER::cmp(@_);
 1271   if ($cmp->{rh_ans}{removeParens}) {
 1272     $self->{open} = $self->{close} = '';
 1273     $cmp->ans_hash(correct_ans => $self->stringify)
 1274       unless defined($self->{correct_ans}) || defined($params{correct_ans});
 1275   }
 1276   return $cmp;
 1277 }
 1278 
 1279 sub cmp_equal {
 1280   my $self = shift; my $ans = shift;
 1281   $ans->{showPartialCorrectAnswers} = $self->getPG('$showPartialCorrectAnswers');
 1282 
 1283   #
 1284   #  get the paramaters
 1285   #
 1286   my $showHints         = getOption($ans,'showHints');
 1287   my $showLengthHints   = getOption($ans,'showLengthHints');
 1288   my $showParenHints    = getOption($ans,'showParenHints');
 1289   my $partialCredit     = getOption($ans,'partialCredit');
 1290   my $requireParenMatch = $ans->{requireParenMatch};
 1291   my $implicitList      = $ans->{implicitList};
 1292   my $typeMatch         = $ans->{typeMatch};
 1293   my $value             = $ans->{entry_type};
 1294   my $ltype             = $ans->{list_type} || lc($self->type);
 1295   my $stype             = $ans->{short_type} || $ltype;
 1296 
 1297   $value = (Value::isValue($typeMatch)? lc($typeMatch->cmp_class): 'a value')
 1298     unless defined($value);
 1299   $value =~ s/(real|complex) //; $ans->{cmp_class} = $value;
 1300   $value =~ s/^an? //; $value = 'formula' if $value =~ m/formula/;
 1301   $ltype =~ s/^an? //; $stype =~ s/^an? //;
 1302   $showHints = $showLengthHints = 0 if $ans->{isPreview};
 1303 
 1304   #
 1305   #  Get the lists of correct and student answers
 1306   #   (split formulas that return lists or unions)
 1307   #
 1308   my @correct = (); my ($cOpen,$cClose);
 1309   if (!$self->isFormula) {
 1310     @correct = $self->value;
 1311     $cOpen = $ans->{correct_value}{open}; $cClose = $ans->{correct_value}{close};
 1312   } else {
 1313     @correct = Value::List->splitFormula($self,$ans);
 1314     $cOpen = $self->{tree}{open}; $cClose = $self->{tree}{close};
 1315   }
 1316   my $student = $ans->{student_value}; my @student = ($student);
 1317   my ($sOpen,$sClose) = ('','');
 1318   if (Value::isFormula($student) && $student->type eq $self->type) {
 1319     if ($implicitList && $student->{tree}{open} ne '') {
 1320       @student = ($student);
 1321     } else {
 1322       @student = Value::List->splitFormula($student,$ans);
 1323       $sOpen = $student->{tree}{open}; $sClose = $student->{tree}{close};
 1324     }
 1325   } elsif (!$student->isFormula && $student->classMatch($self->type)) {
 1326     if ($implicitList && $student->{open} ne '') {
 1327       @student = ($student);
 1328     } else {
 1329       @student = @{$student->{data}};
 1330       $sOpen = $student->{open}; $sClose = $student->{close};
 1331     }
 1332   }
 1333   foreach my $x (@correct) {$x->{equation} = $self};
 1334   foreach my $x (@student) {$x->{equation} = $self};
 1335   return if $ans->{split_error};
 1336   #
 1337   #  Check for parenthesis match
 1338   #
 1339   if ($requireParenMatch && ($sOpen ne $cOpen || $sClose ne $cClose)) {
 1340     if ($showParenHints && !($ans->{ignoreStrings} && $student->type eq 'String')) {
 1341       my $message = "The parentheses for your $ltype ";
 1342       if (($cOpen || $cClose) && ($sOpen || $sClose))
 1343                                 {$message .= "are of the wrong type"}
 1344       elsif ($sOpen || $sClose) {$message .= "should be removed"}
 1345       else                      {$message .= "seem to be missing"}
 1346       $self->cmp_Error($ans,$message) unless $ans->{isPreview};
 1347     }
 1348     return;
 1349   }
 1350 
 1351   #
 1352   #  Determine the maximum score
 1353   #
 1354   my $M = scalar(@correct);
 1355   my $m = scalar(@student);
 1356   my $maxscore = ($m > $M)? $m : $M;
 1357 
 1358   #
 1359   #  Compare the two lists
 1360   #  (Handle errors in user-supplied functions)
 1361   #
 1362   my ($score,@errors);
 1363   if (ref($ans->{list_checker}) eq 'CODE') {
 1364     eval {($score,@errors) = &{$ans->{list_checker}}([@correct],[@student],$ans,$value)};
 1365     if (!defined($score)) {
 1366       die $@ if $@ ne '' && $self->{context}{error}{flag} == 0;
 1367       $self->cmp_error($ans) if $self->{context}{error}{flag};
 1368     }
 1369   } else {
 1370     ($score,@errors) = $self->cmp_list_compare([@correct],[@student],$ans,$value);
 1371   }
 1372   return unless defined($score);
 1373 
 1374   #
 1375   #  Give hints about extra or missing answers
 1376   #
 1377   if ($showLengthHints) {
 1378     $value =~ s/( or|,) /s$1 /g; # fix "interval or union"
 1379     push(@errors,"There should be more ${value}s in your $stype")
 1380       if ($score < $maxscore && $score == $m);
 1381     push(@errors,"There should be fewer ${value}s in your $stype")
 1382       if ($score < $maxscore && $score == $M && !$showHints);
 1383   }
 1384 
 1385   #
 1386   #  If all the entries are in error, don't give individual messages
 1387   #
 1388   if ($score == 0) {
 1389     my $i = 0;
 1390     while ($i <= $#errors) {
 1391       if ($errors[$i++] =~ m/^Your .* is incorrect$/)
 1392         {splice(@errors,--$i,1)}
 1393     }
 1394   }
 1395 
 1396   #
 1397   #  Finalize the score
 1398   #
 1399   $score = 0 if ($score != $maxscore && !$partialCredit);
 1400   $ans->score($score/$maxscore);
 1401   push(@errors,"Score = $ans->{score}") if $ans->{debug};
 1402   my $error = join("\n",@errors); $error =~ s!</DIV>\n!</DIV>!g;
 1403   $ans->{error_message} = $ans->{ans_message} = $error;
 1404 }
 1405 
 1406 #
 1407 #  Compare the contents of the list to see of they are equal
 1408 #
 1409 sub cmp_list_compare {
 1410   my $self = shift; my $context = $self->context;
 1411   my $correct = shift; my $student = shift; my $ans = shift; my $value = shift;
 1412   my @correct = @{$correct}; my @student = @{$student}; my $m = scalar(@student);
 1413   my $ordered = $ans->{ordered};
 1414   my $showTypeWarnings = $ans->{showTypeWarnings} && !$ans->{isPreview};
 1415   my $typeMatch = $ans->{typeMatch};
 1416   my $extra = defined($ans->{extra}) ? $ans->{extra} :
 1417               (Value::isValue($typeMatch) ? $typeMatch: $ans->{firstElement});
 1418   $extra = $self->Package("List")->new() unless defined($extra);
 1419   my $showHints = getOption($ans,'showHints') && !$ans->{isPreview};
 1420   my $error = $context->{error};
 1421   my $score = 0; my @errors; my $i = 0;
 1422 
 1423   #
 1424   #  Check for empty lists
 1425   #
 1426   if (scalar(@correct) == 0) {$ans->score($m == 0); return}
 1427 
 1428   #
 1429   #  Loop through student answers looking for correct ones
 1430   #
 1431   ENTRY: foreach my $entry (@student) {
 1432     $i++; $context->clearError;
 1433     $entry = Value::makeValue($entry,$context);
 1434     $entry = $self->Package("Formula")->new($entry) if !Value::isValue($entry);
 1435 
 1436     #
 1437     #  Some words differ if there is only one entry in the student's list
 1438     #
 1439     my $nth = ''; my $answer = 'answer';
 1440     my $class = $ans->{list_type} || $ans->{cmp_class};
 1441     if ($m > 1) {
 1442       $nth = ' '.$self->NameForNumber($i);
 1443       $class = $ans->{cmp_class};
 1444       $answer = 'value';
 1445     }
 1446 
 1447     #
 1448     #  See if the entry matches the correct answer
 1449     #  and perform syntax checking if not
 1450     #
 1451     if ($ordered) {
 1452       if (scalar(@correct)) {
 1453   if (shift(@correct)->cmp_compare($entry,$ans,$nth,$value)) {$score++; next ENTRY}
 1454       } else {
 1455   # do syntax check
 1456   if (ref($extra) eq 'CODE') {&$extra($entry,$ans,$nth,$value)}
 1457     else {$extra->cmp_compare($entry,$ans,$nth,$value)}
 1458       }
 1459       if ($error->{flag} == $CMP_ERROR) {$self->cmp_error($ans); return}
 1460     } else {
 1461       foreach my $k (0..$#correct) {
 1462   if ($correct[$k]->cmp_compare($entry,$ans,$nth,$value)) {
 1463     splice(@correct,$k,1);
 1464     $score++; next ENTRY;
 1465   }
 1466   if ($error->{flag} == $CMP_ERROR) {$self->cmp_error($ans); return}
 1467       }
 1468       $context->clearError;
 1469       # do syntax check
 1470       if (ref($extra) eq 'CODE') {&$extra($entry,$ans,$nth,$value)}
 1471         else {$extra->cmp_compare($entry,$ans,$nth,$value)}
 1472     }
 1473     #
 1474     #  Give messages about incorrect answers
 1475     #
 1476     my $match = (ref($typeMatch) eq 'CODE')? &$typeMatch($entry,$ans) :
 1477                                              $typeMatch->typeMatch($entry,$ans);
 1478     if ($showTypeWarnings && !$match &&
 1479   !($ans->{ignoreStrings} && $entry->classMatch('String'))) {
 1480       push(@errors,"Your$nth $answer isn't ".lc($class).
 1481      " (it looks like ".lc($entry->showClass).")");
 1482     } elsif ($error->{flag} && $ans->{showEqualErrors}) {
 1483       my $message = $error->{message}; $message =~ s/\s+$//;
 1484       if ($m > 1 && $error->{flag} != $CMP_WARNING) {
 1485         push(@errors,"<SMALL>There is a problem with your$nth $value:</SMALL>",
 1486                '<DIV STYLE="margin-left:1em">'.$message.'</DIV>');
 1487       } else {push(@errors,$message)}
 1488     } elsif ($showHints && $m > 1) {
 1489       push(@errors,"Your$nth $value is incorrect");
 1490     }
 1491   }
 1492 
 1493   #
 1494   #  Return the score and errors
 1495   #
 1496   return ($score,@errors);
 1497 }
 1498 
 1499 
 1500 
 1501 #
 1502 #  Split a formula that is a list or union into a
 1503 #    list of formulas (or Value objects).
 1504 #
 1505 sub splitFormula {
 1506   my $self = shift; my $formula = shift; my $ans = shift;
 1507   my @formula; my @entries;
 1508   if ($formula->type eq 'Union') {@entries = $formula->{tree}->makeUnion}
 1509     else {@entries = @{$formula->{tree}{coords}}}
 1510   foreach my $entry (@entries) {
 1511     my $v = Parser::Formula($entry);
 1512        $v = Parser::Evaluate($v) if (defined($v) && $v->isConstant);
 1513     $v->{equation} = $self;
 1514     push(@formula,$v);
 1515     #
 1516     #  There shouldn't be an error evaluating the formula,
 1517     #    but you never know...
 1518     #
 1519     if (!defined($v)) {$ans->{split_error} = 1; $self->cmp_error; return}
 1520   }
 1521   return @formula;
 1522 }
 1523 
 1524 #  Override for List ?
 1525 #  Return the value if it is defined, otherwise use a default
 1526 #
 1527 sub getOption {
 1528   my $ans = shift; my $name = shift;
 1529   my $value = $ans->{$name};
 1530   return $value if defined($value);
 1531   return $ans->{showPartialCorrectAnswers};
 1532 }
 1533 
 1534 #############################################################
 1535 
 1536 =head3  Value::Formula
 1537 
 1538   Usage: $fun = Formula("x^2-x+1");
 1539          $set = Formula("[-1, x) U (x, 2]");
 1540 
 1541   A formula can have any of the other math object types as its range.
 1542     Union, List, Number (Complex or Real),
 1543 
 1544 
 1545 =cut
 1546 
 1547 package Value::Formula;
 1548 
 1549 sub cmp_defaults {
 1550   my $self = shift;
 1551 
 1552   return (
 1553     Value::Union::cmp_defaults($self,@_),
 1554     typeMatch => $self->Package("Formula")->new("(1,2]"),
 1555     showDomainErrors => 1,
 1556   ) if $self->type eq 'Union';
 1557 
 1558   my $type = $self->type;
 1559   $type = ($self->isComplex)? 'Complex': 'Real' if $type eq 'Number';
 1560   $type = $self->Package($type).'::';
 1561 
 1562   return (
 1563     &{$type.'cmp_defaults'}($self,@_),
 1564     upToConstant => 0,
 1565     showDomainErrors => 1,
 1566   ) if defined(%$type) && $self->type ne 'List';
 1567 
 1568   my $element;
 1569   if ($self->{tree}->class eq 'List') {$element = $self->Package("Formula")->new($self->{tree}{coords}[0])}
 1570     else {$element = $self->Package("Formula")->new(($self->createRandomPoints(1))[1]->[0]{data}[0])}
 1571   return (
 1572     Value::List::cmp_defaults($self,@_),
 1573     removeParens => $self->{autoFormula},
 1574     typeMatch => $element,
 1575     showDomainErrors => 1,
 1576   );
 1577 }
 1578 
 1579 #
 1580 #  Get the types from the values of the formulas
 1581 #     and compare those.
 1582 #
 1583 sub typeMatch {
 1584   my $self = shift; my $other = shift; my $ans = shift;
 1585   return 1 if $self->type eq $other->type;
 1586   my $typeMatch = ($self->createRandomPoints(1))[1]->[0];
 1587   $other = eval {($other->createRandomPoints(1))[1]->[0]} if Value::isFormula($other);
 1588   return 1 unless defined($other); # can't really tell, so don't report type mismatch
 1589   return 1 if $typeMatch->classMatch('String') && Value::isFormula($ans->{typeMatch});  # avoid infinite loop
 1590   $typeMatch->typeMatch($other,$ans);
 1591 }
 1592 
 1593 #
 1594 #  Handle removal of outermost parens in a list.
 1595 #  Evaluate answer, if the eval option is used.
 1596 #  Handle the UpToConstant option.
 1597 #
 1598 sub cmp {
 1599   my $self = shift;
 1600   my $cmp = $self->SUPER::cmp(@_);
 1601   if ($cmp->{rh_ans}{removeParens} && $self->type eq 'List') {
 1602     $self->{tree}{open} = $self->{tree}{close} = '';
 1603     $cmp->ans_hash(correct_ans => $self->stringify)
 1604       unless defined($self->{correct_ans});
 1605   }
 1606   if ($cmp->{rh_ans}{eval} && $self->isConstant) {
 1607     $cmp->ans_hash(correct_value => $self->eval);
 1608     return $cmp;
 1609   }
 1610   if ($cmp->{rh_ans}{upToConstant}) {
 1611     my $current = Parser::Context->current();
 1612     my $context = $self->{context} = $self->{context}->copy;
 1613     Parser::Context->current(undef,$context);
 1614     $context->variables->add('C0' => 'Parameter');
 1615     my $f = $self->Package("Formula")->new('C0')+$self;
 1616     for ('limits','test_points','test_values','num_points','granularity','resolution',
 1617    'checkUndefinedPoints','max_undefined')
 1618       {$f->{$_} = $self->{$_} if defined($self->{$_})}
 1619     $cmp->ans_hash(correct_value => $f);
 1620     Parser::Context->current(undef,$current);
 1621   }
 1622   $cmp->install_pre_filter(\&Value::Formula::cmp_call_filter,"cmp_prefilter");
 1623   $cmp->install_post_filter(\&Value::Formula::cmp_call_filter,"cmp_postfilter");
 1624   return $cmp;
 1625 }
 1626 
 1627 sub cmp_call_filter {
 1628   my $ans = shift; my $method = shift;
 1629   return $ans->{correct_value}->$method($ans,@_);
 1630 }
 1631 
 1632 sub cmp_prefilter {
 1633   my $self = shift; my $ans = shift;
 1634   $ans->{_filter_name} = "fetch_previous_answer";
 1635   $ans->{prev_ans} = undef;
 1636   if (defined($ans->{ans_label})) {
 1637     my $label = "previous_".$ans->{ans_label};
 1638     my $inputs = $self->getPG('$inputs_ref');
 1639     if (defined $inputs->{$label} and $inputs->{$label} =~ /\S/) {
 1640       $ans->{prev_ans} = $inputs->{$label};
 1641       #FIXME -- previous answer item is not always being updated in inputs_ref (which comes from formField)
 1642     }
 1643   }
 1644   return $ans;
 1645 }
 1646 
 1647 sub cmp_postfilter {
 1648   my $self = shift; my $ans = shift;
 1649   $ans->{_filter_name} = "produce_equivalence_message";
 1650   return $ans if $ans->{ans_message}; # don't overwrite other messages
 1651   my $context = $self->context;
 1652   $ans->{prev_formula} = Parser::Formula($context,$ans->{prev_ans});
 1653   if (defined($ans->{prev_formula}) && defined($ans->{student_formula})) {
 1654     my $prev = eval {$self->promote($ans->{prev_formula})->inherit($self)}; # inherit limits, etc.
 1655     break unless defined($prev);
 1656     $context->{answerHash} = $ans; # values here can override context flags
 1657     $ans->{prev_equals_current} = Value::cmp_compare($prev,$ans->{student_formula},$ans);
 1658     $context->{answerHash} = undef;
 1659     if (   !$ans->{isPreview}                                 # not preview mode
 1660   and $ans->{prev_equals_current}                       # equivalent
 1661   and $ans->{prev_ans} ne $ans->{original_student_ans}) # but not identical
 1662       {$ans->{ans_message} = "This answer is equivalent to the one you just submitted."}
 1663   }
 1664   return $ans;
 1665 }
 1666 
 1667 
 1668 sub cmp_equal {
 1669   my $self = shift; my $ans = shift;
 1670   #
 1671   #  Get the problem's seed
 1672   #
 1673   $self->{context}->flags->set(
 1674     random_seed => $self->getPG('$PG_original_problemSeed')
 1675   );
 1676 
 1677   #
 1678   #  Use the list checker if the formula is a list or union
 1679   #    Otherwise use the normal checker
 1680   #
 1681   if ($self->type =~ m/^(List|Union|Set)$/) {
 1682     Value::List::cmp_equal($self,$ans);
 1683   } else {
 1684     $self->SUPER::cmp_equal($ans);
 1685   }
 1686 }
 1687 
 1688 sub cmp_postprocess {
 1689   my $self = shift; my $ans = shift;
 1690   return unless $ans->{score} == 0;
 1691   $self->{context}->clearError;
 1692   eval {$ans->{student_formula}->reduce} if defined($ans->{student_formula}); # check for bad function calls
 1693   $self->cmp_error($ans) if $self->{context}{error}{flag};                    #  and report the error
 1694   return if $ans->{ans_message} || $ans->{isPreview};
 1695   if ($self->{domainMismatch} && $ans->{showDomainErrors}) {
 1696     $self->cmp_Error($ans,"The domain of your function doesn't match that of the correct answer");
 1697     return;
 1698   }
 1699   return if !$ans->{showDimensionHints};
 1700   my $other = $ans->{student_value};
 1701   return if $ans->{ignoreStrings} && (!Value::isValue($other) || $other->type eq 'String');
 1702   return unless $other->type =~ m/^(Point|Vector|Matrix)$/;
 1703   return unless $self->type  =~ m/^(Point|Vector|Matrix)$/;
 1704   return if Parser::Item::typeMatch($self->typeRef,$other->typeRef);
 1705   $self->cmp_Error($ans,"The dimension of your result is incorrect");
 1706 }
 1707 
 1708 #
 1709 #  Diagnostics for Formulas
 1710 #
 1711 sub cmp_diagnostics {
 1712   my $self = shift;  my $ans = shift;
 1713   my $isEvaluator = (ref($ans) =~ /Evaluator/)? 1: 0;
 1714   my $hash = $isEvaluator? $ans->rh_ans : $ans;
 1715   my $diagnostics = $self->{context}->diagnostics->merge("formulas",$self,$hash);
 1716   my $formulas = $diagnostics->{formulas};
 1717   return unless $formulas->{show};
 1718 
 1719   my $output = "";
 1720   if ($isEvaluator) {
 1721     #
 1722     #  The tests to be performed when the answer checker is created
 1723     #
 1724     $self->getPG('loadMacros("PGgraphmacros.pl")');
 1725     my ($inputs) = $self->getPG('$inputs_ref');
 1726     my $process = $inputs->{checkAnswers} || $inputs->{previewAnswers} || $inputs->{submitAnswers};
 1727     if ($formulas->{checkNumericStability} && !$process) {
 1728       ### still needs to be written
 1729     }
 1730   } else {
 1731     #
 1732     #  The checks to be performed when an answer is submitted
 1733     #
 1734     my $student = $ans->{student_formula};
 1735     #
 1736     #  Get the test points
 1737     #
 1738     my @names = $self->{context}->variables->names;
 1739     my $vx = (keys(%{$self->{variables}}))[0];
 1740     my $vi = 0; while ($names[$vi] ne $vx) {$vi++}
 1741     my $points = [map {$_->[$vi]} @{$self->{test_points}}];
 1742     my @params = $self->{context}->variables->parameters;
 1743        @names = $self->{context}->variables->variables;
 1744 
 1745     #
 1746     #  The graphs of the functions and errors
 1747     #
 1748     if ($formulas->{showGraphs}) {
 1749       my @G = ();
 1750       if ($formulas->{combineGraphs}) {
 1751   push(@G,$self->cmp_graph($diagnostics,[$student,$self],
 1752          title=>'Student Answer (red)<BR>Correct Answer (green)<BR>',
 1753          points=>$points,showDomain=>1));
 1754       } else {
 1755   push(@G,$self->cmp_graph($diagnostics,$self,title=>'Correct Answer'));
 1756   push(@G,$self->cmp_graph($diagnostics,$student,title=>'Student Answer'));
 1757       }
 1758       my $cutoff = $self->Package("Formula")->new($self->getFlag('tolerance'));
 1759       if ($formulas->{graphAbsoluteErrors}) {
 1760   push(@G,$self->cmp_graph($diagnostics,[abs($self-$student),$cutoff],
 1761          clip=>$formulas->{clipAbsoluteError},
 1762          title=>'Absolute Error',points=>$points));
 1763       }
 1764       if ($formulas->{graphRelativeErrors}) {
 1765   push(@G,$self->cmp_graph($diagnostics,[abs(($self-$student)/$self),$cutoff],
 1766          clip=>$formulas->{clipRelativeError},
 1767          title=>'Relative Error',points=>$points));
 1768       }
 1769       $output .= '<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="0">'
 1770   . '<TR VALIGN="TOP">'.join('<TD WIDTH="20"></TD>',@G).'</TR></TABLE>';
 1771     }
 1772 
 1773     #
 1774     #  The adaptive parameters
 1775     #
 1776     if ($formulas->{showParameters} && scalar(@params) > 0) {
 1777       $output .= '<HR><TABLE BORDER="0" CELLSPACING="0" CELLPADDING="0"><TR><TD>Adaptive Parameters:<BR>';
 1778       $output .= join("<BR>",map {"&nbsp;&nbsp;$params[$_]: ".$self->{parameters}[$_]} (0..$#params));
 1779       $output .= '</TD></TR></TABLE>';
 1780     }
 1781 
 1782     #
 1783     #  The test points and values
 1784     #
 1785     my @rows = (); my $colsep = '</TD><TD WIDTH="20"></TD><TD ALIGN="RIGHT">';
 1786     my @P = (map {(scalar(@{$_}) == 1)? $_->[0]: $self->Package("Point")->make(@{$_})} @{$self->{test_points}});
 1787     my @i = sort {$P[$a] <=> $P[$b]} (0..$#P);
 1788     foreach $p (@P) {if (Value::isValue($p) && $p->length > 2) {$p = $p->string; $p =~ s|,|,<br />|g}}
 1789     my $zeroLevelTol = $self->{context}{flags}{zeroLevelTol};
 1790     $self->{context}{flags}{zeroLevelTol} = 0; # always show full resolution in the tables below
 1791     my $names = join(',',@names); $names = '('.$names.')' if scalar(@names) > 1;
 1792 
 1793     $student->createPointValues($self->{test_points},0,1,1) unless $student->{test_values};
 1794 
 1795     my $cv = $self->{test_values};
 1796     my $sv = $student->{test_values};
 1797     my $av = $self->{test_adapt} || $cv;
 1798 
 1799     if ($formulas->{showTestPoints}) {
 1800       my @p = ("$names:", (map {$P[$i[$_]]} (0..$#P)));
 1801       push(@rows,'<TR><TD ALIGN="RIGHT">'.join($colsep,@p).'</TD></TR>');
 1802       push(@rows,'<TR><TD ALIGN="RIGHT">'.join($colsep,("<HR>")x scalar(@p)).'</TD></TR>');
 1803       push(@rows,'<TR><TD ALIGN="RIGHT">'
 1804      .join($colsep,($av == $cv)? "Correct Answer:" : "Adapted Answer:",
 1805      map {Value::isNumber($av->[$i[$_]])? $av->[$i[$_]]: "undefined"} (0..$#P))
 1806      .'</TD></TR>');
 1807       push(@rows,'<TR><TD ALIGN="RIGHT">'
 1808      .join($colsep,"Student Answer:",
 1809      map {Value::isNumber($sv->[$i[$_]])? $sv->[$i[$_]]: "undefined"} (0..$#P))
 1810      .'</TD></TR>');
 1811     }
 1812     #
 1813     #  The absolute errors (colored by whether they are ok or too big)
 1814     #
 1815     if ($formulas->{showAbsoluteErrors}) {
 1816       my @p = ("Absolute Error:");
 1817       my $tolerance = $self->getFlag('tolerance');
 1818       my $tolType = $self->getFlag('tolType'); my $error;
 1819       foreach my $j (0..$#P) {
 1820   if (Value::isNumber($sv->[$i[$j]])) {
 1821     $error = abs($av->[$i[$j]] - $sv->[$i[$j]]);
 1822     $error = '<SPAN STYLE="color:#'.($error->value<$tolerance ? '00AA00': 'AA0000').'">'.$error.'</SPAN>'
 1823       if $tolType eq 'absolute';
 1824   } else {$error = "---"}
 1825   push(@p,$error);
 1826       }
 1827       push(@rows,'<TR><TD ALIGN="RIGHT">'.join($colsep,@p).'</TD></TR>');
 1828     }
 1829     #
 1830     #  The relative errors (colored by whether they are OK or too big)
 1831     #
 1832     if ($formulas->{showRelativeErrors}) {
 1833       my @p = ("Relative Error:");
 1834       my $tolerance = $self->getFlag('tolerance'); my $tol;
 1835       my $tolType = $self->getFlag('tolType'); my $error;
 1836       my $zeroLevel = $self->getFlag('zeroLevel');
 1837       foreach my $j (0..$#P) {
 1838   if (Value::isNumber($sv->[$i[$j]])) {
 1839     my $c = $av->[$i[$j]]; my $s = $sv->[$i[$j]];
 1840     if (abs($cv->[$i[$j]]->value) < $zeroLevel || abs($s->value) < $zeroLevel)
 1841             {$error = abs($c-$s); $tol = $zeroLevelTol} else
 1842             {$error = abs(($c-$s)/($c||1E-10)); $tol = $tolerance}
 1843     $error = '<SPAN STYLE="color:#'.($error < $tol ? '00AA00': 'AA0000').'">'.$error.'</SPAN>'
 1844       if $tolType eq 'relative';
 1845   } else {$error = "---"}
 1846   push(@p,$error);
 1847       }
 1848       push(@rows,'<TR><TD ALIGN="RIGHT">'.join($colsep,@p).'</TD></TR>');
 1849     }
 1850     $self->{context}{flags}{zeroLevelTol} = $zeroLevelTol;
 1851     #
 1852     #  Put the data into a table
 1853     #
 1854     if (scalar(@rows)) {
 1855       $output .= '<p><HR><p><TABLE BORDER="0" CELLSPACING="0" CELLPADDING="0">'
 1856   . join('<TR><TD HEIGHT="3"></TD>',@rows)
 1857   . '</TABLE>';
 1858     }
 1859   }
 1860   #
 1861   #  Put all the diagnostic output into a frame
 1862   #
 1863   return unless $output;
 1864   $output
 1865     = '<TABLE BORDER="1" CELLSPACING="2" CELLPADDING="20" BGCOLOR="#F0F0F0">'
 1866     . '<TR><TD ALIGN="LEFT"><B>Diagnostics for '.$self->string .':</B>'
 1867     . '<P><CENTER>' . $output . '</CENTER></TD></TR></TABLE><P>';
 1868   warn $output;
 1869 }
 1870 
 1871 #
 1872 #  Draw a graph from a given Formula object
 1873 #
 1874 sub cmp_graph {
 1875   my $self = shift; my $diagnostics = shift;
 1876   my $F1 = shift; my $F2; ($F1,$F2) = @{$F1} if (ref($F1) eq 'ARRAY');
 1877   #
 1878   #  Get the various options
 1879   #
 1880   my %options = (title=>'',points=>[],@_);
 1881   my $graphs = $diagnostics->{graphs};
 1882   my $limits = $graphs->{limits}; $limits = $self->getFlag('limits',[-2,2]) unless $limits;
 1883   $limits = $limits->[0] while ref($limits) eq 'ARRAY' && ref($limits->[0]) eq 'ARRAY';
 1884   my $size = $graphs->{size}; $size = [$size,$size] unless ref($size) eq 'ARRAY';
 1885   my $steps = $graphs->{divisions};
 1886   my $points = $options{points}; my $clip = $options{clip};
 1887   my ($my,$My) = (0,0); my ($mx,$Mx) = @{$limits};
 1888   my $dx = ($Mx-$mx)/$steps; my $f; my $y;
 1889 
 1890   my @pnames = $self->{context}->variables->parameters;
 1891   my @pvalues = ($self->{parameters} ? @{$self->{parameters}} : (0) x scalar(@pnames));
 1892   my $x = "";
 1893 
 1894   #
 1895   #  Find the max and min values of the function
 1896   #
 1897   foreach $f ($F1,$F2) {
 1898     next unless defined($f);
 1899     foreach my $v (keys(%{$f->{variables}})) {
 1900       if ($v ne $x && !$f->{context}->variables->get($v)->{parameter}) {
 1901   if ($x) {
 1902     warn "Only formulas with one variable can be graphed" unless $self->{graphWarning};
 1903     $self->{graphWarning} = 1;
 1904     return "";
 1905   }
 1906   $x = $v;
 1907       }
 1908     }
 1909     unless ($f->typeRef->{length} == 1) {
 1910       warn "Only real-valued functions can be graphed" unless $self->{graphWarning};
 1911       $self->{graphWarning} = 1;
 1912       return "";
 1913     }
 1914     unless ($f->typeRef->{length} == 1) {
 1915       warn "Only real-valued functions can be graphed";
 1916       return "";
 1917     }
 1918     if ($f->isConstant) {
 1919       $y = $f->eval;
 1920       $my = $y if $y < $my; $My = $y if $y > $My;
 1921     } else {
 1922       my $F = $f->perlFunction(undef,[$x,@pnames]);
 1923       foreach my $i (0..$steps-1) {
 1924         $y = eval {&{$F}($mx+$i*$dx,@pvalues)};
 1925   next unless defined($y) && Value::isNumber($y);
 1926         $my = $y if $y < $my; $My = $y if $y > $My;
 1927       }
 1928     }
 1929   }
 1930   $My = 1 if abs($My - $my) < 1E-5;
 1931   $my *= 1.1; $My *= 1.1;
 1932   if ($clip) {
 1933     $my = -$clip if $my < -$clip;
 1934     $My = $clip if $My > $clip;
 1935   }
 1936   $my = -$My/10 if $my > -$My/10; $My = -$my/10 if $My < -$my/10;
 1937   my $a = $self->Package("Real")->new(($My-$my)/($Mx-$mx));
 1938 
 1939   #
 1940   #  Create the graph itself, with suitable title
 1941   #
 1942   my $grf = $self->getPG('$_grf_ = {n => 0}');
 1943   $grf->{Goptions} = [
 1944      $mx,$my,$Mx,$My,
 1945      axes => $graphs->{axes},
 1946      grid => $graphs->{grid},
 1947      size => $size,
 1948   ];
 1949   $grf->{params} = {
 1950     names => [$x,@pnames],
 1951     values => {map {$pnames[$_] => $pvalues[$_]} (0..scalar(@pnames)-1)},
 1952   };
 1953   $grf->{G} = $self->getPG('init_graph(@{$_grf_->{Goptions}})');
 1954   $grf->{G}->imageName($grf->{G}->imageName.'-'.time()); # avoid browser cache
 1955   $self->cmp_graph_function($grf,$F2,"green",$steps,$points) if defined($F2);
 1956   $self->cmp_graph_function($grf,$F1,"red",$steps,$points);
 1957   my $image = $self->getPG('alias(insertGraph($_grf_->{G}))');
 1958   $image = '<IMG SRC="'.$image.'" WIDTH="'.$size->[0].'" HEIGHT="'.$size->[1].'" BORDER="0" STYLE="margin-bottom:5px">';
 1959   my $title = $options{title}; $title .= '<DIV STYLE="margin-top:5px"></DIV>' if $title;
 1960   $title .= "<SMALL>Domain: [$mx,$Mx]</SMALL><BR>" if $options{showDomain};
 1961   $title .= "<SMALL>Range: [$my,$My]<BR>Aspect ratio: $a:1</SMALL>";
 1962   return '<TD ALIGN="CENTER" VALIGN="TOP" NOWRAP>'.$image.'<BR>'.$title.'</TD>';
 1963 }
 1964 
 1965 #
 1966 #  Add a function to a graph object, and plot the points
 1967 #  that are used to test the function
 1968 #
 1969 sub cmp_graph_function {
 1970   my $self = shift; my $grf = shift; my $F = shift;
 1971   my $color = shift; my $steps = shift; my $points = shift;
 1972   $grf->{n}++; my $Fn = "F".$grf->{n}; $grf->{$Fn} = $F; my $f;
 1973   if ($F->isConstant) {
 1974     my $y = $F->eval;
 1975     $f = $self->getPG('new Fun(sub {'.$y.'},$_grf_->{G})');
 1976   } else {
 1977     my $X = $grf->{params}{names}[0];
 1978     $f = $self->getPG('new Fun(sub {Parser::Evaluate($_grf_->{'.$Fn.'},'
 1979            .$X.'=>shift,%{$_grf_->{params}{values}})},$_grf_->{G})');
 1980     foreach my $x (@{$points}) {
 1981       my $y = Parser::Evaluate($F,($X)=>$x,%{$grf->{params}{values}});
 1982       next unless defined($y) && Value::isNumber($y);
 1983       $grf->{x} = $x; $grf->{'y'} = $y;
 1984       my $C = $self->getPG('new Circle($_grf_->{x},$_grf_->{y},4,"'.$color.'","'.$color.'")');
 1985       $grf->{G}->stamps($C);
 1986     }
 1987   }
 1988   $f->color($color); $f->weight(2); $f->steps($steps);
 1989 }
 1990 
 1991 #
 1992 #  If an answer array was used, get the data from the
 1993 #  Matrix, Vector or Point, and format the array of
 1994 #  data using the original parameter
 1995 #
 1996 sub correct_ans {
 1997   my $self = shift;
 1998   return $self->SUPER::correct_ans unless $self->{ans_name};
 1999   my @array = ();
 2000   if ($self->{tree}->type eq 'Matrix') {
 2001     foreach my $row (@{$self->{tree}{coords}}) {
 2002       my @row = ();
 2003       foreach my $x (@{$row->coords}) {push(@row,$x->string)}
 2004       push(@array,[@row]);
 2005     }
 2006   } else {
 2007     foreach my $x (@{$self->{tree}{coords}}) {push(@array,$x->string)}
 2008     if ($self->{tree}{ColumnVector}) {foreach my $x (@array) {$x = [$x]}}
 2009       else {@array = [@array]}
 2010   }
 2011   Value::VERBATIM($self->format_matrix([@array],@{$self->{format_options}},tth_delims=>1));
 2012 }
 2013 
 2014 #
 2015 #  Get the size of the array and create the appropriate answer array
 2016 #
 2017 sub ANS_MATRIX {
 2018   my $self = shift;
 2019   my $extend = shift; my $name = shift;
 2020   my $size = shift || 5; my $type = $self->type;
 2021   my $cols = $self->length; my $rows = 1; my $sep = ',';
 2022   if ($type eq 'Matrix') {
 2023     $sep = ''; $rows = $cols; $cols = $self->{tree}->typeRef->{entryType}{length};
 2024   }
 2025   if ($self->{tree}{ColumnVector}) {
 2026     $sep = ""; $type = "Matrix";
 2027     my $tmp = $rows; $rows = $cols; $cols = $tmp;
 2028     $self->{ColumnVector} = 1;
 2029   }
 2030   my $def = $self->context->lists->get($type);
 2031   my $open = $self->{open} || $self->{tree}{open} || $def->{open};
 2032   my $close = $self->{close} || $self->{tree}{close} || $def->{close};
 2033   $self->ans_matrix($extend,$name,$rows,$cols,$size,$open,$close,$sep);
 2034 }
 2035 
 2036 sub ans_array {
 2037   my $self = shift;
 2038   return $self->SUPER::ans_array(@_) unless $self->array_OK;
 2039   $self->ANS_MATRIX(0,'',@_);
 2040 }
 2041 sub named_ans_array {
 2042   my $self = shift;
 2043   return $self->SUPER::named_ans_array(@_) unless $self->array_OK;
 2044   $self->ANS_MATRIX(0,@_);
 2045 }
 2046 sub named_ans_array_extension {
 2047   my $self = shift;
 2048   return $self->SUPER::named_ans_array_extension(@_) unless $self->array_OK;
 2049   $self->ANS_MATRIX(1,@_);
 2050 }
 2051 
 2052 sub array_OK {
 2053   my $self = shift; my $tree = $self->{tree};
 2054   return $tree->type =~ m/^(Point|Vector|Matrix)$/ && $tree->class eq 'List';
 2055 }
 2056 
 2057 #
 2058 #  Get an array of values from a Matrix, Vector or Point
 2059 #  (this needs to be made more general)
 2060 #
 2061 sub value {
 2062   my $self = shift;
 2063   return $self unless defined $self->{tree}{coords};
 2064   my $context = $self->context;
 2065   my @array = ();
 2066   if ($self->{tree}->type eq 'Matrix') {
 2067     foreach my $row (@{$self->{tree}->coords}) {
 2068       my @row = ();
 2069       foreach my $x (@{$row->coords}) {push(@row,$context->Package("Formula")->new($context,$x))}
 2070       push(@array,[@row]);
 2071     }
 2072   } else {
 2073     foreach my $x (@{$self->{tree}->coords}) {
 2074       push(@array,$context->Package("Formula")->new($context,$x));
 2075     }
 2076   }
 2077   return @array;
 2078 }
 2079 
 2080 #############################################################
 2081 
 2082 1;

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9