File:
[LON-CAPA] /
loncom /
homework /
default_homework.lcpm
Revision
1.151:
download - view:
text,
annotated -
select for diffs
Thu Dec 16 16:01:01 2010 UTC (13 years, 8 months ago) by
raeburn
Branches:
MAIN
CVS tags:
version_2_10_0_RC2,
HEAD
- Bug 5531.
caparesponse.pm
- For stringresponse: (case (in)sensitive) computer's answer available
in detailed submission display.
- Student username in warnings on control characters etc. renamed $sname
instead of $name (already in use in different scope) to improve code
readability
- computer answer available for legacy stringresponse submission (e.g.,
for bug 5531 detection script -see neutrinohavest.pl)
if grade_retrieveanswers included in form for answer target.
default_homework.pm
- fix detection of control characters in answers - answers will be in
an array
- computer's answer returned by &caparesponse_check_list()
loncommon.pm
- &format_previous_attempt_value() handles display of computer's answer.
- fix typo in phrase for localization (no current translations in
localize/*.pm to update).
1: # The LearningOnline Network with CAPA
2: # used by lonxml::xmlparse() as input variable $safeinit to Apache::run::run()
3: #
4: # $Id: default_homework.lcpm,v 1.151 2010/12/16 16:01:01 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28: #
29:
30: #init some globals
31: $hidden::RANDOMINIT=0;
32: $pi=atan2(1,1)*4;
33: $rad2deg=180.0/$pi;
34: $deg2rad=$pi/180.0;
35: $"=' ';
36: use strict;
37: {
38: my $n = 0;
39: my $total = 0;
40: my $num_left = 0;
41: my @order;
42: my $type;
43:
44: sub init_permutation {
45: my ($size,$requested_type) = @_;
46: @order = (0..$size-1);
47: $n = $size;
48: $type = $requested_type;
49: if ($type eq 'ordered') {
50: $total = $num_left = 1;
51: } elsif ($type eq 'unordered') {
52: $total = $num_left = &factorial($size);
53: } else {
54: die("Unkown type: $type");
55: }
56: }
57:
58: sub get_next_permutation {
59: if ($num_left == $total) {
60: $num_left--;
61: return \@order;
62: }
63:
64: # Find largest index j with a[j] < a[j+1]
65:
66: my $j = scalar(@order) - 2;
67: while ($order[$j] > $order[$j+1]) {
68: $j--;
69: }
70:
71: # Find index k such that a[k] is smallest integer
72: # greater than a[j] to the right of a[j]
73:
74: my $k = scalar(@order) - 1;
75: while ($order[$j] > $order[$k]) {
76: $k--;
77: }
78:
79: # Interchange a[j] and a[k]
80:
81: @order[($k,$j)] = @order[($j,$k)];
82:
83: # Put tail end of permutation after jth position in increasing order
84:
85: my $r = scalar(@order) - 1;
86: my $s = $j + 1;
87:
88: while ($r > $s) {
89: @order[($s,$r)]=@order[($r,$s)];
90: $r--;
91: $s++;
92: }
93:
94: $num_left--;
95: return(\@order);
96: }
97:
98: sub get_permutations_left {
99: return $num_left;
100: }
101: }
102:
103: sub check_commas {
104: my ($response)=@_;
105: #print("$response ");
106: my @numbers=split(',',$response);
107: #print(" numbers ".join('-',@numbers)." ");
108: if (scalar(@numbers) > 1) {
109: #print(" numbers[0] ".$numbers[0]." ");
110: if (length($numbers[0]) > 3 || length($numbers[0]) == 0) { return -1; }
111: shift(@numbers);
112: #print(" numbers ".scalar(@numbers)." ");
113: while (scalar(@numbers) > 1) {
114: #print(" numbers ".join('-',@numbers)." ");
115: if (length($numbers[0]) != 3) { return -2; }
116: shift(@numbers);
117: }
118: my ($number)=split('\.',$numbers[0]);
119: #print(" number ".$number." ");
120: #print(" numbers[0] ".$numbers[0]." ");
121: if (length($number) != 3) { return -3; }
122: } else {
123: my ($number)=split('\.',$numbers[0]);
124: if (length($number) > 3) { return -4; }
125: }
126: return 1;
127: }
128:
129:
130: sub caparesponse_check {
131: my ($answer,$response)=@_;
132: #not properly used yet: calc
133: #not to be used: $ans_fmt
134: my $type=$LONCAPA::CAPAresponse_args{'type'};
135: my $tol=$LONCAPA::CAPAresponse_args{'tol'};
136: my $sig=$LONCAPA::CAPAresponse_args{'sig'};
137: my $ans_fmt=$LONCAPA::CAPAresponse_args{'format'};
138: my $unit=$LONCAPA::CAPAresponse_args{'unit'};
139: my $calc=$LONCAPA::CAPAresponse_args{'calc'};
140: my $samples=$LONCAPA::CAPAresponse_args{'samples'};
141:
142: my $tol_type=''; # gets it's value from whether tol has a % or not done
143: my $sig_lbound=''; #done
144: my $sig_ubound=''; #done
145:
146:
147: #type's definitons come from capaParser.h
148:
149: #remove leading and trailing whitespace
150: if (!defined($response)) {
151: $response='';
152: }
153: if ($response=~ /^\s|\s$/) {
154: $response=~ s:^\s+|\s+$::g;
155: &LONCAPA_INTERNAL_DEBUG("Removed ws now :$response:");
156: }
157:
158: #&LONCAPA_INTERNAL_DEBUG(" type is $type ");
159: if ($type eq 'cs' || $type eq 'ci') {
160: #for string answers make sure all places spaces occur, there is
161: #really only 1 space, in both the answer and the response
162: $answer=~s/ +/ /g;
163: $response=~s/ +/ /g;
164: } elsif ($type eq 'mc') {
165: $answer=~s/[\s,]//g;
166: $response=~s/[\s,]//g;
167: }
168: if ($type eq 'float' && $unit=~/\$/) {
169: if ($response!~/^\$|\$$/) { return ('NO_UNIT', undef); }
170: $response=~s/\$//g;
171: }
172: if ($type eq 'float' && $unit=~/\,/ && (&check_commas($response)<0)) {
173: return "COMMA_FAIL:";
174: }
175: $ans_fmt=~s/\W//g;
176: $unit=~s/[\$,]//g;
177: if ($type eq 'float') { $response=~s/,//g; }
178:
179: if (length($response) > 500) { return ('TOO_LONG',undef); }
180:
181: if ($type eq '' ) {
182: &LONCAPA_INTERNAL_DEBUG("Didn't find a type :$type: defaulting");
183: if ( $answer eq ($answer *1.0)) { $type = 2;
184: } else { $type = 3; }
185: } else {
186: if ($type eq 'cs') { $type = 4; }
187: elsif ($type eq 'ci') { $type = 3 }
188: elsif ($type eq 'mc') { $type = 5; }
189: elsif ($type eq 'fml') { $type = 8; }
190: elsif ($type eq 'math') { $type = 9; }
191: elsif ($type eq 'subj') { $type = 7; }
192: elsif ($type eq 'float') { $type = 2; }
193: elsif ($type eq 'int') { $type = 1; }
194: else { return ('ERROR', "Unknown type of answer: $type") }
195: }
196:
197: my $points;
198: my $id_list;
199: #formula type setup the sample points
200: if ($type eq '8') {
201: ($id_list,$points)=split(/@/,$samples);
202: &LONCAPA_INTERNAL_DEBUG("Found :$id_list:$points: points in $samples");
203: }
204: if ($tol eq '') {
205: $tol=0.0;
206: $tol_type=1; #TOL_ABSOLUTE
207: } else {
208: if ($tol =~ /%$/) {
209: chop $tol;
210: $tol_type=2; #TOL_PERCENTAGE
211: } else {
212: $tol_type=1; #TOL_ABSOLUTE
213: }
214: }
215:
216: ($sig_ubound,$sig_lbound)=&LONCAPA_INTERNAL_get_sigrange($sig);
217:
218: my $reterror="";
219: my $result;
220: if (($type eq '9') || ($type eq '8')) {
221: if ($response=~/\=/) {
222: return ('BAD_FORMULA','Please submit just an expression, not an equation.');
223: } elsif ($response =~ /\,/ and $response !~ /^\s*\{.*\}\s*$/) {
224: return ('BAD_FORMULA');
225: }
226: }
227: if ($type eq '9') {
228: $result = &maxima_check(&maxima_cas_formula_fix($response),&maxima_cas_formula_fix($answer),\$reterror);
229: } else {
230: if ($type eq '8') { # fml type
231: $response = &capa_formula_fix($response);
232: $answer = &capa_formula_fix($answer);
233: }
234: $result = &caparesponse_capa_check_answer($response,$answer,$type,
235: $tol_type,$tol,
236: $sig_lbound,$sig_ubound,
237: $ans_fmt,$unit,$calc,$id_list,
238: $points,$external::randomseed,
239: \$reterror);
240: }
241: if ($result == '1') { $result='EXACT_ANS'; }
242: elsif ($result == '2') { $result='APPROX_ANS'; }
243: elsif ($result == '3') { $result='SIG_FAIL'; }
244: elsif ($result == '4') { $result='UNIT_FAIL'; }
245: elsif ($result == '5') { $result='NO_UNIT'; }
246: elsif ($result == '6') { $result='UNIT_OK'; }
247: elsif ($result == '7') { $result='INCORRECT'; }
248: elsif ($result == '8') { $result='UNIT_NOTNEEDED'; }
249: elsif ($result == '9') { $result='ANS_CNT_NOT_MATCH'; }
250: elsif ($result =='10') { $result='SUB_RECORDED'; }
251: elsif ($result =='11') { $result='BAD_FORMULA'; }
252: elsif ($result =='12' && !$response) { $result='MISSING_ANSWER'; }
253: elsif ($result =='12') { $result='WANTED_NUMERIC'; }
254: elsif ($result =='13') { $result='UNIT_INVALID_INSTRUCTOR'; }
255: elsif ($result =='141') { $result='UNIT_INVALID_STUDENT'; }
256: elsif ($result =='142') { $result='UNIT_INVALID_STUDENT'; }
257: elsif ($result =='143') { $result='UNIT_INVALID_STUDENT'; }
258: elsif ($result =='15') { $result='UNIT_IRRECONCIBLE'; }
259: else {$result = "ERROR: Unknown Result:$result:$@:";}
260:
261: &LONCAPA_INTERNAL_DEBUG("RetError $reterror: Answer $answer: Response $response: type-$type|$tol|$tol_type|$sig:$sig_lbound:$sig_ubound|$unit|");
262: &LONCAPA_INTERNAL_DEBUG(" $answer $response $result ");
263: return ($result,$reterror);
264: }
265:
266:
267: sub caparesponse_check_list {
268: my $responses=$LONCAPA::CAPAresponse_args{'response'};
269: &LONCAPA_INTERNAL_DEBUG("args ".join(':',%LONCAPA::CAPAresponse_args));
270: my $type = $LONCAPA::CAPAresponse_args{'type'};
271: my $answerunit=$LONCAPA::CAPAresponse_args{'unit'};
272: &LONCAPA_INTERNAL_DEBUG("Got type :$type: answer unit :$answerunit:\n");
273:
274: my $num_input_lines =
275: scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}});
276:
277: if ($type ne '' ) {
278: if (scalar(@$responses) < $num_input_lines) {
279: return 'MISSING_ANSWER';
280: }
281: if (scalar(@$responses) > $num_input_lines) {
282: return 'EXTRA_ANSWER';
283: }
284:
285: }
286:
287: foreach my $which (0..($num_input_lines-1)) {
288: my $answer_size =
289: scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}[$which]});
290: if ($type ne ''
291: && $answer_size > 1) {
292: $responses->[$which]=[split(/,/,$responses->[$which])];
293: } else {
294: $responses->[$which]=[$responses->[$which]];
295: }
296: }
297: foreach my $which (0..($num_input_lines-1)) {
298: my $answer_size =
299: scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}[$which]});
300: my $response_size =
301: scalar(@{$responses->[$which]});
302: if ($answer_size > $response_size) {
303: return 'MISSING_ANSWER';
304: }
305: if ($answer_size < $response_size) {
306: return 'EXTRA_ANSWER';
307: }
308: }
309:
310: &LONCAPA_INTERNAL_DEBUG("Initial final response :$responses->[0][-1]:");
311: my $unit;
312: if ($type eq 'float' || $type eq '') {
313: #for numerical problems split off the unit
314: # if ( $responses->[0][-1]=~ /(.*[^\s])\s+([^\s]+)/ ) {
315: if ( $responses->[0][-1]=~ /^([\d\.\,\s\$]*(?:(?:[xX\*]10[\^\*]*|[eE]*)[\+\-]*\d*)*(?:^|\S)\d+)([\$\s\w\^\*\/\(\)\+\-]*[^\d\.\s\,][\$\s\w\^\*\/\(\)\+\-]*)$/ ) {
316: $responses->[0][-1]=$1;
317: $unit=&capa_formula_fix($2);
318: &LONCAPA_INTERNAL_DEBUG("Found unit :$unit:");
319: }
320: }
321: &LONCAPA_INTERNAL_DEBUG("Final final response :$responses->[0][-1]:$unit:");
322: $unit=~s/\s//;
323: my $error;
324: foreach my $response (@$responses) {
325: foreach my $element (@$response) {
326: if (($type eq 'float') || (($type eq '') && ($unit ne ''))) {
327: $element =~ s/\s//g;
328: }
329: my $appendunit=$unit;
330: # Deal with percentages
331: # unit is unit entered by student, answerunit is unit by author
332: # Deprecated: divide answer by 100 if student entered percent,
333: # but author did not. Too much confusion
334: # if (($unit=~/\%/) && ($answerunit ne '%')) {
335: # $element=$element/100;
336: # $appendunit=~s/\%//;
337: # }
338: # Author entered percent, student did not
339: if (($unit!~/\%/) && ($answerunit=~/\%/)) {
340: $element=$element*100;
341: $appendunit='%'.$appendunit;
342: }
343: # Zero does not need a dimension
344: if (($element==0) && ($unit!~/\w/) && ($answerunit=~/\w/)) {
345: $appendunit=$answerunit;
346: }
347: if ($appendunit ne '') {
348: $element .= " $appendunit";
349: }
350: &LONCAPA_INTERNAL_DEBUG("Made response element :$element:");
351: }
352: }
353:
354: foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
355: if (!defined($thisanswer)) {
356: return ('ERROR','answer was undefined');
357: }
358: }
359:
360: my $allow_control_char = 0;
361: my $control_chars_removed = 0;
362: my $ansstring;
363: if ($type eq 'cs' || $type eq 'ci') {
364: if (ref($LONCAPA::CAPAresponse_answer->{'answers'}) eq 'ARRAY') {
365: foreach my $strans (@{$LONCAPA::CAPAresponse_answer->{'answers'}}) {
366: if (ref($strans) eq 'ARRAY') {
367: foreach my $item (@{$strans}) {
368: if ($item =~ /[\000-\037]/) {
369: $allow_control_char = 1;
370: }
371: }
372: }
373: }
374: }
375: }
376: if (($type eq 'cs') || ($type eq 'ci')) {
377: if (ref($LONCAPA::CAPAresponse_answer->{'answers'}) eq 'ARRAY') {
378: foreach my $answer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
379: if (ref($answer) eq 'ARRAY') {
380: $ansstring = join("\0",@{$answer});
381: }
382: }
383: }
384: }
385:
386: # &LONCAPA_INTERNAL_DEBUG(&LONCAPA_INTERNAL_Dumper($responses));
387: my %memoized;
388: if ($LONCAPA::CAPAresponse_answer->{'type'} eq 'ordered') {
389: for (my $i=0; $i<scalar(@$responses);$i++) {
390: my $answer = $LONCAPA::CAPAresponse_answer->{'answers'}[$i];
391: my $response = $responses->[$i];
392: my $key = "$answer\0$response";
393: my (@awards,@msgs);
394: for (my $j=0; $j<scalar(@$response); $j++) {
395: if ($type eq 'cs' || $type eq 'ci') {
396: unless ($allow_control_char) {
397: if ($response->[$j] =~ /[\000-\037]/) {
398: $response->[$j] =~ s/[\000-\037]//g;
399: $control_chars_removed = 1;
400: }
401: }
402: }
403: my ($award,$msg) = &caparesponse_check($answer->[$j],
404: $response->[$j]);
405: if ($type eq 'cs' || $type eq 'ci') {
406: $error = &verify_stringresponse($type,$award,$response->[$j],
407: $answer->[$j]);
408: }
409: push(@awards,$award);
410: push(@msgs, $msg);
411: }
412: my ($award,$msg) =
413: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
414: $memoized{$key} = [$award,$msg];
415: }
416: } else {
417: #FIXME broken with unorder responses where one is a <value>
418: # and the other is a <vector> (need to delay parse til
419: # inside the loop?)
420: foreach my $response (@$responses) {
421: my $response_size = scalar(@{$response});
422: foreach my $answer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
423: my $key = "$answer\0$response";
424: my $answer_size = scalar(@{$answer});
425: my ($award,$msg);
426: if ($answer_size > $response_size) {
427: $award = 'MISSING_ANSWER';
428: } elsif ($answer_size < $response_size) {
429: $award = 'EXTRA_ANSWER';
430: } else {
431: my (@awards,@msgs);
432: for (my $j=0; $j<scalar(@$response); $j++) {
433: if ($type eq 'cs' || $type eq 'ci') {
434: unless ($allow_control_char) {
435: if ($response->[$j] =~ /[\000-\037]/) {
436: $response->[$j] =~ s/[\000-\037]//g;
437: $control_chars_removed = 1;
438: }
439: }
440: }
441: my ($award,$msg) = &caparesponse_check($answer->[$j],
442: $response->[$j]);
443: if ($type eq 'cs' || $type eq 'ci') {
444: $error = &verify_stringresponse($type,$award,$response->[$j],
445: $answer->[$j]);
446: }
447: push(@awards,$award);
448: push(@msgs, $msg);
449: }
450: ($award,$msg) =
451: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
452: }
453: $memoized{$key} = [$award,$msg];
454: }
455: }
456: }
457:
458: my ($final_award,$final_msg);
459: &init_permutation(scalar(@$responses),
460: $LONCAPA::CAPAresponse_answer->{'type'});
461:
462: # possible FIXMEs
463: # - significant time is spent calling non-safe space routine
464: # from safe space
465: # - early outs could be possible with classifying awards is to stratas
466: # and stopping as so as hitting the top strata
467: # - some early outs also might be possible with check ing the
468: # memoized hash of results (is correct even possible? etc.)
469:
470: my (@final_awards,@final_msg);
471: while( &get_permutations_left() ) {
472: my $order = &get_next_permutation();
473: my (@awards, @msgs, $i);
474: foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
475: my $key = "$thisanswer\0".$responses->[$order->[$i]];
476: push(@awards,$memoized{$key}[0]);
477: push(@msgs,$memoized{$key}[1]);
478: $i++;
479:
480: }
481: &LONCAPA_INTERNAL_DEBUG(" all awards ".join(':',@awards));
482:
483: my ($possible_award,$possible_msg) =
484: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
485: &LONCAPA_INTERNAL_DEBUG(" pos awards ".$possible_award);
486: push(@final_awards,$possible_award);
487: push(@final_msg,$possible_msg);
488: }
489:
490: &LONCAPA_INTERNAL_DEBUG(" all final_awards ".join(':',@final_awards));
491: my ($final_award,$final_msg) =
492: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@final_awards,\@final_msg,undef,1);
493: return ($final_award,$final_msg,$error,$control_chars_removed,$ansstring);
494: }
495:
496: sub verify_stringresponse {
497: my ($type,$award,$resp,$ans) = @_;
498: return if ($award eq 'EXACT_ANS');
499: my $error;
500: if ($resp =~ /^\s|\s$/) {
501: $resp =~ s{^\s+|\s+$}{}g;
502: }
503: if ($ans =~ /^\s|\s$/) {
504: $ans =~ s{^\s+|\s+$}{}g;
505: }
506: if ($type eq 'ci') {
507: $resp = lc($resp);
508: $ans = lc($ans);
509: }
510: if ($resp eq $ans) {
511: if ($award eq 'INCORRECT') {
512: $error = 'MISGRADED';
513: }
514: }
515: return $error;
516: }
517:
518: sub cas {
519: my ($system,$input,$library)=@_;
520: my $output;
521: my $dump;
522: if ($system eq 'maxima') {
523: $output=&maxima_eval($input,$library);
524: } elsif ($system eq 'R') {
525: ($output,$dump)=&r_eval($input,$library,0);
526: } else {
527: $output='Error: unrecognized CAS';
528: }
529: return $output;
530: }
531:
532: sub cas_hashref {
533: my ($system,$input,$library)=@_;
534: if ($system eq 'maxima') {
535: return 'Error: unsupported CAS';
536: } elsif ($system eq 'R') {
537: return &r_eval($input,$library,1);
538: } else {
539: return 'Error: unrecognized CAS';
540: }
541: }
542:
543: #
544: # cas_hashref_entry takes a list of indices and gets the entry in a hash generated by Rreturn.
545: # Call: cas_hashref_entry(Rvalue, index1, index2, ...) where Rvalue is a hash returned by Rreturn.
546: # Rentry will return the first scalar value it encounters (ignoring excess indices).
547: # If an invalid key is given, it returns undef.
548: #
549: sub cas_hashref_entry {
550: return &Rentry(@_);
551: }
552:
553: #
554: # cas_hashref_array takes a list of indices and gets a column array from a hash generated by Rreturn.
555: # Call: cas_hashref_array(Rvalue, index1, index2, ...) where Rvalue is a hash returned by Rreturn.
556: # If an invalid key is given, it returns undef.
557: #
558: sub cas_hashref_array {
559: return &Rarray(@_);
560: }
561:
562: sub tex {
563: if ( $external::target eq "tex" ) {
564: return $_[0];
565: } else {
566: return $_[1];
567: }
568: }
569:
570: sub var_in_tex {
571: if ( $external::target eq "tex" ) {
572: return $_[0];
573: } else {
574: return "";
575: }
576: }
577:
578: sub web {
579: if ( $external::target eq "tex" ) {
580: return $_[1];
581: } else {
582: if ( $external::target eq "web" || $external::target eq "answer") {
583: return $_[2];
584: } else {
585: return $_[0];
586: }
587: }
588: }
589:
590: sub html {
591: if ( $external::target eq "web" ) {
592: return shift;
593: }
594: }
595:
596: sub hinton {
597: return 0;
598: }
599:
600: sub random {
601: my ($start,$end,$step)=@_;
602: if ( ! $hidden::RANDOMINIT ) {
603: if ($external::randomseed == 0) { $external::randomseed=1; }
604: if ($external::randomseed =~/,/) {
605: my ($num1,$num2)=split(/,/,$external::randomseed);
606: &random_set_seed(1,abs($num1));
607: } elsif ($external::randomseed =~/:/) {
608: my ($num1,$num2)=split(/:/,$external::randomseed);
609: &random_set_seed(abs($num1),abs($num2));
610: } else {
611: &random_set_seed(1,int(abs($external::randomseed)));
612: }
613: &math_random_uniform();
614: $hidden::RANDOMINIT=1;
615: }
616: if (!defined($step)) { $step=1; }
617: my $num=1+int(($end-$start)/$step);
618: my $result=$start + int(&math_random_uniform() * $num)*$step;
619: return $result;
620: }
621:
622: sub random_normal {
623: my ($item_cnt,$seed,$av,$std_dev) = @_;
624: my @oldseed=&random_get_seed();
625: my @retArray;
626: &random_set_seed_from_phrase($seed);
627: @retArray=&math_random_normal($item_cnt,$av,$std_dev);
628: &random_set_seed(@oldseed);
629: return @retArray;
630: }
631:
632: sub random_beta {
633: my ($item_cnt,$seed,$aa,$bb) = @_;
634: my @oldseed=&random_get_seed();
635: my @retArray;
636: &random_set_seed_from_phrase($seed);
637: @retArray=&math_random_beta($item_cnt,$aa,$bb);
638: &random_set_seed(@oldseed);
639: return @retArray;
640: }
641:
642: sub random_gamma {
643: my ($item_cnt,$seed,$a,$r) = @_;
644: my @oldseed=&random_get_seed();
645: my @retArray;
646: &random_set_seed_from_phrase($seed);
647: @retArray=&math_random_gamma($item_cnt,$a,$r);
648: &random_set_seed(@oldseed);
649: return @retArray;
650: }
651:
652: sub random_exponential {
653: my ($item_cnt,$seed,$av) = @_;
654: my @oldseed=&random_get_seed();
655: my @retArray;
656: &random_set_seed_from_phrase($seed);
657: @retArray=&math_random_exponential($item_cnt,$av);
658: &random_set_seed(@oldseed);
659: return @retArray;
660: }
661:
662: sub random_poisson {
663: my ($item_cnt,$seed,$mu) = @_;
664: my @oldseed=&random_get_seed();
665: my @retArray;
666: &random_set_seed_from_phrase($seed);
667: @retArray=&math_random_poisson($item_cnt,$mu);
668: &random_set_seed(@oldseed);
669: return @retArray;
670: }
671:
672: sub random_chi {
673: my ($item_cnt,$seed,$df) = @_;
674: my @oldseed=&random_get_seed();
675: my @retArray;
676: &random_set_seed_from_phrase($seed);
677: @retArray=&math_random_chi_square($item_cnt,$df);
678: &random_set_seed(@oldseed);
679: return @retArray;
680: }
681:
682: sub random_noncentral_chi {
683: my ($item_cnt,$seed,$df,$nonc) = @_;
684: my @oldseed=&random_get_seed();
685: my @retArray;
686: &random_set_seed_from_phrase($seed);
687: @retArray=&math_random_noncentral_chi_square($item_cnt,$df,$nonc);
688: &random_set_seed(@oldseed);
689: return @retArray;
690: }
691:
692: sub random_f {
693: my ($item_cnt,$seed,$dfn,$dfd) = @_;
694: my @oldseed=&random_get_seed();
695: my @retArray;
696: &random_set_seed_from_phrase($seed);
697: @retArray=&math_random_f($item_cnt,$dfn,$dfd);
698: &random_set_seed(@oldseed);
699: return @retArray;
700: }
701:
702: sub random_noncentral_f {
703: my ($item_cnt,$seed,$dfn,$dfd,$nonc) = @_;
704: my @oldseed=&random_get_seed();
705: my @retArray;
706: &random_set_seed_from_phrase($seed);
707: @retArray=&math_random_noncentral_f($item_cnt,$dfn,$dfd,$nonc);
708: &random_set_seed(@oldseed);
709: return @retArray;
710: }
711:
712: sub random_multivariate_normal {
713: my ($item_cnt,$seed,$mean,$covar) = @_;
714: my @oldseed=&random_get_seed();
715: &random_set_seed_from_phrase($seed);
716: my @retArray=&math_random_multivariate_normal($item_cnt,@$mean,@$covar);
717: &random_set_seed(@oldseed);
718: return @retArray;
719: }
720:
721: sub random_multinomial {
722: my ($item_cnt,$seed,@p) = @_;
723: my @oldseed=&random_get_seed();
724: my @retArray;
725: &random_set_seed_from_phrase($seed);
726: my @retArray=&math_random_multinomial($item_cnt,@p);
727: &random_set_seed(@oldseed);
728: return @retArray;
729: }
730:
731: sub random_permutation {
732: my ($seed,@inArray) = @_;
733: my @oldseed=&random_get_seed();
734: my @retArray;
735: &random_set_seed_from_phrase($seed);
736: @retArray=&math_random_permutation(@inArray);
737: &random_set_seed(@oldseed);
738: return @retArray;
739: }
740:
741: sub random_uniform {
742: my ($item_cnt,$seed,$low,$high) = @_;
743: my @oldseed=&random_get_seed();
744: my @retArray;
745: &random_set_seed_from_phrase($seed);
746: @retArray=&math_random_uniform($item_cnt,$low,$high);
747: &random_set_seed(@oldseed);
748: return @retArray;
749: }
750:
751: sub random_uniform_integer {
752: my ($item_cnt,$seed,$low,$high) = @_;
753: my @oldseed=&random_get_seed();
754: my @retArray;
755: &random_set_seed_from_phrase($seed);
756: @retArray=&math_random_uniform_integer($item_cnt,$low,$high);
757: &random_set_seed(@oldseed);
758: return @retArray;
759: }
760:
761: sub random_binomial {
762: my ($item_cnt,$seed,$nt,$p) = @_;
763: my @oldseed=&random_get_seed();
764: my @retArray;
765: &random_set_seed_from_phrase($seed);
766: @retArray=&math_random_binomial($item_cnt,$nt,$p);
767: &random_set_seed(@oldseed);
768: return @retArray;
769: }
770:
771: sub random_negative_binomial {
772: my ($item_cnt,$seed,$ne,$p) = @_;
773: my @oldseed=&random_get_seed();
774: my @retArray;
775: &random_set_seed_from_phrase($seed);
776: @retArray=&math_random_negative_binomial($item_cnt,$ne,$p);
777: &random_set_seed(@oldseed);
778: return @retArray;
779: }
780:
781: sub abs { CORE::abs(shift) }
782: sub sin { CORE::sin(shift) }
783: sub cos { CORE::cos(shift) }
784: sub exp { CORE::exp(shift) }
785: sub int { CORE::int(shift) }
786: sub log { CORE::log(shift) }
787: sub atan2 { CORE::atan2($_[0],$_[1]) }
788: sub sqrt { CORE::sqrt(shift) }
789:
790: sub tan { CORE::sin($_[0]) / CORE::cos($_[0]) }
791: #sub atan { atan2($_[0], 1); }
792: #sub acos { atan2(sqrt(1 - $_[0] * $_[0]), $_[0] ); }
793: #sub asin { atan2($_[0], sqrt(1- $_[0] * $_[0]) ); }
794:
795: sub log10 { CORE::log($_[0])/CORE::log(10); }
796:
797: sub factorial {
798: my $input = CORE::int(shift);
799: return "Error - unable to take factorial of an negative number ($input)" if $input < 0;
800: return "Error - factorial result is greater than system limit ($input)" if $input > 170;
801: return 1 if $input == 0;
802: my $result = 1;
803: for (my $i=2; $i<=$input; $i++) { $result *= $i }
804: return $result;
805: }
806:
807: sub sgn {
808: return -1 if $_[0] < 0;
809: return 0 if $_[0] == 0;
810: return 1 if $_[0] > 0;
811: }
812:
813: sub min {
814: my @sorted = sort { $a <=> $b || $a cmp $b } @_;
815: return shift @sorted;
816: }
817:
818: sub max {
819: my @sorted = sort { $a <=> $b || $a cmp $b } @_;
820: return pop @sorted;
821: }
822:
823: sub roundto {
824: my ($input,$n) = @_;
825: return sprintf('%.'.$n.'f',$input);
826: }
827:
828: sub to_string {
829: my ($input,$n) = @_;
830: return sprintf($input) if $n eq "";
831: $n = '.'.$n if $n !~ /^\./;
832: return sprintf('%'.$n,$input) if $n ne "";
833: }
834:
835: sub sub_string {
836: my ($str,$start,$len) = @_;
837: return substr($str,$start-1,$len);
838: }
839:
840: sub pow {return $_[0] ** $_[1]; }
841: sub ceil {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? (CORE::int($_[0])+ 1) : CORE::int($_[0])); }
842: sub floor {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? CORE::int($_[0]) : (CORE::int($_[0])-1)); }
843: #sub floor {return int($_[0]); }
844:
845: sub format {
846: my ($value,$fmt)=@_;
847: my ($dollarmode,$commamode,$alwaysperiod,$options);
848: if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; }
849: #if ($options =~ /\$/) { $dollamode=1; }
850: #if ($options =~ /,/) { $commamode=1; }
851: if ($options =~ /\./) { $alwaysperiod=1; }
852: my $result;
853: if ($fmt=~/s$/i) {
854: $result=&format_significant_figures($value,$fmt);
855: } else {
856: $fmt=~s/e/E/g;
857: $result=sprintf('%.'.$fmt,$value);
858: if ($alwaysperiod && $fmt eq '0f') { $result .='.'; }
859: $result=~s/(E[+-]*)0/$1/;
860: }
861: #if ($dollarmode) {$result=&dollarformat($result);}
862: #if ($commamode) {$result=&commaformat($result);}
863: return $result;
864: }
865:
866: sub chemparse {
867: my ($reaction) = @_;
868: my @tokens = split(/(\s\+|\->|<=>|<\-|\.)/,$reaction);
869: my $formula = '';
870: foreach my $token (@tokens) {
871: if ($token eq '->' ) {
872: $formula .= '<m>\ensuremath{\rightarrow}</m> ';
873: next;
874: }
875: if ($token eq '<-' ) {
876: $formula .= '<m>\ensuremath{\leftarrow}</m> ';
877: next;
878: }
879: if ($token eq '<=>') {
880: if ($external::target eq 'web' &&
881: &EXT('request.browser.unicode')) {
882: $formula .= '⇌ ';
883: } else {
884: $formula .= &web('<=> ','<m>\ensuremath{\rightleftharpoons}</m> ',
885: '<=> ');
886: }
887: next;
888: }
889: if ($token eq '.') {
890: $formula =~ s/(\ \;| )$//;
891: $formula .= '·';
892: next;
893: }
894: $token =~ /^\s*([\d|\/]*(?:&frac\d\d)?)(.*)/;
895: $formula .= $1 if ($1 ne '1'); # stoichiometric coefficient
896:
897: my $molecule = $2;
898: # subscripts
899: $molecule =~ s|(?<=[a-zA-Z\)\]\s])(\d+)|<sub>$1</sub>|g;
900: # superscripts
901: $molecule =~ s|\^(\d*[+\-]*)|<sup>$1</sup>|g;
902: # strip whitespace
903: $molecule =~ s/\s*//g;
904: # forced space
905: $molecule =~ s/_/ /g;
906: $molecule =~ s/-/−/g;
907: $formula .= $molecule.' ';
908: }
909: # get rid of trailing space
910: $formula =~ s/(\ \;| )$//;
911: return &xmlparse($formula);
912: }
913:
914: sub prettyprint {
915: my ($value,$fmt,$target)=@_;
916: my $result;
917: if (!$target) { $target = $external::target; }
918: if ($fmt =~ /chem/i) { return(&chemparse($value)); }
919: my ($dollarmode,$commamode,$alwaysperiod,$options);
920: if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; }
921: if ($options =~ /\$/) { $dollarmode=1; }
922: if ($options =~ /,/) { $commamode=1; }
923: if ($options =~ /\./) { $alwaysperiod=1; }
924: if ($fmt=~/s$/i) {
925: $value=&format_significant_figures($value,$fmt);
926: } elsif ($fmt) {
927: $value=sprintf('%.'.$fmt,$value);
928: }
929: if ($alwaysperiod && $fmt eq '0f') {
930: if ($target eq 'tex') {
931: $value .='\\ensuremath{.}';
932: } else {
933: $value .='.';
934: }
935: }
936: if ($value =~ /([0-9\.\-\+]+)E([0-9\-\+]+)/i ) {
937: my $frac=$1;
938: if ($dollarmode) { $frac=&dollarformat($frac); }
939: if ($commamode) { $frac=&commaformat($frac); }
940: my $exponent=$2;
941: $exponent=~s/^\+0*//;
942: $exponent=~s/^-0*/-/;
943: $exponent=~s/^-0*/-/;
944: if ($exponent eq '-') { undef($exponent); }
945: if ($exponent) {
946: if ($target eq 'web') {
947: $result=$frac.'×10<sup>'.$exponent.'</sup>';
948: } elsif ($target eq 'tex') {
949: $result='\ensuremath{'.$frac.'\times 10^{'.$exponent.'}}';
950: } else {
951: $result=$value;
952: }
953: } else {
954: $result=$frac;
955: }
956: } else {
957: $result=$value;
958: if ($dollarmode) { $result=&dollarformat($result,$target); }
959: elsif ($commamode) { $result=&commaformat($result,$target); }
960: }
961: return $result;
962: }
963:
964: sub commaformat {
965: my ($number,$target) = @_;
966: if ($number =~ /\./) {
967: while ($number =~ /([^0-9]*)([0-9]+)([^\.,][^\.,][^\.,])([,0-9]*\.[0-9]*)$/) {
968: $number = $1.$2.','.$3.$4;
969: }
970: } else {
971: while ($number =~ /^([^0-9]*)([0-9]+)([^,][^,][^,])([,0-9]*)$/) {
972: $number = $1.$2.','.$3.$4;
973: }
974: }
975: return $number;
976: }
977:
978: sub dollarformat {
979: my ($number,$target) = @_;
980: if (!$target) { $target = $external::target; }
981: $number=&commaformat($number,$target);
982: if ($target eq 'tex') {
983: $number='\$'.$number; #' stupid emacs
984: } else {
985: $number='$'.$number; #' stupid emacs
986: }
987: return $number;
988: }
989:
990: # format of form ns or nS where n is an integer
991: sub format_significant_figures {
992: my ($number,$format) = @_;
993: return '0' if ($number == 0);
994: # extract number of significant figures needed
995: my ($sig) = ($format =~ /(\d+)s/i);
996: # arbitrary choice - suggestions ?? or throw error message?
997: $sig = 3 if ($sig eq '');
998: # save the minus sign
999: my $sign = ($number < 0) ? '-' : '';
1000: $number = abs($number);
1001: # needed to correct for a number greater than 1 (or
1002: my $power = ($number < 1) ? 0 : 1;
1003: # could round up. Take the integer part of log10.
1004: my $x10 = int(log($number)/log(10));
1005: # find number with values left of decimal pt = # of sign figs.
1006: my $xsig = $number*10**($sig-$x10-$power);
1007: # get just digits left of decimal pt - also rounds off correctly
1008: my $xint = sprintf('%.0f',$xsig);
1009: # save any trailing zero's
1010: my ($zeros) = ($xint =~ /(0+)$/);
1011: # return number to original magnitude
1012: my $numSig = $xint*10**($x10-$sig+$power);
1013: # insert trailing zero's if have decimal point
1014: $numSig =~ s/^(\d+)\.(\d+)(\e?(.*)?)$/$1\.$2$zeros$3/;
1015: # put a decimal pt for number ending with 0 and length = # of sig fig
1016: $numSig.='.' if (length($numSig) == $sig && $numSig =~ /0$/);
1017: if (length($numSig) < $sig) {
1018: $numSig.='.'.substr($zeros,0,($sig-length($numSig)));
1019: }
1020: # return number with sign
1021: return $sign.$numSig;
1022:
1023: }
1024:
1025: sub map {
1026: my ($phrase,$dest,$source)=@_;
1027: my @oldseed=&random_get_seed();
1028: my @seed = &random_seed_from_phrase($phrase);
1029: &random_set_seed(@seed);
1030: my $destct = scalar(@$dest);
1031: if (!$source) {
1032: my @output;
1033: my @idx = &math_random_permuted_index($destct);
1034: my $ctr = 0;
1035: while ($ctr < $destct) {
1036: $output[$ctr] = $$dest[$idx[$ctr]];
1037: $ctr++;
1038: }
1039: &random_set_seed(@oldseed);
1040: return @output;
1041: } else {
1042: my $num = scalar(@$source);
1043: my @idx = &math_random_permuted_index($num);
1044: my $ctr = 0;
1045: my $tot = $num;
1046: $tot = $destct if $destct < $num;
1047: if (ref($$dest[0])) {
1048: while ($ctr < $tot) {
1049: ${$$dest[$ctr]} = $$source[$idx[$ctr]];
1050: $ctr++;
1051: }
1052: } else {
1053: while ($ctr < $tot) {
1054: $$dest[$ctr] = $$source[$idx[$ctr]];
1055: $ctr++;
1056: }
1057: }
1058: }
1059: &random_set_seed(@oldseed);
1060: return '';
1061: }
1062:
1063: sub rmap {
1064: my ($phrase,$dest,$source)=@_;
1065: my @oldseed=&random_get_seed();
1066: my @seed = &random_seed_from_phrase($phrase);
1067: &random_set_seed(@seed);
1068: my $destct = scalar(@$dest);
1069: if (!$source) {
1070: my @idx = &math_random_permuted_index($destct);
1071: my $ctr = 0;
1072: my @r_idx;
1073: while ($ctr < $destct) {
1074: $r_idx[$idx[$ctr]] = $ctr;
1075: $ctr++;
1076: }
1077: my @output;
1078: $ctr = 0;
1079: while ($ctr < $destct) {
1080: $output[$ctr] = $$dest[$r_idx[$ctr]];
1081: $ctr++;
1082: }
1083: &random_set_seed(@oldseed);
1084: return @output;
1085: } else {
1086: my $num = scalar(@$source);
1087: my @idx = &math_random_permuted_index($num);
1088: my $ctr = 0;
1089: my $tot = $num;
1090: $tot = $destct if $destct < $num;
1091: my @r_idx;
1092: while ($ctr < $tot) {
1093: $r_idx[$idx[$ctr]] = $ctr;
1094: $ctr++;
1095: }
1096: $ctr = 0;
1097: if (ref($$dest[0])) {
1098: while ($ctr < $tot) {
1099: ${$$dest[$ctr]} = $$source[$r_idx[$ctr]];
1100: $ctr++;
1101: }
1102: } else {
1103: while ($ctr < $tot) {
1104: $$dest[$ctr] = $$source[$r_idx[$ctr]];
1105: $ctr++;
1106: }
1107: }
1108: }
1109: &random_set_seed(@oldseed);
1110: return '';
1111: }
1112:
1113: sub capa_id { return }
1114:
1115: sub problem { return }
1116:
1117: sub name{
1118: my $fullname = &EXT('environment.lastname').', '.&EXT('environment.firstname').' '.&EXT('environment.middlename');
1119: $fullname = "" if $fullname eq ", ";
1120: $fullname =~ s/\%2d/-/g;
1121: return $fullname;
1122: }
1123:
1124: sub student_number {
1125: my $id = &EXT('environment.id');
1126: $id = '' if $id eq "";
1127: return $id;
1128: }
1129:
1130: sub class {
1131: my $course = &EXT('course.description');
1132: $course = '' if $course eq "";
1133: return $course;
1134: }
1135:
1136: sub firstname {
1137: my $firstname = &EXT('environment.firstname');
1138: $firstname = '' if $firstname eq "";
1139: return $firstname;
1140: }
1141:
1142: sub lastname {
1143: my $lastname = &EXT('environment.lastname');
1144: $lastname = '' if $lastname eq "";
1145: return $lastname;
1146: }
1147:
1148: sub sec {
1149: my $sec = &EXT('request.course.sec');
1150: $sec = '' if $sec eq "";
1151: return $sec;
1152: }
1153:
1154: sub submission {
1155: my ($partid,$responseid,$subnumber)=@_;
1156: my $sub='';
1157: if ($subnumber) { $sub=$subnumber.':'; }
1158: return &EXT('user.resource.'.$sub.'resource.'.$partid.'.'.$responseid.'.submission');
1159: }
1160:
1161: sub currentpart {
1162: return $external::part;
1163: }
1164:
1165: sub eval_time {
1166: my ($timestamp)=@_;
1167: unless ($timestamp) { return ''; }
1168: return &locallocaltime($timestamp);
1169: }
1170:
1171: sub open_date {
1172: my ($partid)=@_;
1173: unless ($partid) { $partid=0; }
1174: return &eval_time(&EXT('resource.'.$partid.'.opendate'));
1175: }
1176:
1177: sub due_date {
1178: my ($partid)=@_;
1179: unless ($partid) { $partid=0; }
1180: return &eval_time(&EXT('resource.'.$partid.'.duedate'));
1181: }
1182:
1183: sub answer_date {
1184: my ($partid)=@_;
1185: unless ($partid) { $partid=0; }
1186: return &eval_time(&EXT('resource.'.$partid.'.answerdate'));
1187: }
1188:
1189: sub open_date_epoch {
1190: my ($partid)=@_;
1191: unless ($partid) { $partid=0; }
1192: return &EXT('resource.'.$partid.'.opendate');
1193: }
1194:
1195: sub due_date_epoch {
1196: my ($partid)=@_;
1197: unless ($partid) { $partid=0; }
1198: return &EXT('resource.'.$partid.'.duedate');
1199: }
1200:
1201: sub answer_date_epoch {
1202: my ($partid)=@_;
1203: unless ($partid) { $partid=0; }
1204: return &EXT('resource.'.$partid.'.answerdate');
1205: }
1206:
1207: sub array_moments {
1208: my @input=@_;
1209: my (@output,$N);
1210: $N=scalar (@input);
1211: $output[0]=$N;
1212: if ($N <= 1) {
1213: $output[1]=$input[0];
1214: $output[1]="Input array not defined" if ($N == 0);
1215: $output[2]="variance undefined for N<=1";
1216: $output[3]="skewness undefined for N<=1";
1217: $output[4]="kurtosis undefined for N<=1";
1218: return @output;
1219: }
1220: my $sum=0;
1221: foreach my $line (@input) {
1222: $sum+=$line;
1223: }
1224: $output[1] = $sum/$N;
1225: my ($x,$sdev,$var,$skew,$kurt) = 0;
1226: foreach my $line (@input) {
1227: $x=$line-$output[1];
1228: $var+=$x**2;
1229: $skew+=$x**3;
1230: $kurt+=$x**4;
1231: }
1232: $output[2]=$var/($N-1);
1233: $sdev=CORE::sqrt($output[2]);
1234: if ($sdev == 0) {
1235: $output[3]="inf-variance=0";
1236: $output[4]="inf-variance=0";
1237: return @output;
1238: }
1239: $output[3]=$skew/($sdev**3*$N);
1240: $output[4]=$kurt/($sdev**4*$N)-3;
1241: return @output;
1242: }
1243:
1244: sub choose {
1245: my $num = $_[0];
1246: return $_[$num];
1247: }
1248:
1249: #&sum1(1,$x,sub { &sum1($_[0],2*$_[0], sub { fact($_[0])**2 })});
1250: #sub sum1 {
1251: # my ($start,$end,$sub)=@_;
1252: # my $sum=0;
1253: # for (my $i=$start;$i<=$end;$i++) {
1254: # $sum+=&$sub($i);
1255: # }
1256: # return $sum
1257: #}
1258:
1259: #&sum2('a',1,$x,'&sum2(\'b\',$a,2*$a, \'&factorial($b)**2\')');
1260: #sub sum2 {
1261: # my ($varname,$start,$end,$line)=@_;
1262: # my $sum=0;
1263: # for (my $i=$start;$i<=$end;$i++) {
1264: # my $func=sub {
1265: # eval("\$".$varname."=$i");
1266: # eval($line);
1267: # };
1268: # $sum+=&$func($i);
1269: # }
1270: # return $sum
1271: #}
1272:
1273: # expiremental idea
1274: sub proper_path {
1275: my ($path)=@_;
1276: if ( $external::target eq "tex" ) {
1277: return '/home/httpd/html'.$path;
1278: } else {
1279: return $path;
1280: }
1281: }
1282:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>