-
-
Notifications
You must be signed in to change notification settings - Fork 76
/
AnswerChecker.pm
2501 lines (2271 loc) · 76 KB
/
AnswerChecker.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
=head1 DESCRIPTION
#############################################################
#
# Implements the ->cmp method for Value objects.
# Otherwise known as MathObjects. This produces
# an answer checker appropriate for the type of object.
# Additional options can be passed to the cmp method to
# modify its action.
#
# Usage: $num = Real(3.45); # Real can be replaced by any other MathObject
# ANS($num->cmp(compareOptionName => compareOptionValue, ... ))
#
# The individual Value packages are modified below to add the
# needed methods.
#
#############################################################
=cut
package Value;
use PGcore;
#
# Context can add default values to the answer checkers by class;
#
$Value::defaultContext->{cmpDefaults} = {};
=head4 $mathObject->cmp_defaults()
# Internal use.
# Set default flags for the answer checker in this object
# showTypeWarnings => 1
# showEqualErrors => 1
# ignoreStrings => 1
# studentsMustReduceUnions => 1
# showUnionReduceWarnings => 1
#
=cut
sub cmp_defaults { (
showTypeWarnings => 1,
showEqualErrors => 1,
ignoreStrings => 1,
studentsMustReduceUnions => 1,
showUnionReduceWarnings => 1,
) }
#
# Special Context flags to be set for the student answer
#
sub cmp_contextFlags {
my $self = shift;
my $ans = shift;
return (
StringifyAsTeX => 0, # reset this, just in case.
no_parameters => 1, # don't let students enter parameters
showExtraParens => 2, # make student answer painfully unambiguous
reduceConstants => 0, # don't combine student constants
reduceConstantFunctions => 0, # don't reduce constant functions
(
$ans->{studentsMustReduceUnions}
? (
reduceUnions => 0,
reduceSets => 0,
reduceUnionsForComparison => $ans->{showUnionReduceWarnings},
reduceSetsForComparison => $ans->{showUnionReduceWarnings}
)
: (
reduceUnions => 1,
reduceSets => 1,
reduceUnionsForComparison => 1,
reduceSetsForComparison => 1
)
),
($ans->{requireParenMatch} ? () : ignoreEndpointTypes => 1), # for Intervals
);
}
#
# Create an answer checker for the given type of object
#
sub cmp {
my $self = shift;
my $ans = new AnswerEvaluator;
my $correct = preformat($self->{correct_ans});
$correct = $self->correct_ans unless defined($correct);
my $correct_latex = $self->{correct_ans_latex_string};
$correct_latex = $self->correct_ans_latex unless defined($correct_latex);
$self->{context} = Value->context unless defined($self->{context});
$ans->ans_hash(
type => "Value (" . $self->class . ")",
correct_ans => $correct,
correct_ans_latex_string => $correct_latex,
correct_value => $self,
$self->cmp_defaults(@_),
%{ $self->{context}{cmpDefaults}{ $self->class } || {} }, # context-specified defaults
@_,
);
$ans->{debug} = $ans->{rh_ans}{debug};
$ans->install_evaluator(sub {
my $ans = shift;
$ans->{_filter_name} = "MathObjects answer checker";
$ans->{correct_value}->cmp_parse($ans);
});
$ans->install_pre_filter('erase') if $self->{ans_name}; # don't do blank check if answer_array
$self->cmp_diagnostics($ans);
return $ans;
}
sub correct_ans { preformat(shift->string) }
sub correct_ans_latex { shift->TeX }
sub cmp_diagnostics { }
#
# Parse the student answer and compute its value,
# produce the preview strings, and then compare the
# student and professor's answers for equality.
#
sub cmp_parse {
my $self = shift;
my $ans = shift;
#
# Do some setup
#
my $context = $ans->{correct_value}{context} || $current;
Parser::Context->current(undef, $context); # change to correct answser's context
my $flags = contextSet($context, $self->cmp_contextFlags($ans)); # save old context flags
my $inputs = $self->getPG('$inputs_ref');
$ans->{isPreview} = $inputs->{previewAnswers} || (($inputs->{action} // '') =~ m/^Preview/);
$ans->{cmp_class} = $self->cmp_class($ans) unless $ans->{cmp_class};
$ans->{error_message} = $ans->{ans_message} = ''; # clear any old messages
$ans->{preview_latex_string} = $ans->{preview_text_string} = '';
$context->clearError();
$context->{answerHash} = $ans; # values here can override context flags
#
# Parse and evaluate the student answer
#
$ans->score(0); # assume failure
$context->flags->set(
parseMathQuill => $context->flag("useMathQuill") && (!defined $context->{answerHash}{mathQuillOpts}
|| $context->{answerHash}{mathQuillOpts} !~ /^\s*disabled\s*$/i)
);
$ans->{student_value} = $ans->{student_formula} = Parser::Formula($ans->{student_ans});
$ans->{student_value} = Parser::Evaluate($ans->{student_formula})
if defined($ans->{student_formula}) && $ans->{student_formula}->isConstant;
$context->flags->set(parseMathQuill => 0);
#
# If it parsed OK, save the output forms and check if it is correct
# otherwise report an error
#
if (defined $ans->{student_value}) {
$ans->{student_value} = $self->Package("Formula")->new($ans->{student_value})
unless Value::isValue($ans->{student_value});
$ans->{student_value}{isStudent} = 1;
$ans->{preview_latex_string} = $ans->{student_formula}->TeX;
$ans->{preview_text_string} = preformat($ans->{student_formula}->string);
#
# Get the string for the student answer
#
for ($self->getFlag('formatStudentAnswer')) {
/evaluated/i and do { $ans->{student_ans} = preformat($ans->{student_value}->string); last };
/parsed/i and do { $ans->{student_ans} = $ans->{preview_text_string}; last };
/reduced/i and do {
my $oldFlags = contextSet($context, reduceConstants => 1, reduceConstantFunctions => 0);
$ans->{student_ans} = preformat($ans->{student_formula}->substitute()->string);
contextSet($context, %{$oldFags});
last;
};
warn "Unknown student answer format |$ans->{formatStudentAnswer}|";
}
if ($self->cmp_collect($ans)) {
$self->cmp_preprocess($ans);
$self->cmp_equal($ans);
$self->cmp_postprocess($ans) if !$ans->{error_message} && !$ans->{typeError};
$self->cmp_diagnostics($ans);
}
} else {
$self->cmp_collect($ans);
$self->cmp_error($ans);
}
$context->{answerHash} = undef;
contextSet($context, %{$flags}); # restore context values
return $ans;
}
#
# Check if the object has an answer array and collect the results
# Build the combined student answer and set the preview values
#
sub cmp_collect {
my $self = shift;
my $ans = shift;
return 1 unless $self->{ans_name};
$ans->{preview_latex_string} = $ans->{preview_text_string} = "";
my $OK = $self->ans_collect($ans);
$ans->{student_ans} = $self->format_matrix($ans->{student_formula}, @{ $self->{format_options} }, tth_delims => 1);
return 0 unless $OK;
my $array = $ans->{student_formula};
if ($self->{ColumnVector}) {
my @V = ();
foreach my $x (@{$array}) { push(@V, $x->[0]) }
$array = [@V];
} elsif (scalar(@{$array}) == 1) {
my @d = ($self->classMatch("Matrix") ? $self->dimensions : (1));
$array = $array->[0] if scalar(@d) == 1;
}
my $type = $self;
$type = $self->Package($self->{tree}->type) if $self->isFormula;
$ans->{student_formula} = eval { $type->new($array)->with(ColumnVector => $self->{ColumnVector}) };
if (!defined($ans->{student_formula}) || $self->context->{error}{flag}) {
Parser::reportEvalError($@);
$self->cmp_error($ans);
return 0;
}
$ans->{student_formula}{tree}{open} = $self->{open} if $self->{open};
$ans->{student_formula}{tree}{close} = $self->{close} if $self->{close};
$ans->{student_value} = $ans->{student_formula};
$ans->{preview_text_string} = $ans->{student_ans};
$ans->{preview_latex_string} = $ans->{student_formula}->TeX;
return 0 if $ans->{typeError};
if (Value::isFormula($ans->{student_formula}) && $ans->{student_formula}->isConstant) {
$ans->{student_value} = Parser::Evaluate($ans->{student_formula});
return 0 unless $ans->{student_value};
}
return 1;
}
#
# Check if the parsed student answer equals the professor's answer
#
sub cmp_equal {
my $self = shift;
my $ans = shift;
my $correct = $ans->{correct_value};
my $student = $ans->{student_value};
if ($correct->typeMatch($student, $ans)) {
$self->context->clearError();
my $equal = $correct->cmp_compare($student, $ans);
if ($self->context->{error}{flag} != $CMP_MESSAGE
&& (defined($equal) || !$ans->{showEqualErrors}))
{
$ans->score(0 + $equal) if $equal;
return;
}
$self->cmp_error($ans);
} else {
return if $ans->{ignoreStrings} && (!Value::isValue($student) || $student->type eq 'String');
$ans->{typeError} = 1;
$ans->{ans_message} = $ans->{error_message} =
"Your answer isn't " . lc($ans->{cmp_class}) . "\n" . "(it looks like " . lc($student->showClass) . ")"
if !$ans->{isPreview} && $ans->{showTypeWarnings} && !$ans->{error_message};
}
}
#
# Perform the comparison, either using the checker supplied
# by the answer evaluator, or the overloaded == operator.
#
our $CMP_ERROR = 2; # a fatal error was detected
our $CMP_WARNING = 3; # a warning was produced
our $CMP_MESSAGE = 4; # a message should be reported for this check
sub cmp_compare {
my $self = shift;
my $other = shift;
my $ans = shift;
my $nth = shift || '';
my $context = (Value::isValue($self) ? $self->context : Value->context);
return eval { $self == $other } unless ref($ans->{checker}) eq 'CODE';
my @equal = eval { &{ $ans->{checker} }($self, $other, $ans, $nth, @_) };
if (!defined($equal) && $@ ne '' && (!$context->{error}{flag} || $ans->{showAllErrors})) {
$nth = "" if ref($nth) eq 'AnswerHash';
$context->setError(
[
"<I>An error occurred while checking your$nth answer:</I>\n"
. '<DIV STYLE="margin-left:1em">%s</DIV>',
$@
],
'', undef, undef,
$CMP_ERROR
);
warn "Please inform your instructor that an error occurred while checking your answer";
}
return (wantarray ? @equal : $equal[0]);
}
sub cmp_list_compare { Value::List::cmp_list_compare(@_) }
#
# Check if types are compatible for equality check
#
sub typeMatch {
my $self = shift;
my $other = shift;
return 1 unless ref($other);
$self->type eq $other->type && !$other->isFormula;
}
#
# Class name for cmp error messages
#
sub cmp_class {
my $self = shift;
my $ans = shift;
my $class = $self->showClass;
$class =~ s/Real //;
return $class if $class =~ m/Formula/;
return "an Interval, Set or Union" if $self->isSetOfReals;
return $class;
}
#
# Student answer evaluation failed.
# Report the error, with formatting, if possible.
#
sub cmp_error {
my $self = shift;
my $ans = shift;
my $error = $self->context->{error};
my $message = $error->{message};
if ($error->{pos}) {
my $string = $error->{string};
my ($s, $e) = @{ $error->{pos} };
$message =~ s/; see.*//; # remove the position from the message
$ans->{student_ans} =
protectHTML(substr($string, 0, $s))
. '<SPAN CLASS="parsehilight">'
. protectHTML(substr($string, $s, $e - $s))
. '</SPAN>'
. protectHTML(substr($string, $e));
}
$self->cmp_Error($ans, $message);
}
#
# Set the error message
#
sub cmp_Error {
my $self = shift;
my $ans = shift;
return unless scalar(@_) > 0;
$ans->score(0);
$ans->{ans_message} = $ans->{error_message} = join("\n", @_);
}
#
# Force a message into the results message column and die
# (To be used when overriding Parser classes that need
# to report errors to the student but can't do it in
# the overridden == since errors are trapped.)
#
sub cmp_Message {
my $message = shift;
my $context = Value->context;
$message = [ $message, @_ ] if scalar(@_) > 0;
$context->setError($message, '', undef, undef, $CMP_MESSAGE);
$message = $context->{error}{message};
die $message . traceback() if $context->flags('showTraceback');
die $message . getCaller();
}
#
# filled in by sub-classes
#
sub cmp_preprocess { }
sub cmp_postprocess { }
#
# Used to call an object's method as a pre- or post-filter.
# E.g.,
# $cmp->install_pre_filter(\&Value::cmp_call_filter,"cmp_prefilter");
#
sub cmp_call_filter {
my $ans = shift;
my $method = shift;
return $ans->{correct_value}->$method($ans, @_);
}
#
# Check for unreduced reduced Unions and Sets
#
sub cmp_checkUnionReduce {
my $self = shift;
my $student = shift;
my $ans = shift;
my $nth = shift || '';
return
unless $ans->{studentsMustReduceUnions}
&& $ans->{showUnionReduceWarnings}
&& !$ans->{isPreview}
&& !Value::isFormula($student);
return unless $student->isSetOfReals;
my ($result, $error) = $student->isReduced;
return unless $error;
return {
"overlaps" => "Your$nth union contains overlapping intervals",
"overlaps in sets" => "Your$nth union contains sets and intervals that overlap",
"uncombined intervals" => "Your$nth union can be simplified by combining intervals",
"uncombined sets" => "Your$nth union can be simplified by combining some sets",
"repeated elements in set" => "Your$nth union contains sets with repeated elements",
"repeated elements" => "Your$nth set should have no repeated elements",
}->{$error};
}
#
# create answer rules of various types
#
sub ans_rule { shift; pgCall('ans_rule', @_) }
sub named_ans_rule { shift; pgCall('NAMED_ANS_RULE', @_) }
sub named_ans_rule_extension { shift; pgCall('NAMED_ANS_RULE_EXTENSION', @_) }
sub ans_array { shift->ans_rule(@_) }
sub named_ans_array { shift->named_ans_rule(@_) }
sub named_ans_array_extension { shift->named_ans_rule_extension(@_) }
sub pgCall { my $call = shift; &{ WeBWorK::PG::Translator::PG_restricted_eval('\&' . $call) }(@_) }
sub pgRef { WeBWorK::PG::Translator::PG_restricted_eval('\&' . shift) }
our $answerPrefix = "MaTrIx";
#
# Lay out a matrix of answer rules
#
sub ans_matrix {
my $self = shift;
my $extend = shift;
my $name = shift;
my $rows = shift;
my $cols = shift;
my $size = shift;
my $open = shift;
my $close = shift;
my $sep = shift;
my $toplabels = shift;
my %options = @_;
#die(join(';',map {"$_ and $options{$_}"} keys %options));
my $named_extension = pgRef('NAMED_ANS_ARRAY_EXTENSION');
my $named_ans_rule = pgRef('NAMED_ANS_RULE');
my $HTML = "";
my $ename = $name;
$name = pgCall('NEW_ANS_NAME') if ($name eq '');
$ename = "${answerPrefix}_${name}";
$self->{ans_name} = $ename;
$self->{ans_rows} = $rows;
$self->{ans_cols} = $cols;
# warn "ans_matrix: ename=$ename answer_group_name=$options{answer_group_name}";
my @array = ();
foreach my $i (0 .. $rows - 1) {
my @row = ();
foreach my $j (0 .. $cols - 1) {
my $label;
if ($options{aria_label}) {
$label = $options{aria_label} . 'row ' . ($i + 1) . ' col ' . ($j + 1);
} else {
$label = pgCall('generate_aria_label', ANS_NAME($ename, $i, $j));
}
my $answer_group_name = $options{answer_group_name} // $name;
if ($i == 0 && $j == 0) {
if ($extend) {
push(
@row,
&$named_extension(
$name, $size,
answer_group_name => $answer_group_name,
aria_label => $label
)
);
} else {
push(@row, &$named_ans_rule($name, $size, aria_label => $label));
}
} else {
push(
@row,
&$named_extension(
ANS_NAME($ename, $i, $j), $size,
answer_group_name => $answer_group_name,
aria_label => $label
)
);
}
}
push(@array, [@row]);
}
$self->format_matrix([@array], open => $open, close => $close, sep => $sep, top_labels => $toplabels);
}
sub ANS_NAME {
my ($name, $i, $j) = @_;
$name . '_' . $i . '_' . $j;
}
#
# Lay out an arbitrary matrix
#
sub format_matrix {
my $self = shift;
my $array = shift;
my $displayMode = $self->getPG('$displayMode');
$array = [$array] unless ref($array->[0]) eq 'ARRAY';
return $self->format_matrix_tex($array, @_) if ($displayMode eq 'TeX');
return $self->format_matrix_PTX($array, @_) if ($displayMode eq 'PTX');
return $self->format_matrix_HTML($array, @_);
}
sub format_matrix_tex {
my $self = shift;
my $array = shift;
my %options = (open => '.', close => '.', sep => '', @_);
$self->{format_options} = [%options] unless $self->{format_options};
my ($open, $close, $sep) = ($options{open}, $options{close}, $options{sep});
my ($rows, $cols) = (scalar(@{$array}), scalar(@{ $array->[0] }));
my $tex = "";
my @rows = ();
$open = '\\' . $open if $open =~ m/[{}]/;
$close = '\\' . $close if $close =~ m/[{}]/;
$tex .= '\(\left' . $open . '\let\quad=\relax'; # WHY is there a \quad in the answer rule extension?
$tex .= '\setlength{\arraycolsep}{2pt}', $sep = '\,' . $sep if $sep;
$tex .= '\begin{array}{' . ('c' x $cols) . '}';
if ($options{top_labels}) {
push @rows, join($sep . '&', @{ $options{top_labels} });
}
foreach my $i (0 .. $rows - 1) { push(@rows, join($sep . '&', @{ $array->[$i] })) }
$tex .= join('\cr' . "\n", @rows);
$tex .= '\end{array}\right' . $close . '\)';
return $tex;
}
sub format_matrix_PTX {
my $self = shift;
my $array = shift;
my ($rows, $cols) = (scalar(@{$array}), scalar(@{ $array->[0] }));
my $ptx = '<fillin';
$ptx .= qq( rows="$rows") if $rows > 1;
$ptx .= qq( cols="$cols") if $cols > 1;
$ptx .= '/>';
return $ptx;
}
sub format_matrix_HTML {
my $self = shift;
my $array = shift;
my %options = (open => '', close => '', sep => '', tth_delims => 0, @_);
$self->{format_options} = [%options] unless $self->{format_options};
my ($open, $close, $sep) = ($options{open}, $options{close}, $options{sep});
my ($rows, $cols) = (scalar(@{$array}), scalar(@{ $array->[0] }));
my $HTML = "";
my $class = 'class="ans_array_cell"';
my $cell = "display:table-cell;vertical-align:middle;";
my $pad = "padding:4px 0;";
if ($sep) { $sep = '<span class="ans_array_sep" style="' . $cell . 'padding:0 2px">' . $sep . '</span>' }
else { $sep = '<span class="ans_array_sep" style="' . $cell . 'width:8px"></span>' }
$sep = '</span>' . $sep . '<span ' . $class . ' style="' . $cell . $pad . '">';
if ($options{top_labels}) {
$HTML .=
'<span style="display:table-row"><span '
. $class
. ' style="'
. $cell
. $pad . '">'
. join($sep, @{ $options{top_labels} })
. '</span></span>';
}
foreach my $i (0 .. $rows - 1) {
$HTML .=
'<span style="display:table-row"><span '
. $class
. ' style="'
. $cell
. $pad . '">'
. join($sep, EVALUATE(@{ $array->[$i] }))
. '</span></span>';
}
$HTML = '<span class="ans_array_table" style="display:inline-table; vertical-align:middle">' . $HTML . '</span>';
$open = $self->format_delimiter($open, $rows, $options{tth_delims});
$close = $self->format_delimiter($close, $rows, $options{tth_delims});
if ($open ne '' || $close ne '') {
my $delim = "display:inline-block; vertical-align:middle;";
$HTML =
'<span class="ans_array_open" style="'
. $delim
. ' margin-right:4px">'
. $open
. '</span>'
. $HTML
. '<span class="ans_array_close" style="'
. $delim
. ' margin-left:4px">'
. $close
. '</span>';
}
return '<span class="ans_array" style="display:inline-block;vertical-align:.5ex">' . $HTML . '</span>';
}
sub EVALUATE {
map { (Value::isFormula($_) && $_->isConstant ? $_->eval : $_) } @_;
}
sub VERBATIM {
my $string = shift;
my $displayMode = Value->getPG('$displayMode');
$string = '\end{verbatim}' . $string . '\begin{verbatim}' if $displayMode eq 'TeX';
return $string;
}
#
# Create a tall delimiter to match the line height
#
sub format_delimiter {
my $self = shift;
my $delim = shift;
my $rows = shift;
my $tth = shift;
return '' if $delim eq '' || $delim eq '.';
my $displayMode = $self->getPG('$displayMode');
return $self->format_delimiter_tth($delim, $rows, $tth)
if $tth || $displayMode eq 'HTML_tth' || $displayMode !~ m/^HTML_/;
my $rule = '\vrule width 0pt height ' . $rows . 'em depth 0pt';
$rule = '\Rule{0pt}{' . (1.2 * $rows) . 'em}{0pt}' if $displayMode eq 'HTML_MathJax';
$rule = '\rule 0pt ' . (1.2 * $rows) . 'em 0pt' if $displayMode eq 'HTML_jsMath';
$delim = '\\' . $delim if $delim eq '{' || $delim eq '}';
return '\(\left' . $delim . $rule . '\right.\)';
}
#
# Data for tth delimiters [top,mid,bot,rep]
#
$tth_family = "symbol";
my %tth_delim = (
'[' => [ '⎡', '', '⎣', '⎢' ],
']' => [ '⎤', '', '⎦', '⎥' ],
'(' => [ '⎛', '', '⎝', '⎜' ],
')' => [ '⎞', '', '⎠', '⎟' ],
'{' => [ '⎧', '⎨', '⎩', '⎪' ],
'}' => [ '⎫', '⎬', '⎭', '⎪' ],
'|' => [ '|', '', '|', '|' ],
'<' => ['⟨'],
'>' => ['⟩'],
'\lgroup' => [ '⎧', '', '⎩', '⎪' ],
'\rgroup' => [ '⎫', '', '⎭', '⎪' ],
);
#
# Make delimiters as stacks of characters
#
sub format_delimiter_tth {
my $self = shift;
my $delim = shift;
my $rows = shift;
my $tth = shift;
return '' if $delim eq '' || !defined($tth_delim{$delim});
my $c = $delim;
$delim = $tth_delim{$delim};
$c = $delim->[0] if scalar(@{$delim}) == 1;
my $size = ($tth ? "" : "font-size:175%; ");
return '<SPAN STYLE="font-family: ' . $tth_family . '; ' . $size . 'margin:0px 2px">' . $c . '</SPAN>'
if $rows == 1 || scalar(@{$delim}) == 1;
my $HTML = "";
if ($delim->[1] eq '') {
$HTML = join('<BR>', $delim->[0], ($delim->[3]) x (2 * ($rows - 1)), $delim->[2]);
} else {
$HTML = join('<BR>',
$delim->[0], ($delim->[3]) x ($rows - 1),
$delim->[1], ($delim->[3]) x ($rows - 1),
$delim->[2]);
}
return '<DIV STYLE="font-family: ' . $tth_family . '; line-height:90%; margin: 0px 2px">' . $HTML . '</DIV>';
}
#
# Look up the values of the answer array entries, and check them
# for syntax and other errors. Build the student answer
# based on these, and keep track of error messages.
#
my @ans_cmp_defaults = (showCoodinateHints => 0, checker => sub {0});
sub ans_collect {
my $self = shift;
my $ans = shift;
my $inputs = $self->getPG('$inputs_ref');
my $blank = ($self->getPG('$displayMode') eq 'TeX') ? '\_\_' : '__';
my ($rows, $cols) = ($self->{ans_rows}, $self->{ans_cols});
my @array = ();
my $data = [ $self->value ];
my $errors = [];
my $OK = 1;
if ($self->{ColumnVector}) {
foreach my $x (@{$data}) { $x = [$x] }
}
$data = [$data] unless ref($data->[0]) eq 'ARRAY';
foreach my $i (0 .. $rows - 1) {
my @row = ();
my $entry;
foreach my $j (0 .. $cols - 1) {
if ($i || $j) {
$entry = $inputs->{ ANS_NAME($self->{ans_name}, $i, $j) };
} else {
$entry = $ans->{original_student_ans};
$ans->{student_formula} = $ans->{student_value} = undef unless $entry =~ m/\S/;
}
# Pass the mathQuillOpts on to each entry to ensure that the correct parsing is used for each entry.
# This really only needs to know if MathQuill is disabled or not, but it is more efficient to just pass on the reference.
# The value is safely ignored if $ans->{mathQuillOpts} does not match /^\s*disabled\s*$/i.
my $result =
$data->[$i][$j]->cmp(@ans_cmp_defaults, mathQuillOpts => $ans->{mathQuillOpts})->evaluate($entry);
$OK &= entryCheck($result, $blank);
$ans->{typeError} = 1 if $result->{typeError};
push(@row, $result->{student_formula});
entryMessage($result->{ans_message}, $errors, $i, $j, $rows, $cols);
}
push(@array, [@row]);
}
$ans->{student_formula} = [@array];
$ans->{ans_message} = $ans->{error_message} = "";
if (scalar(@{$errors})) {
$ans->{ans_message} = $ans->{error_message} =
'<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="0" CLASS="ArrayLayout">'
. join('<TR><TD HEIGHT="4"></TD></TR>', @{$errors})
. '</TABLE>';
$OK = 0;
}
return $OK;
}
sub entryMessage {
my $message = shift;
return unless $message;
my ($errors, $i, $j, $rows, $cols) = @_;
$i++;
$j++;
my $title;
if ($rows == 1) { $title = "In entry $j" }
elsif ($cols == 1) { $title = "In entry $i" }
else { $title = "In entry ($i,$j)" }
push(
@{$errors},
"<TR><TD NOWRAP STYLE=\"vertical-align:top; background-color:transparent; text-align:right; border:0px\"><I>$title</I>: </TD>"
. "<TD STYLE=\"background-color:transparent; text-align:left; border:0px\">$message</TD></TR>"
);
}
sub entryCheck {
my $ans = shift;
my $blank = shift;
return 1 if defined($ans->{student_value}) || $ans->{typeError};
if (!defined($ans->{student_formula})) {
$ans->{student_formula} = $ans->{student_ans};
$ans->{student_formula} = $blank unless $ans->{student_formula};
}
return 0;
}
#
# Get and Set values in context
#
sub contextSet {
my $context = shift;
my %set = (@_);
my $flags = $context->{flags};
my $get = {};
foreach my $id (keys %set) { $get->{$id} = $flags->{$id}; $flags->{$id} = $set{$id} }
return $get;
}
#
# Quote HTML characters
#
sub protectHTML {
my $string = shift;
return unless defined($string);
return $string if eval('$main::displayMode') eq 'TeX';
$string =~ s/&/\&/g;
$string =~ s/</\</g;
$string =~ s/>/\>/g;
$string;
}
#
# Convert newlines to <BR>
#
sub preformat {
my $string = protectHTML(shift);
return unless defined $string;
$string =~ s!\n!<br />!g unless eval('$main::displayMode') eq 'TeX';
$string;
}
#
# names for numbers
#
sub NameForNumber {
my $self = shift;
my $n = shift;
my $name =
('zeroth', 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth')[$n];
$name = "$n-th" if ($n > 10);
return $name;
}
#
# Get a value from the safe compartment
#
sub getPG {
my $self = shift;
# (WeBWorK::PG::Translator::PG_restricted_eval(shift))[0];
eval('package main; ' . shift); # faster
}
#############################################################
#############################################################
=head3 Value::Real
Usage ANS( Real(3.56)->cmp() )
Compares response to a real value using 'fuzzy' comparison
compareOptions and default values:
showTypeWarnings => 1,
showEqualErrors => 1,
ignoreStrings => 1,
=cut
package Value::Real;
sub cmp_defaults { (shift->SUPER::cmp_defaults(@_), ignoreInfinity => 1,) }
sub typeMatch {
my $self = shift;
my $other = shift;
my $ans = shift;
return 1 unless ref($other);
return 0 if Value::isFormula($other);
return 1 if $other->type eq 'Infinity' && $ans->{ignoreInfinity};
$self->type eq $other->type;
}
#############################################################
package Value::Infinity;
sub cmp_class {'a Number'}
sub typeMatch {
my $self = shift;
my $other = shift;
my $ans = shift;
return 1 unless ref($other);
return 0 if Value::isFormula($other);
return 1 if $other->type eq 'Number';
$self->type eq $other->type;
}
#############################################################
=head3 Value::String
Usage: $s = String("pole");
ANS($s->cmp(typeMatch => Complex("4+i")));
# compare to response 'pole', don't complain about complex number responses.
compareOptions and default values:
showTypeWarnings => 1,
showEqualErrors => 1,
ignoreStrings => 1, # don't complain about string-valued responses
typeMatch => 'Value::Real'
Initial and final spaces are ignored when comparing strings.
=cut
package Value::String;
sub cmp_defaults { (Value::Real->cmp_defaults(@_), typeMatch => 'Value::Real',) }
sub cmp_class {
my $self = shift;
my $ans = shift;
my $typeMatch = $ans->{typeMatch};
return 'a Word' if !Value::isValue($typeMatch) || $typeMatch->classMatch('String');
return $typeMatch->cmp_class;
}
sub typeMatch {
my $self = shift;
my $other = shift;
my $ans = shift;
my $typeMatch = $ans->{typeMatch};
return &$typeMatch($other, $ans) if ref($typeMatch) eq 'CODE';
return 1
if !Value::isValue($typeMatch)
|| $typeMatch->classMatch('String')
|| $self->type eq $other->type;
return $typeMatch->typeMatch($other, $ans);
}
#
# Remove the blank-check prefilter when the string is empty,
# and add a filter that removes leading and trailing whitespace.
# Also, properly quote the correct answer string.
#
sub cmp {
my $self = shift;
my $correct = ($self->{correct_ans} || $self->string);
my $cmp = $self->SUPER::cmp(
correct_ans => $self->quoteHTML($correct),
correct_ans_latex_string => $self->quoteTeX($correct),
@_
);
if ($self->value =~ m/^\s*$/) {
$cmp->install_pre_filter('erase');
$cmp->install_pre_filter(sub {
my $ans = shift;
$ans->{student_ans} =~ s/^\s+//g;
$ans->{student_ans} =~ s/\s+$//g;
return $ans;
});
}
return $cmp;
}
#
# Adjust student preview and anser strings so they display properly
#
sub cmp_preprocess {
my $self = shift;
my $ans = shift;
if (defined $ans->{student_value}) {
$ans->{preview_latex_string} = $ans->{student_value}->TeX;
$ans->{student_ans} = $self->quoteHTML($ans->{student_value}->string);
}
}
#############################################################
=head3 Value::Point
Usage: $pt = Point("(3,6)"); # preferred
or $pt = Point(3,6);
or $pt = Point([3,6]);
ANS($pt->cmp());
compareOptions:
showTypeWarnings => 1, # warns if student response is of incorrect type
showEqualErrors => 1,
ignoreStrings => 1,
showDimensionHints => 1, # reports incorrect number of coordinates
showCoordinateHints =>1, # flags individual coordinates that are incorrect
=cut
package Value::Point;
sub cmp_defaults { (
shift->SUPER::cmp_defaults(@_),
showDimensionHints => 1,
showCoordinateHints => 1,
) }
sub typeMatch {
my $self = shift;
my $other = shift;
my $ans = shift;
return ref($other) && $other->type eq 'Point' && !$other->isFormula;
}
#
# Check for dimension mismatch and incorrect coordinates
#
sub cmp_postprocess {
my $self = shift;
my $ans = shift;
return unless $ans->{score} == 0 && !$ans->{isPreview};
my $student = $ans->{student_value};
return if $ans->{ignoreStrings} && (!Value::isValue($student) || $student->type eq 'String');
if ($ans->{showDimensionHints} && $self->length != $student->length) {
$self->cmp_Error($ans, "The number of coordinates is incorrect");
return;
}
if ($ans->{showCoordinateHints}) {
my @errors;
foreach my $i (1 .. $self->length) {
push(@errors, "The " . $self->NameForNumber($i) . " coordinate is incorrect")
if ($self->{data}[ $i - 1 ] != $student->{data}[ $i - 1 ]);
}
$self->cmp_Error($ans, @errors);
return;
}