Annotation of loncom/homework/default_homework.lcpm, revision 1.177
1.42 albertel 1: # The LearningOnline Network with CAPA
1.1 harris41 2: # used by lonxml::xmlparse() as input variable $safeinit to Apache::run::run()
1.42 albertel 3: #
1.177 ! raeburn 4: # $Id: default_homework.lcpm,v 1.176 2019/04/03 21:37:11 raeburn Exp $
1.42 albertel 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: #
1.20 harris41 28: #
1.76 albertel 29:
1.25 albertel 30: #init some globals
1.38 albertel 31: $hidden::RANDOMINIT=0;
1.177 ! raeburn 32: $hidden::RANDOMINITTRYPART='';
1.22 ng 33: $pi=atan2(1,1)*4;
34: $rad2deg=180.0/$pi;
35: $deg2rad=$pi/180.0;
1.44 matthew 36: $"=' ';
1.116 albertel 37: use strict;
38: {
39: my $n = 0;
40: my $total = 0;
41: my $num_left = 0;
42: my @order;
43: my $type;
44:
45: sub init_permutation {
46: my ($size,$requested_type) = @_;
47: @order = (0..$size-1);
48: $n = $size;
49: $type = $requested_type;
50: if ($type eq 'ordered') {
51: $total = $num_left = 1;
52: } elsif ($type eq 'unordered') {
53: $total = $num_left = &factorial($size);
54: } else {
55: die("Unkown type: $type");
56: }
57: }
58:
59: sub get_next_permutation {
60: if ($num_left == $total) {
61: $num_left--;
1.117 albertel 62: return \@order;
1.116 albertel 63: }
64:
65: # Find largest index j with a[j] < a[j+1]
66:
67: my $j = scalar(@order) - 2;
68: while ($order[$j] > $order[$j+1]) {
69: $j--;
70: }
71:
72: # Find index k such that a[k] is smallest integer
73: # greater than a[j] to the right of a[j]
74:
75: my $k = scalar(@order) - 1;
76: while ($order[$j] > $order[$k]) {
77: $k--;
78: }
79:
80: # Interchange a[j] and a[k]
81:
82: @order[($k,$j)] = @order[($j,$k)];
83:
84: # Put tail end of permutation after jth position in increasing order
85:
86: my $r = scalar(@order) - 1;
87: my $s = $j + 1;
88:
89: while ($r > $s) {
90: @order[($s,$r)]=@order[($r,$s)];
91: $r--;
92: $s++;
93: }
94:
95: $num_left--;
1.117 albertel 96: return(\@order);
1.116 albertel 97: }
98:
99: sub get_permutations_left {
100: return $num_left;
101: }
102: }
1.3 albertel 103:
1.91 albertel 104: sub check_commas {
105: my ($response)=@_;
106: #print("$response ");
107: my @numbers=split(',',$response);
108: #print(" numbers ".join('-',@numbers)." ");
109: if (scalar(@numbers) > 1) {
110: #print(" numbers[0] ".$numbers[0]." ");
111: if (length($numbers[0]) > 3 || length($numbers[0]) == 0) { return -1; }
112: shift(@numbers);
113: #print(" numbers ".scalar(@numbers)." ");
114: while (scalar(@numbers) > 1) {
115: #print(" numbers ".join('-',@numbers)." ");
116: if (length($numbers[0]) != 3) { return -2; }
117: shift(@numbers);
118: }
119: my ($number)=split('\.',$numbers[0]);
120: #print(" number ".$number." ");
121: #print(" numbers[0] ".$numbers[0]." ");
122: if (length($number) != 3) { return -3; }
123: } else {
124: my ($number)=split('\.',$numbers[0]);
125: if (length($number) > 3) { return -4; }
126: }
127: return 1;
128: }
129:
1.117 albertel 130:
1.7 albertel 131: sub caparesponse_check {
1.74 albertel 132: my ($answer,$response)=@_;
1.73 albertel 133: #not properly used yet: calc
134: #not to be used: $ans_fmt
1.74 albertel 135: my $type=$LONCAPA::CAPAresponse_args{'type'};
136: my $tol=$LONCAPA::CAPAresponse_args{'tol'};
137: my $sig=$LONCAPA::CAPAresponse_args{'sig'};
1.88 albertel 138: my $ans_fmt=$LONCAPA::CAPAresponse_args{'format'};
1.74 albertel 139: my $unit=$LONCAPA::CAPAresponse_args{'unit'};
140: my $calc=$LONCAPA::CAPAresponse_args{'calc'};
141: my $samples=$LONCAPA::CAPAresponse_args{'samples'};
1.73 albertel 142:
143: my $tol_type=''; # gets it's value from whether tol has a % or not done
144: my $sig_lbound=''; #done
145: my $sig_ubound=''; #done
146:
147: #type's definitons come from capaParser.h
1.116 albertel 148:
1.73 albertel 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: }
1.116 albertel 156:
1.100 albertel 157: if ($type eq 'cs' || $type eq 'ci') {
1.130 www 158: #for string answers make sure all places spaces occur, there is
1.76 albertel 159: #really only 1 space, in both the answer and the response
160: $answer=~s/ +/ /g;
161: $response=~s/ +/ /g;
1.100 albertel 162: } elsif ($type eq 'mc') {
163: $answer=~s/[\s,]//g;
164: $response=~s/[\s,]//g;
1.76 albertel 165: }
1.91 albertel 166: if ($type eq 'float' && $unit=~/\$/) {
1.126 www 167: if ($response!~/^\$|\$$/) { return ('NO_UNIT', undef); }
1.88 albertel 168: $response=~s/\$//g;
169: }
1.91 albertel 170: if ($type eq 'float' && $unit=~/\,/ && (&check_commas($response)<0)) {
171: return "COMMA_FAIL:";
172: }
1.88 albertel 173: $ans_fmt=~s/\W//g;
1.91 albertel 174: $unit=~s/[\$,]//g;
175: if ($type eq 'float') { $response=~s/,//g; }
1.88 albertel 176:
1.117 albertel 177: if (length($response) > 500) { return ('TOO_LONG',undef); }
1.73 albertel 178:
179: if ($type eq '' ) {
180: if ( $answer eq ($answer *1.0)) { $type = 2;
181: } else { $type = 3; }
182: } else {
1.107 albertel 183: if ($type eq 'cs') { $type = 4; }
1.73 albertel 184: elsif ($type eq 'ci') { $type = 3 }
185: elsif ($type eq 'mc') { $type = 5; }
186: elsif ($type eq 'fml') { $type = 8; }
1.107 albertel 187: elsif ($type eq 'math') { $type = 9; }
1.73 albertel 188: elsif ($type eq 'subj') { $type = 7; }
189: elsif ($type eq 'float') { $type = 2; }
190: elsif ($type eq 'int') { $type = 1; }
1.117 albertel 191: else { return ('ERROR', "Unknown type of answer: $type") }
1.73 albertel 192: }
193:
194: my $points;
195: my $id_list;
196: #formula type setup the sample points
197: if ($type eq '8') {
198: ($id_list,$points)=split(/@/,$samples);
199: }
200: if ($tol eq '') {
201: $tol=0.0;
202: $tol_type=1; #TOL_ABSOLUTE
203: } else {
204: if ($tol =~ /%$/) {
205: chop $tol;
206: $tol_type=2; #TOL_PERCENTAGE
207: } else {
208: $tol_type=1; #TOL_ABSOLUTE
209: }
210: }
211:
1.85 albertel 212: ($sig_ubound,$sig_lbound)=&LONCAPA_INTERNAL_get_sigrange($sig);
213:
1.73 albertel 214: my $reterror="";
1.107 albertel 215: my $result;
1.142 raeburn 216: if (($type eq '9') || ($type eq '8')) {
217: if ($response=~/\=/) {
218: return ('BAD_FORMULA','Please submit just an expression, not an equation.');
1.143 riegler 219: } elsif ($response =~ /\,/ and $response !~ /^\s*\{.*\}\s*$/) {
1.142 raeburn 220: return ('BAD_FORMULA');
221: }
222: }
1.107 albertel 223: if ($type eq '9') {
1.108 www 224: $result = &maxima_check(&maxima_cas_formula_fix($response),&maxima_cas_formula_fix($answer),\$reterror);
1.107 albertel 225: } else {
1.109 albertel 226: if ($type eq '8') { # fml type
227: $response = &capa_formula_fix($response);
228: $answer = &capa_formula_fix($answer);
229: }
230: $result = &caparesponse_capa_check_answer($response,$answer,$type,
1.73 albertel 231: $tol_type,$tol,
232: $sig_lbound,$sig_ubound,
233: $ans_fmt,$unit,$calc,$id_list,
234: $points,$external::randomseed,
235: \$reterror);
1.107 albertel 236: }
1.73 albertel 237: if ($result == '1') { $result='EXACT_ANS'; }
238: elsif ($result == '2') { $result='APPROX_ANS'; }
239: elsif ($result == '3') { $result='SIG_FAIL'; }
240: elsif ($result == '4') { $result='UNIT_FAIL'; }
241: elsif ($result == '5') { $result='NO_UNIT'; }
242: elsif ($result == '6') { $result='UNIT_OK'; }
243: elsif ($result == '7') { $result='INCORRECT'; }
244: elsif ($result == '8') { $result='UNIT_NOTNEEDED'; }
245: elsif ($result == '9') { $result='ANS_CNT_NOT_MATCH'; }
246: elsif ($result =='10') { $result='SUB_RECORDED'; }
247: elsif ($result =='11') { $result='BAD_FORMULA'; }
1.94 albertel 248: elsif ($result =='12' && !$response) { $result='MISSING_ANSWER'; }
249: elsif ($result =='12') { $result='WANTED_NUMERIC'; }
1.77 albertel 250: elsif ($result =='13') { $result='UNIT_INVALID_INSTRUCTOR'; }
251: elsif ($result =='141') { $result='UNIT_INVALID_STUDENT'; }
252: elsif ($result =='142') { $result='UNIT_INVALID_STUDENT'; }
253: elsif ($result =='143') { $result='UNIT_INVALID_STUDENT'; }
254: elsif ($result =='15') { $result='UNIT_IRRECONCIBLE'; }
1.73 albertel 255: else {$result = "ERROR: Unknown Result:$result:$@:";}
256:
1.139 raeburn 257: return ($result,$reterror);
1.37 albertel 258: }
259:
1.73 albertel 260:
1.37 albertel 261: sub caparesponse_check_list {
1.119 albertel 262: my $responses=$LONCAPA::CAPAresponse_args{'response'};
1.105 albertel 263: &LONCAPA_INTERNAL_DEBUG("args ".join(':',%LONCAPA::CAPAresponse_args));
1.74 albertel 264: my $type = $LONCAPA::CAPAresponse_args{'type'};
1.133 www 265: my $answerunit=$LONCAPA::CAPAresponse_args{'unit'};
266: &LONCAPA_INTERNAL_DEBUG("Got type :$type: answer unit :$answerunit:\n");
1.157 www 267:
268: my $preprocess=$LONCAPA::CAPAresponse_args{'preprocess'};
269: $preprocess=~s/^\&//;
270:
1.119 albertel 271: my $num_input_lines =
272: scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}});
1.120 albertel 273:
274: if ($type ne '' ) {
1.119 albertel 275: if (scalar(@$responses) < $num_input_lines) {
1.105 albertel 276: return 'MISSING_ANSWER';
277: }
1.119 albertel 278: if (scalar(@$responses) > $num_input_lines) {
279: return 'EXTRA_ANSWER';
280: }
281:
282: }
283:
284: foreach my $which (0..($num_input_lines-1)) {
285: my $answer_size =
286: scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}[$which]});
287: if ($type ne ''
288: && $answer_size > 1) {
289: $responses->[$which]=[split(/,/,$responses->[$which])];
290: } else {
291: $responses->[$which]=[$responses->[$which]];
292: }
293: }
294: foreach my $which (0..($num_input_lines-1)) {
295: my $answer_size =
296: scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}[$which]});
297: my $response_size =
298: scalar(@{$responses->[$which]});
299: if ($answer_size > $response_size) {
300: return 'MISSING_ANSWER';
301: }
302: if ($answer_size < $response_size) {
1.105 albertel 303: return 'EXTRA_ANSWER';
304: }
1.73 albertel 305: }
1.119 albertel 306:
1.105 albertel 307: my $unit;
1.159 www 308: my ($allowalgebra)=($LONCAPA::CAPAresponse_args{'allowalgebra'}=~/^(yes|1|on)$/i);
1.140 raeburn 309: if ($type eq 'float' || $type eq '') {
1.73 albertel 310: #for numerical problems split off the unit
1.156 www 311: my $part1;
312: my $part2;
1.173 damieng 313: my $match_algebra = qr{^(.*[^\s])\s+([^\s]+)$};
314: # FIXME: with the above regexp, algebra with spaces will not be evaluated correctly
315: my $match_numerical_units = qr{^([\d\.\,\s\$]*(?:(?:[xX\*]10[\^\*]*|[eE]*)[\+\-]*\d*)*(?:^|\S)\d+)([\$\s\w\^\*\/\(\)\+\-]*[^\d\.\s\,][\$\s\w\^\*\/\(\)\+\-]*)$};
1.156 www 316: if ($allowalgebra) {
1.173 damieng 317: ($part1,$part2) = ($responses->[0][-1] =~ /$match_algebra/);
1.156 www 318: } else {
1.173 damieng 319: ($part1,$part2) = ($responses->[0][-1] =~ /$match_numerical_units/);
1.156 www 320: }
1.157 www 321: if (defined($part1) && defined($part2)) {
1.156 www 322: $responses->[0][-1]=$part1;
323: $unit=&capa_formula_fix($part2);
1.159 www 324: my $customunits=$LONCAPA::CAPAresponse_args{'customunits'};
1.161 raeburn 325: if ($customunits =~ /\S/) {
326: foreach my $replacement (split(/\s*\,\s*/,$customunits)) {
327: my ($which,$what)=split(/\s*\=\s*/,$replacement);
328: if ((defined($which)) && (defined($what))) {
329: $what=&capa_formula_fix($what);
330: $unit=~s/$which/\($what\)/g;
331: }
1.159 www 332: }
333: }
1.173 damieng 334: if (scalar(@$responses) > 0 && defined $answerunit) {
335: # there are several response values, units should be the same for all
336: $part2 =~ s/^\s+|\s+$//g;
337: for (my $i=1; $i<scalar(@$responses); $i++) {
338: my $element = $responses->[$i][-1];
339: my ($part1i, $part2i);
340: if ($allowalgebra) {
341: ($part1i, $part2i) = ($element =~ /$match_algebra/);
342: } else {
343: ($part1i, $part2i) = ($element =~ /$match_numerical_units/);
344: }
345: $part2i =~ s/^\s+|\s+$//g;
346: if (!defined $part2i) {
347: return 'NO_UNIT';
348: } elsif ($part2i ne $part2) {
349: return ('UNIT_FAIL', "$part2 $part2i");
350: } else {
351: $responses->[$i][-1] = $part1i;
352: }
353: }
354: }
1.73 albertel 355: }
356: }
357: $unit=~s/\s//;
1.149 raeburn 358: my $error;
1.133 www 359: foreach my $response (@$responses) {
1.157 www 360: foreach my $element (@$response) {
361: # See if we have preprocessor
362: if ($preprocess=~/\S/) {
363: if (defined(&$preprocess)) {
364: no strict 'refs';
1.158 www 365: $element=&$preprocess($element,$unit);
1.157 www 366: use strict 'refs';
367: }
368: }
1.138 raeburn 369: if (($type eq 'float') || (($type eq '') && ($unit ne ''))) {
370: $element =~ s/\s//g;
371: }
1.133 www 372: my $appendunit=$unit;
1.147 www 373: # Deal with percentages
374: # unit is unit entered by student, answerunit is unit by author
375: # Deprecated: divide answer by 100 if student entered percent,
376: # but author did not. Too much confusion
1.146 www 377: # if (($unit=~/\%/) && ($answerunit ne '%')) {
378: # $element=$element/100;
379: # $appendunit=~s/\%//;
380: # }
1.147 www 381: # Author entered percent, student did not
382: if (($unit!~/\%/) && ($answerunit=~/\%/)) {
383: $element=$element*100;
384: $appendunit='%'.$appendunit;
385: }
386: # Zero does not need a dimension
1.160 raeburn 387: if (($element =~ /^[0\.]+$/) && ($unit!~/\w/) && ($answerunit=~/\w/)) {
1.133 www 388: $appendunit=$answerunit;
389: }
1.156 www 390: # Do the math for the student if allowed
391: if ($allowalgebra) {
392: $element=&cas('maxima',$element);
393: }
1.148 raeburn 394: if ($appendunit ne '') {
395: $element .= " $appendunit";
396: }
1.133 www 397: &LONCAPA_INTERNAL_DEBUG("Made response element :$element:");
398: }
1.119 albertel 399: }
400:
1.117 albertel 401: foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
402: if (!defined($thisanswer)) {
403: return ('ERROR','answer was undefined');
404: }
405: }
406:
1.150 raeburn 407: my $allow_control_char = 0;
408: my $control_chars_removed = 0;
1.151 raeburn 409: my $ansstring;
1.150 raeburn 410: if ($type eq 'cs' || $type eq 'ci') {
411: if (ref($LONCAPA::CAPAresponse_answer->{'answers'}) eq 'ARRAY') {
412: foreach my $strans (@{$LONCAPA::CAPAresponse_answer->{'answers'}}) {
1.151 raeburn 413: if (ref($strans) eq 'ARRAY') {
1.152 raeburn 414: $ansstring = join("\0",@{$strans});
1.151 raeburn 415: foreach my $item (@{$strans}) {
416: if ($item =~ /[\000-\037]/) {
417: $allow_control_char = 1;
418: }
419: }
420: }
421: }
422: }
423: }
1.117 albertel 424:
1.121 albertel 425: # &LONCAPA_INTERNAL_DEBUG(&LONCAPA_INTERNAL_Dumper($responses));
1.117 albertel 426: my %memoized;
427: if ($LONCAPA::CAPAresponse_answer->{'type'} eq 'ordered') {
1.119 albertel 428: for (my $i=0; $i<scalar(@$responses);$i++) {
1.117 albertel 429: my $answer = $LONCAPA::CAPAresponse_answer->{'answers'}[$i];
1.119 albertel 430: my $response = $responses->[$i];
1.117 albertel 431: my $key = "$answer\0$response";
1.119 albertel 432: my (@awards,@msgs);
1.150 raeburn 433: for (my $j=0; $j<scalar(@$response); $j++) {
434: if ($type eq 'cs' || $type eq 'ci') {
435: unless ($allow_control_char) {
436: if ($response->[$j] =~ /[\000-\037]/) {
437: $response->[$j] =~ s/[\000-\037]//g;
438: $control_chars_removed = 1;
439: }
440: }
441: }
1.159 www 442: # See if we have preprocessor for string responses
443: if (($preprocess=~/\S/) && ($type eq 'cs' || $type eq 'ci')) {
1.158 www 444: if (defined(&$preprocess)) {
445: no strict 'refs';
446: $response->[$j]=&$preprocess($response->[$j]);
447: use strict 'refs';
448: }
449: }
450:
1.119 albertel 451: my ($award,$msg) = &caparesponse_check($answer->[$j],
452: $response->[$j]);
1.149 raeburn 453: if ($type eq 'cs' || $type eq 'ci') {
454: $error = &verify_stringresponse($type,$award,$response->[$j],
455: $answer->[$j]);
456: }
1.119 albertel 457: push(@awards,$award);
458: push(@msgs, $msg);
459: }
460: my ($award,$msg) =
461: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
462: $memoized{$key} = [$award,$msg];
1.117 albertel 463: }
464: } else {
1.119 albertel 465: #FIXME broken with unorder responses where one is a <value>
466: # and the other is a <vector> (need to delay parse til
467: # inside the loop?)
468: foreach my $response (@$responses) {
469: my $response_size = scalar(@{$response});
1.117 albertel 470: foreach my $answer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
471: my $key = "$answer\0$response";
1.119 albertel 472: my $answer_size = scalar(@{$answer});
473: my ($award,$msg);
474: if ($answer_size > $response_size) {
475: $award = 'MISSING_ANSWER';
476: } elsif ($answer_size < $response_size) {
477: $award = 'EXTRA_ANSWER';
478: } else {
479: my (@awards,@msgs);
480: for (my $j=0; $j<scalar(@$response); $j++) {
1.150 raeburn 481: if ($type eq 'cs' || $type eq 'ci') {
482: unless ($allow_control_char) {
483: if ($response->[$j] =~ /[\000-\037]/) {
484: $response->[$j] =~ s/[\000-\037]//g;
485: $control_chars_removed = 1;
486: }
487: }
488: }
1.158 www 489: # See if we have preprocessor
1.159 www 490: if (($preprocess=~/\S/) && ($type eq 'cs' || $type eq 'ci')) {
1.158 www 491: if (defined(&$preprocess)) {
492: no strict 'refs';
493: $response->[$j]=&$preprocess($response->[$j]);
494: use strict 'refs';
495: }
496: }
497:
1.119 albertel 498: my ($award,$msg) = &caparesponse_check($answer->[$j],
499: $response->[$j]);
1.149 raeburn 500: if ($type eq 'cs' || $type eq 'ci') {
501: $error = &verify_stringresponse($type,$award,$response->[$j],
502: $answer->[$j]);
503: }
1.119 albertel 504: push(@awards,$award);
505: push(@msgs, $msg);
506: }
507: ($award,$msg) =
508: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
509: }
510: $memoized{$key} = [$award,$msg];
1.117 albertel 511: }
512: }
513: }
514:
1.116 albertel 515: my ($final_award,$final_msg);
1.119 albertel 516: &init_permutation(scalar(@$responses),
1.116 albertel 517: $LONCAPA::CAPAresponse_answer->{'type'});
1.117 albertel 518:
1.118 albertel 519: # possible FIXMEs
520: # - significant time is spent calling non-safe space routine
521: # from safe space
522: # - early outs could be possible with classifying awards is to stratas
523: # and stopping as so as hitting the top strata
524: # - some early outs also might be possible with check ing the
525: # memoized hash of results (is correct even possible? etc.)
526:
1.117 albertel 527: my (@final_awards,@final_msg);
1.116 albertel 528: while( &get_permutations_left() ) {
1.117 albertel 529: my $order = &get_next_permutation();
1.116 albertel 530: my (@awards, @msgs, $i);
531: foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
1.119 albertel 532: my $key = "$thisanswer\0".$responses->[$order->[$i]];
1.117 albertel 533: push(@awards,$memoized{$key}[0]);
534: push(@msgs,$memoized{$key}[1]);
1.116 albertel 535: $i++;
1.119 albertel 536:
1.116 albertel 537: }
1.119 albertel 538: &LONCAPA_INTERNAL_DEBUG(" all awards ".join(':',@awards));
539:
1.116 albertel 540: my ($possible_award,$possible_msg) =
541: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
1.119 albertel 542: &LONCAPA_INTERNAL_DEBUG(" pos awards ".$possible_award);
1.117 albertel 543: push(@final_awards,$possible_award);
544: push(@final_msg,$possible_msg);
1.73 albertel 545: }
1.117 albertel 546:
1.119 albertel 547: &LONCAPA_INTERNAL_DEBUG(" all final_awards ".join(':',@final_awards));
1.117 albertel 548: my ($final_award,$final_msg) =
549: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@final_awards,\@final_msg,undef,1);
1.151 raeburn 550: return ($final_award,$final_msg,$error,$control_chars_removed,$ansstring);
1.149 raeburn 551: }
552:
553: sub verify_stringresponse {
554: my ($type,$award,$resp,$ans) = @_;
555: return if ($award eq 'EXACT_ANS');
556: my $error;
557: if ($resp =~ /^\s|\s$/) {
558: $resp =~ s{^\s+|\s+$}{}g;
559: }
560: if ($ans =~ /^\s|\s$/) {
561: $ans =~ s{^\s+|\s+$}{}g;
562: }
563: if ($type eq 'ci') {
564: $resp = lc($resp);
565: $ans = lc($ans);
566: }
567: if ($resp eq $ans) {
568: if ($award eq 'INCORRECT') {
569: $error = 'MISGRADED';
570: }
571: }
572: return $error;
1.7 albertel 573: }
574:
1.124 www 575: sub cas {
1.137 www 576: my ($system,$input,$library)=@_;
1.124 www 577: my $output;
1.145 www 578: my $dump;
1.124 www 579: if ($system eq 'maxima') {
1.137 www 580: $output=&maxima_eval($input,$library);
1.144 www 581: } elsif ($system eq 'R') {
1.145 www 582: ($output,$dump)=&r_eval($input,$library,0);
1.137 www 583: } else {
584: $output='Error: unrecognized CAS';
1.124 www 585: }
586: return $output;
587: }
588:
1.145 www 589: sub cas_hashref {
590: my ($system,$input,$library)=@_;
591: if ($system eq 'maxima') {
592: return 'Error: unsupported CAS';
593: } elsif ($system eq 'R') {
594: return &r_eval($input,$library,1);
595: } else {
596: return 'Error: unrecognized CAS';
597: }
598: }
599:
600: #
601: # cas_hashref_entry takes a list of indices and gets the entry in a hash generated by Rreturn.
602: # Call: cas_hashref_entry(Rvalue, index1, index2, ...) where Rvalue is a hash returned by Rreturn.
603: # Rentry will return the first scalar value it encounters (ignoring excess indices).
604: # If an invalid key is given, it returns undef.
605: #
606: sub cas_hashref_entry {
607: return &Rentry(@_);
608: }
609:
610: #
611: # cas_hashref_array takes a list of indices and gets a column array from a hash generated by Rreturn.
612: # Call: cas_hashref_array(Rvalue, index1, index2, ...) where Rvalue is a hash returned by Rreturn.
613: # If an invalid key is given, it returns undef.
614: #
615: sub cas_hashref_array {
616: return &Rarray(@_);
617: }
618:
1.4 albertel 619: sub tex {
1.73 albertel 620: if ( $external::target eq "tex" ) {
621: return $_[0];
622: } else {
623: return $_[1];
624: }
1.4 albertel 625: }
626:
1.24 ng 627: sub var_in_tex {
1.73 albertel 628: if ( $external::target eq "tex" ) {
629: return $_[0];
630: } else {
631: return "";
632: }
1.24 ng 633: }
634:
1.4 albertel 635: sub web {
1.73 albertel 636: if ( $external::target eq "tex" ) {
637: return $_[1];
1.26 ng 638: } else {
1.73 albertel 639: if ( $external::target eq "web" || $external::target eq "answer") {
640: return $_[2];
641: } else {
642: return $_[0];
643: }
1.4 albertel 644: }
645: }
646:
1.24 ng 647: sub html {
1.73 albertel 648: if ( $external::target eq "web" ) {
649: return shift;
650: }
1.24 ng 651: }
652:
1.1 harris41 653: sub hinton {
1.73 albertel 654: return 0;
1.1 harris41 655: }
656:
657: sub random {
1.61 albertel 658: my ($start,$end,$step)=@_;
1.177 ! raeburn 659: if (( ! $hidden::RANDOMINIT ) ||
! 660: (($external::randomizetrypart ne '') &&
! 661: ($hidden::RANDOMINITTRYPART ne $external::randomizetrypart))) {
1.176 raeburn 662: if ($external::randomseed == 0) { $external::randomseed=1; }
663: if ($external::randomseed =~/,/) {
664: my ($num1,$num2) = map { abs($_); } split(/,/,$external::randomseed);
665: if ((!$num1) || ($num1 > 2147483398)) {
666: &random_set_seed_from_phrase($external::randomseed);
667: } else {
668: &random_set_seed(1,$num1);
669: }
670: } elsif ($external::randomseed =~/:/) {
671: my ($num1,$num2) = map { abs($_); } split(/:/,$external::randomseed);
672: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
673: &random_set_seed_from_phrase($external::randomseed);
674: } else {
675: &random_set_seed($num1,$num2);
676: }
677: } else {
678: my $num1 = int(abs($external::randomseed));
679: if ((!$num1) || ($num1 > 2147483398)) {
680: &random_set_seed_from_phrase($external::randomseed);
681: } else {
682: &random_set_seed(1,$num1);
683: }
684: }
1.61 albertel 685: &math_random_uniform();
686: $hidden::RANDOMINIT=1;
1.177 ! raeburn 687: $hidden::RANDOMINITTRYPART=$external::randomizetrypart;
1.61 albertel 688: }
689: if (!defined($step)) { $step=1; }
690: my $num=1+int(($end-$start)/$step);
691: my $result=$start + int(&math_random_uniform() * $num)*$step;
692: return $result;
1.1 harris41 693: }
694:
1.26 ng 695: sub random_normal {
1.73 albertel 696: my ($item_cnt,$seed,$av,$std_dev) = @_;
697: my @oldseed=&random_get_seed();
698: my @retArray;
699: &random_set_seed_from_phrase($seed);
700: @retArray=&math_random_normal($item_cnt,$av,$std_dev);
701: &random_set_seed(@oldseed);
702: return @retArray;
1.26 ng 703: }
704:
705: sub random_beta {
1.73 albertel 706: my ($item_cnt,$seed,$aa,$bb) = @_;
707: my @oldseed=&random_get_seed();
708: my @retArray;
709: &random_set_seed_from_phrase($seed);
710: @retArray=&math_random_beta($item_cnt,$aa,$bb);
711: &random_set_seed(@oldseed);
712: return @retArray;
1.26 ng 713: }
714:
715: sub random_gamma {
1.73 albertel 716: my ($item_cnt,$seed,$a,$r) = @_;
717: my @oldseed=&random_get_seed();
718: my @retArray;
719: &random_set_seed_from_phrase($seed);
720: @retArray=&math_random_gamma($item_cnt,$a,$r);
721: &random_set_seed(@oldseed);
722: return @retArray;
1.26 ng 723: }
724:
725: sub random_exponential {
1.73 albertel 726: my ($item_cnt,$seed,$av) = @_;
727: my @oldseed=&random_get_seed();
728: my @retArray;
729: &random_set_seed_from_phrase($seed);
730: @retArray=&math_random_exponential($item_cnt,$av);
731: &random_set_seed(@oldseed);
732: return @retArray;
1.26 ng 733: }
734:
735: sub random_poisson {
1.73 albertel 736: my ($item_cnt,$seed,$mu) = @_;
737: my @oldseed=&random_get_seed();
738: my @retArray;
739: &random_set_seed_from_phrase($seed);
740: @retArray=&math_random_poisson($item_cnt,$mu);
741: &random_set_seed(@oldseed);
742: return @retArray;
1.26 ng 743: }
744:
745: sub random_chi {
1.73 albertel 746: my ($item_cnt,$seed,$df) = @_;
747: my @oldseed=&random_get_seed();
748: my @retArray;
749: &random_set_seed_from_phrase($seed);
750: @retArray=&math_random_chi_square($item_cnt,$df);
751: &random_set_seed(@oldseed);
752: return @retArray;
1.26 ng 753: }
754:
755: sub random_noncentral_chi {
1.73 albertel 756: my ($item_cnt,$seed,$df,$nonc) = @_;
757: my @oldseed=&random_get_seed();
758: my @retArray;
759: &random_set_seed_from_phrase($seed);
760: @retArray=&math_random_noncentral_chi_square($item_cnt,$df,$nonc);
761: &random_set_seed(@oldseed);
762: return @retArray;
1.26 ng 763: }
764:
765: sub random_f {
1.73 albertel 766: my ($item_cnt,$seed,$dfn,$dfd) = @_;
767: my @oldseed=&random_get_seed();
768: my @retArray;
769: &random_set_seed_from_phrase($seed);
770: @retArray=&math_random_f($item_cnt,$dfn,$dfd);
771: &random_set_seed(@oldseed);
772: return @retArray;
1.26 ng 773: }
774:
775: sub random_noncentral_f {
1.73 albertel 776: my ($item_cnt,$seed,$dfn,$dfd,$nonc) = @_;
777: my @oldseed=&random_get_seed();
778: my @retArray;
779: &random_set_seed_from_phrase($seed);
780: @retArray=&math_random_noncentral_f($item_cnt,$dfn,$dfd,$nonc);
781: &random_set_seed(@oldseed);
782: return @retArray;
1.26 ng 783: }
784:
785: sub random_multivariate_normal {
1.73 albertel 786: my ($item_cnt,$seed,$mean,$covar) = @_;
787: my @oldseed=&random_get_seed();
788: &random_set_seed_from_phrase($seed);
1.87 albertel 789: my @retArray=&math_random_multivariate_normal($item_cnt,@$mean,@$covar);
1.73 albertel 790: &random_set_seed(@oldseed);
791: return @retArray;
1.26 ng 792: }
793:
794: sub random_multinomial {
1.73 albertel 795: my ($item_cnt,$seed,@p) = @_;
796: my @oldseed=&random_get_seed();
797: my @retArray;
798: &random_set_seed_from_phrase($seed);
1.87 albertel 799: my @retArray=&math_random_multinomial($item_cnt,@p);
1.73 albertel 800: &random_set_seed(@oldseed);
801: return @retArray;
1.26 ng 802: }
803:
804: sub random_permutation {
1.73 albertel 805: my ($seed,@inArray) = @_;
806: my @oldseed=&random_get_seed();
807: my @retArray;
808: &random_set_seed_from_phrase($seed);
809: @retArray=&math_random_permutation(@inArray);
810: &random_set_seed(@oldseed);
811: return @retArray;
1.26 ng 812: }
813:
814: sub random_uniform {
1.73 albertel 815: my ($item_cnt,$seed,$low,$high) = @_;
816: my @oldseed=&random_get_seed();
817: my @retArray;
818: &random_set_seed_from_phrase($seed);
819: @retArray=&math_random_uniform($item_cnt,$low,$high);
820: &random_set_seed(@oldseed);
821: return @retArray;
1.26 ng 822: }
823:
824: sub random_uniform_integer {
1.73 albertel 825: my ($item_cnt,$seed,$low,$high) = @_;
826: my @oldseed=&random_get_seed();
827: my @retArray;
828: &random_set_seed_from_phrase($seed);
829: @retArray=&math_random_uniform_integer($item_cnt,$low,$high);
830: &random_set_seed(@oldseed);
831: return @retArray;
1.26 ng 832: }
833:
834: sub random_binomial {
1.73 albertel 835: my ($item_cnt,$seed,$nt,$p) = @_;
836: my @oldseed=&random_get_seed();
837: my @retArray;
838: &random_set_seed_from_phrase($seed);
839: @retArray=&math_random_binomial($item_cnt,$nt,$p);
840: &random_set_seed(@oldseed);
841: return @retArray;
1.26 ng 842: }
843:
844: sub random_negative_binomial {
1.73 albertel 845: my ($item_cnt,$seed,$ne,$p) = @_;
846: my @oldseed=&random_get_seed();
847: my @retArray;
848: &random_set_seed_from_phrase($seed);
849: @retArray=&math_random_negative_binomial($item_cnt,$ne,$p);
850: &random_set_seed(@oldseed);
851: return @retArray;
1.26 ng 852: }
853:
1.103 albertel 854: sub abs { CORE::abs(shift) }
855: sub sin { CORE::sin(shift) }
856: sub cos { CORE::cos(shift) }
857: sub exp { CORE::exp(shift) }
858: sub int { CORE::int(shift) }
859: sub log { CORE::log(shift) }
1.162 raeburn 860: sub ln { CORE::log(shift) }
1.103 albertel 861: sub atan2 { CORE::atan2($_[0],$_[1]) }
862: sub sqrt { CORE::sqrt(shift) }
1.23 ng 863:
1.59 albertel 864: sub tan { CORE::sin($_[0]) / CORE::cos($_[0]) }
1.21 harris41 865: #sub atan { atan2($_[0], 1); }
866: #sub acos { atan2(sqrt(1 - $_[0] * $_[0]), $_[0] ); }
867: #sub asin { atan2($_[0], sqrt(1- $_[0] * $_[0]) ); }
1.22 ng 868:
1.59 albertel 869: sub log10 { CORE::log($_[0])/CORE::log(10); }
1.22 ng 870:
1.20 harris41 871: sub factorial {
1.59 albertel 872: my $input = CORE::int(shift);
1.20 harris41 873: return "Error - unable to take factorial of an negative number ($input)" if $input < 0;
874: return "Error - factorial result is greater than system limit ($input)" if $input > 170;
875: return 1 if $input == 0;
876: my $result = 1;
877: for (my $i=2; $i<=$input; $i++) { $result *= $i }
878: return $result;
879: }
880:
881: sub sgn {
882: return -1 if $_[0] < 0;
883: return 0 if $_[0] == 0;
884: return 1 if $_[0] > 0;
885: }
886:
887: sub min {
888: my @sorted = sort { $a <=> $b || $a cmp $b } @_;
889: return shift @sorted;
890: }
891:
892: sub max {
893: my @sorted = sort { $a <=> $b || $a cmp $b } @_;
894: return pop @sorted;
895: }
1.1 harris41 896:
1.20 harris41 897: sub roundto {
898: my ($input,$n) = @_;
899: return sprintf('%.'.$n.'f',$input);
900: }
901:
902: sub to_string {
903: my ($input,$n) = @_;
1.26 ng 904: return sprintf($input) if $n eq "";
905: $n = '.'.$n if $n !~ /^\./;
1.20 harris41 906: return sprintf('%'.$n,$input) if $n ne "";
907: }
908:
909: sub sub_string {
910: my ($str,$start,$len) = @_;
911: return substr($str,$start-1,$len);
912: }
1.1 harris41 913:
914: sub pow {return $_[0] ** $_[1]; }
1.59 albertel 915: sub ceil {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? (CORE::int($_[0])+ 1) : CORE::int($_[0])); }
916: sub floor {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? CORE::int($_[0]) : (CORE::int($_[0])-1)); }
1.27 ng 917: #sub floor {return int($_[0]); }
1.1 harris41 918:
1.2 albertel 919: sub format {
1.73 albertel 920: my ($value,$fmt)=@_;
1.81 albertel 921: my ($dollarmode,$commamode,$alwaysperiod,$options);
922: if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; }
923: #if ($options =~ /\$/) { $dollamode=1; }
924: #if ($options =~ /,/) { $commamode=1; }
1.82 albertel 925: if ($options =~ /\./) { $alwaysperiod=1; }
1.99 ng 926: my $result;
1.97 albertel 927: if ($fmt=~/s$/i) {
928: $result=&format_significant_figures($value,$fmt);
929: } else {
930: $fmt=~s/e/E/g;
1.99 ng 931: $result=sprintf('%.'.$fmt,$value);
1.97 albertel 932: if ($alwaysperiod && $fmt eq '0f') { $result .='.'; }
933: $result=~s/(E[+-]*)0/$1/;
934: }
1.81 albertel 935: #if ($dollarmode) {$result=&dollarformat($result);}
936: #if ($commamode) {$result=&commaformat($result);}
1.73 albertel 937: return $result;
1.46 albertel 938: }
939:
1.75 albertel 940: sub chemparse {
941: my ($reaction) = @_;
1.96 albertel 942: my @tokens = split(/(\s\+|\->|<=>|<\-|\.)/,$reaction);
1.75 albertel 943: my $formula = '';
944: foreach my $token (@tokens) {
945: if ($token eq '->' ) {
1.172 damieng 946: if ($external::target eq 'web') {
947: $formula .= '→ ';
948: } else {
949: $formula .= '<m>\ensuremath{\rightarrow}</m> ';
950: }
1.75 albertel 951: next;
952: }
1.96 albertel 953: if ($token eq '<-' ) {
1.172 damieng 954: if ($external::target eq 'web') {
955: $formula .= '← ';
956: } else {
957: $formula .= '<m>\ensuremath{\leftarrow}</m> ';
958: }
1.96 albertel 959: next;
960: }
1.75 albertel 961: if ($token eq '<=>') {
962: if ($external::target eq 'web' &&
963: &EXT('request.browser.unicode')) {
1.76 albertel 964: $formula .= '⇌ ';
1.75 albertel 965: } else {
966: $formula .= &web('<=> ','<m>\ensuremath{\rightleftharpoons}</m> ',
1.95 albertel 967: '<=> ');
1.75 albertel 968: }
969: next;
970: }
1.96 albertel 971: if ($token eq '.') {
972: $formula =~ s/(\ \;| )$//;
973: $formula .= '·';
974: next;
975: }
976: $token =~ /^\s*([\d|\/]*(?:&frac\d\d)?)(.*)/;
1.90 albertel 977: $formula .= $1 if ($1 ne '1'); # stoichiometric coefficient
1.75 albertel 978:
979: my $molecule = $2;
980: # subscripts
1.78 albertel 981: $molecule =~ s|(?<=[a-zA-Z\)\]\s])(\d+)|<sub>$1</sub>|g;
1.75 albertel 982: # superscripts
983: $molecule =~ s|\^(\d*[+\-]*)|<sup>$1</sup>|g;
984: # strip whitespace
985: $molecule =~ s/\s*//g;
986: # forced space
987: $molecule =~ s/_/ /g;
1.96 albertel 988: $molecule =~ s/-/−/g;
1.75 albertel 989: $formula .= $molecule.' ';
990: }
991: # get rid of trailing space
1.87 albertel 992: $formula =~ s/(\ \;| )$//;
1.75 albertel 993: return &xmlparse($formula);
994: }
995:
1.175 raeburn 996: sub conv_eng_format {
1.174 raeburn 997: my ($ans,$baseunit)=@_;
998: my ($value,$answer,$unit);
999: $baseunit =~ s{[^\w/\-\.]}{}g;
1000: eval {
1001: $value = &number_format_pref($ans);
1002: };
1003: my ($answer,$prefix) = ($value=~ /^(.+)(\w)$/);
1004: my $unit = $prefix.$baseunit;
1005: return($answer,$unit);
1006: }
1007:
1.46 albertel 1008: sub prettyprint {
1.73 albertel 1009: my ($value,$fmt,$target)=@_;
1010: my $result;
1011: if (!$target) { $target = $external::target; }
1.75 albertel 1012: if ($fmt =~ /chem/i) { return(&chemparse($value)); }
1.81 albertel 1013: my ($dollarmode,$commamode,$alwaysperiod,$options);
1014: if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; }
1.86 albertel 1015: if ($options =~ /\$/) { $dollarmode=1; }
1.81 albertel 1016: if ($options =~ /,/) { $commamode=1; }
1017: if ($options =~ /\./) { $alwaysperiod=1; }
1.97 albertel 1018: if ($fmt=~/s$/i) {
1019: $value=&format_significant_figures($value,$fmt);
1020: } elsif ($fmt) {
1021: $value=sprintf('%.'.$fmt,$value);
1022: }
1.81 albertel 1023: if ($alwaysperiod && $fmt eq '0f') {
1024: if ($target eq 'tex') {
1025: $value .='\\ensuremath{.}';
1026: } else {
1027: $value .='.';
1028: }
1029: }
1.73 albertel 1030: if ($value =~ /([0-9\.\-\+]+)E([0-9\-\+]+)/i ) {
1031: my $frac=$1;
1032: if ($dollarmode) { $frac=&dollarformat($frac); }
1.80 albertel 1033: if ($commamode) { $frac=&commaformat($frac); }
1.73 albertel 1034: my $exponent=$2;
1035: $exponent=~s/^\+0*//;
1036: $exponent=~s/^-0*/-/;
1037: $exponent=~s/^-0*/-/;
1038: if ($exponent eq '-') { undef($exponent); }
1039: if ($exponent) {
1040: if ($target eq 'web') {
1041: $result=$frac.'×10<sup>'.$exponent.'</sup>';
1042: } elsif ($target eq 'tex') {
1043: $result='\ensuremath{'.$frac.'\times 10^{'.$exponent.'}}';
1044: } else {
1045: $result=$value;
1046: }
1047: } else {
1048: $result=$frac;
1049: }
1050: } else {
1.48 albertel 1051: $result=$value;
1.86 albertel 1052: if ($dollarmode) { $result=&dollarformat($result,$target); }
1053: elsif ($commamode) { $result=&commaformat($result,$target); }
1.46 albertel 1054: }
1.73 albertel 1055: return $result;
1.48 albertel 1056: }
1057:
1.80 albertel 1058: sub commaformat {
1.73 albertel 1059: my ($number,$target) = @_;
1060: if ($number =~ /\./) {
1.102 albertel 1061: while ($number =~ /([^0-9]*)([0-9]+)([^\.,][^\.,][^\.,])([,0-9]*\.[0-9]*)$/) {
1062: $number = $1.$2.','.$3.$4;
1.73 albertel 1063: }
1064: } else {
1.102 albertel 1065: while ($number =~ /^([^0-9]*)([0-9]+)([^,][^,][^,])([,0-9]*)$/) {
1066: $number = $1.$2.','.$3.$4;
1.73 albertel 1067: }
1068: }
1.80 albertel 1069: return $number;
1070: }
1071:
1072: sub dollarformat {
1073: my ($number,$target) = @_;
1074: if (!$target) { $target = $external::target; }
1075: $number=&commaformat($number,$target);
1.73 albertel 1076: if ($target eq 'tex') {
1077: $number='\$'.$number; #' stupid emacs
1078: } else {
1079: $number='$'.$number; #' stupid emacs
1080: }
1081: return $number;
1.2 albertel 1082: }
1.5 albertel 1083:
1.97 albertel 1084: # format of form ns or nS where n is an integer
1085: sub format_significant_figures {
1086: my ($number,$format) = @_;
1087: return '0' if ($number == 0);
1088: # extract number of significant figures needed
1089: my ($sig) = ($format =~ /(\d+)s/i);
1090: # arbitrary choice - suggestions ?? or throw error message?
1091: $sig = 3 if ($sig eq '');
1092: # save the minus sign
1093: my $sign = ($number < 0) ? '-' : '';
1094: $number = abs($number);
1095: # needed to correct for a number greater than 1 (or
1096: my $power = ($number < 1) ? 0 : 1;
1097: # could round up. Take the integer part of log10.
1098: my $x10 = int(log($number)/log(10));
1099: # find number with values left of decimal pt = # of sign figs.
1100: my $xsig = $number*10**($sig-$x10-$power);
1101: # get just digits left of decimal pt - also rounds off correctly
1102: my $xint = sprintf('%.0f',$xsig);
1103: # save any trailing zero's
1104: my ($zeros) = ($xint =~ /(0+)$/);
1105: # return number to original magnitude
1106: my $numSig = $xint*10**($x10-$sig+$power);
1.165 raeburn 1107: if ($numSig =~ /^(\d+)\.(\d+)/) {
1108: # insert trailing zero's if have decimal point
1.166 raeburn 1109: my @digarray = split('',$1.$2);
1110: my $sigcount;
1111: while (@digarray > 0) {
1112: my $item = shift(@digarray);
1113: if ($item) {
1114: $sigcount = 1 + @digarray;
1115: last;
1116: }
1117: }
1118: if (($sigcount) && ($sig >= $sigcount)) {
1119: $zeros = substr($zeros,0,($sig - $sigcount));
1120: }
1.165 raeburn 1121: $numSig =~ s/^(\d+)\.(\d+)(\e?(.*)?)$/$1\.$2$zeros$3/;
1122: } else {
1.167 raeburn 1123: if ($numSig =~ /^(\d+)e([\+\-]\d+)$/i) {
1124: my $pre_exp = $1;
1125: my $exponent = $2;
1126: $numSig = $pre_exp.'.'.$zeros.'E'.$exponent;
1127: } elsif ($numSig =~ /0$/) {
1.165 raeburn 1128: # add decimal pt for number ending with 0 and length == # of sig figs
1129: if (length($numSig) == $sig) {
1130: $numSig.='.';
1131: } elsif (length($numSig) > $sig) {
1132: # exponential form for number ending with 0 and length > # of sig figs
1133: my $fmtsig = $sig-1;
1134: if ($fmtsig) {
1.167 raeburn 1135: $numSig = sprintf('%.'.$fmtsig.'E',$numSig);
1.165 raeburn 1136: }
1.167 raeburn 1137: } elsif (length($numSig) < $sig) {
1138: $numSig.='.'.substr($zeros,0,($sig-length($numSig)));
1139: }
1140: } else {
1141: if (length($numSig) < $sig) {
1142: $numSig.='.'.substr($zeros,0,($sig-length($numSig)));
1.165 raeburn 1143: }
1144: }
1.98 albertel 1145: }
1.97 albertel 1146: # return number with sign
1147: return $sign.$numSig;
1148: }
1149:
1.5 albertel 1150: sub map {
1.27 ng 1151: my ($phrase,$dest,$source)=@_;
1.51 albertel 1152: my @oldseed=&random_get_seed();
1.27 ng 1153: my @seed = &random_seed_from_phrase($phrase);
1154: &random_set_seed(@seed);
1155: my $destct = scalar(@$dest);
1.28 ng 1156: if (!$source) {
1157: my @output;
1158: my @idx = &math_random_permuted_index($destct);
1159: my $ctr = 0;
1160: while ($ctr < $destct) {
1161: $output[$ctr] = $$dest[$idx[$ctr]];
1.27 ng 1162: $ctr++;
1.28 ng 1163: }
1.51 albertel 1164: &random_set_seed(@oldseed);
1.28 ng 1165: return @output;
1.27 ng 1166: } else {
1.28 ng 1167: my $num = scalar(@$source);
1168: my @idx = &math_random_permuted_index($num);
1169: my $ctr = 0;
1170: my $tot = $num;
1171: $tot = $destct if $destct < $num;
1172: if (ref($$dest[0])) {
1173: while ($ctr < $tot) {
1174: ${$$dest[$ctr]} = $$source[$idx[$ctr]];
1175: $ctr++;
1176: }
1177: } else {
1178: while ($ctr < $tot) {
1179: $$dest[$ctr] = $$source[$idx[$ctr]];
1180: $ctr++;
1181: }
1182: }
1.27 ng 1183: }
1.56 albertel 1184: &random_set_seed(@oldseed);
1.51 albertel 1185: return '';
1.27 ng 1186: }
1187:
1188: sub rmap {
1189: my ($phrase,$dest,$source)=@_;
1.51 albertel 1190: my @oldseed=&random_get_seed();
1.27 ng 1191: my @seed = &random_seed_from_phrase($phrase);
1192: &random_set_seed(@seed);
1193: my $destct = scalar(@$dest);
1.28 ng 1194: if (!$source) {
1195: my @idx = &math_random_permuted_index($destct);
1196: my $ctr = 0;
1197: my @r_idx;
1198: while ($ctr < $destct) {
1199: $r_idx[$idx[$ctr]] = $ctr;
1200: $ctr++;
1201: }
1202: my @output;
1203: $ctr = 0;
1204: while ($ctr < $destct) {
1205: $output[$ctr] = $$dest[$r_idx[$ctr]];
1.27 ng 1206: $ctr++;
1.28 ng 1207: }
1.51 albertel 1208: &random_set_seed(@oldseed);
1.28 ng 1209: return @output;
1.27 ng 1210: } else {
1.28 ng 1211: my $num = scalar(@$source);
1212: my @idx = &math_random_permuted_index($num);
1213: my $ctr = 0;
1214: my $tot = $num;
1215: $tot = $destct if $destct < $num;
1216: my @r_idx;
1.27 ng 1217: while ($ctr < $tot) {
1.28 ng 1218: $r_idx[$idx[$ctr]] = $ctr;
1.27 ng 1219: $ctr++;
1.28 ng 1220: }
1221: $ctr = 0;
1222: if (ref($$dest[0])) {
1223: while ($ctr < $tot) {
1224: ${$$dest[$ctr]} = $$source[$r_idx[$ctr]];
1225: $ctr++;
1226: }
1227: } else {
1228: while ($ctr < $tot) {
1229: $$dest[$ctr] = $$source[$r_idx[$ctr]];
1230: $ctr++;
1231: }
1232: }
1.6 albertel 1233: }
1.51 albertel 1234: &random_set_seed(@oldseed);
1235: return '';
1.5 albertel 1236: }
1.22 ng 1237:
1.23 ng 1238: sub capa_id { return }
1239:
1240: sub problem { return }
1241:
1.22 ng 1242: sub name{
1.73 albertel 1243: my $fullname = &EXT('environment.lastname').', '.&EXT('environment.firstname').' '.&EXT('environment.middlename');
1244: $fullname = "" if $fullname eq ", ";
1245: $fullname =~ s/\%2d/-/g;
1246: return $fullname;
1.22 ng 1247: }
1248:
1249: sub student_number {
1.73 albertel 1250: my $id = &EXT('environment.id');
1251: $id = '' if $id eq "";
1252: return $id;
1.22 ng 1253: }
1254:
1255: sub class {
1.73 albertel 1256: my $course = &EXT('course.description');
1257: $course = '' if $course eq "";
1258: return $course;
1.22 ng 1259: }
1260:
1.153 www 1261: sub classid {
1262: my $courseid = &EXT('request.course.id');
1263: $courseid = '' if $courseid eq "";
1264: return $courseid;
1265: }
1266:
1.112 www 1267: sub firstname {
1268: my $firstname = &EXT('environment.firstname');
1269: $firstname = '' if $firstname eq "";
1270: return $firstname;
1271: }
1.153 www 1272:
1273: sub middlename {
1274: my $middlename = &EXT('environment.middlename');
1275: $middlename = '' if $middlename eq "";
1276: return $middlename;
1277: }
1278:
1.112 www 1279: sub lastname {
1280: my $lastname = &EXT('environment.lastname');
1281: $lastname = '' if $lastname eq "";
1282: return $lastname;
1283: }
1284:
1.22 ng 1285: sub sec {
1.73 albertel 1286: my $sec = &EXT('request.course.sec');
1287: $sec = '' if $sec eq "";
1288: return $sec;
1.22 ng 1289: }
1290:
1.136 www 1291: sub submission {
1.170 raeburn 1292: my ($partid,$responseid,$subnumber,$encode,$cleanupnum,$mapalias)=@_;
1.136 www 1293: my $sub='';
1294: if ($subnumber) { $sub=$subnumber.':'; }
1.164 bisitz 1295: my $output =
1.170 raeburn 1296: &EXT('user.resource.'.$sub.'resource.'.$partid.'.'.$responseid.'.submission',$mapalias);
1.168 raeburn 1297: if (ref($output) eq 'ARRAY') {
1298: my @items = @{$output};
1299: if ($encode) {
1300: @items = map { &encode_response($_); } @items;
1301: }
1.169 raeburn 1302: if (ref($cleanupnum) eq 'HASH') {
1303: @items = map { &cleanup_numerical_response($cleanupnum,$_); } @items;
1304: }
1.168 raeburn 1305: return \@items;
1306: } else {
1307: if ($encode) {
1308: $output = &encode_response($output);
1309: }
1.169 raeburn 1310: if (ref($cleanupnum) eq 'HASH') {
1311: $output = &cleanup_numerical_response($cleanupnum,$output);
1312: }
1.168 raeburn 1313: return $output;
1.165 raeburn 1314: }
1.168 raeburn 1315: }
1316:
1317: sub encode_response {
1318: my ($value) = @_;
1319: $value =~ s/&/&/g;
1320: $value =~ s/</</g;
1321: $value =~ s/>/>/g;
1322: $value =~ s/"/"/g;
1323: return $value;
1.136 www 1324: }
1325:
1.169 raeburn 1326: sub cleanup_numerical_response {
1327: my ($cleanupnum,$value) = @_;
1328: if (ref($cleanupnum) eq 'HASH') {
1329: if ($cleanupnum->{exponent}) {
1330: if ($value =~ m{^(.*)[\*xX]\s*10\s*\^\s*(\+|\-)?\s*(\d+)(.*)$}) {
1331: my $pre_exp = $1;
1332: my $sign = $2;
1333: my $exponent = $3;
1334: my $post_exp = $4;
1335: if ($pre_exp !~ /\./) {
1336: $pre_exp .= '.';
1337: }
1338: if ($sign eq '') {
1339: $sign = '+';
1340: }
1341: $value = $pre_exp.'E'.$sign.$exponent.$post_exp;
1342: }
1343: }
1344: if ($cleanupnum->{comma}) {
1345: $value =~ s{(\d+),(\d+)}{$1$2};
1346: }
1347: if ($cleanupnum->{letterforzero}) {
1348: $value =~ s/^\s*o(\.\d+)/0$1/i;
1349: }
1350: if ($cleanupnum->{spaces}) {
1351: $value =~ s{^\s+|\s+$}{}g;
1352: if ($value =~ m{^(.*)\.\s+(\d+)(.*)$}) {
1353: my $pre_pt = $1;
1354: my $decimal = $2;
1355: my $post_dec = $3;
1356: $value = $pre_pt.'.'.$decimal.$post_dec;
1357: }
1358: }
1359: if ($cleanupnum->{format} =~ /^\d+s$/i) {
1360: $value = &format_significant_figures($value,$cleanupnum->{format});
1361: }
1362: }
1363: return $value;
1364: }
1365:
1.136 www 1366: sub currentpart {
1367: return $external::part;
1368: }
1369:
1.135 www 1370: sub eval_time {
1371: my ($timestamp)=@_;
1372: unless ($timestamp) { return ''; }
1373: return &locallocaltime($timestamp);
1374: }
1375:
1.23 ng 1376: sub open_date {
1.134 www 1377: my ($partid)=@_;
1378: unless ($partid) { $partid=0; }
1.135 www 1379: return &eval_time(&EXT('resource.'.$partid.'.opendate'));
1.23 ng 1380: }
1381:
1.134 www 1382: sub due_date {
1383: my ($partid)=@_;
1384: unless ($partid) { $partid=0; }
1.135 www 1385: return &eval_time(&EXT('resource.'.$partid.'.duedate'));
1.23 ng 1386: }
1387:
1388: sub answer_date {
1.134 www 1389: my ($partid)=@_;
1390: unless ($partid) { $partid=0; }
1.135 www 1391: return &eval_time(&EXT('resource.'.$partid.'.answerdate'));
1.24 ng 1392: }
1393:
1.136 www 1394: sub open_date_epoch {
1395: my ($partid)=@_;
1396: unless ($partid) { $partid=0; }
1397: return &EXT('resource.'.$partid.'.opendate');
1398: }
1399:
1400: sub due_date_epoch {
1401: my ($partid)=@_;
1402: unless ($partid) { $partid=0; }
1403: return &EXT('resource.'.$partid.'.duedate');
1404: }
1405:
1406: sub answer_date_epoch {
1407: my ($partid)=@_;
1408: unless ($partid) { $partid=0; }
1409: return &EXT('resource.'.$partid.'.answerdate');
1410: }
1411:
1.154 www 1412: sub parameter_setting {
1413: my ($which,$partid)=@_;
1414: unless ($partid) { $partid=0; }
1415: return &EXT('resource.'.$partid.'.'.$which);
1416: }
1417:
1418: sub stored_data {
1419: my ($which,$partid)=@_;
1420: unless ($partid) { $partid=0; }
1421: return &EXT('user.resource.resource.'.$partid.'.'.$which);
1422: }
1423:
1.155 www 1424: sub wrong_bubbles {
1425: my ($correct,$lower,$upper,$step,@given)=@_;
1426: my @array=();
1427: my %hash=();
1428: foreach my $new (@given) {
1429: $hash{$new}=1;
1430: }
1431: my $num=int(¶meter_setting('numbubbles',¤tpart()));
1432: unless ($num) { $num=8; }
1433: if ($num>1) {
1434: for (my $i=0;$i<=500;$i++) {
1435: my $new=&random($lower,$upper,$step);
1436: if ($hash{$new}) { next; }
1437: if (abs($new-$correct)<$step) { next; }
1438: $hash{$new}=1;
1439: @array=keys(%hash);
1440: if ($#array+2>=$num) { last; }
1441: }
1442: }
1443: return @array;
1444: }
1445:
1.24 ng 1446: sub array_moments {
1.73 albertel 1447: my @input=@_;
1448: my (@output,$N);
1449: $N=scalar (@input);
1450: $output[0]=$N;
1451: if ($N <= 1) {
1452: $output[1]=$input[0];
1453: $output[1]="Input array not defined" if ($N == 0);
1454: $output[2]="variance undefined for N<=1";
1455: $output[3]="skewness undefined for N<=1";
1456: $output[4]="kurtosis undefined for N<=1";
1457: return @output;
1458: }
1459: my $sum=0;
1460: foreach my $line (@input) {
1461: $sum+=$line;
1462: }
1463: $output[1] = $sum/$N;
1464: my ($x,$sdev,$var,$skew,$kurt) = 0;
1465: foreach my $line (@input) {
1466: $x=$line-$output[1];
1467: $var+=$x**2;
1468: $skew+=$x**3;
1469: $kurt+=$x**4;
1470: }
1471: $output[2]=$var/($N-1);
1472: $sdev=CORE::sqrt($output[2]);
1473: if ($sdev == 0) {
1474: $output[3]="inf-variance=0";
1475: $output[4]="inf-variance=0";
1476: return @output;
1477: }
1478: $output[3]=$skew/($sdev**3*$N);
1479: $output[4]=$kurt/($sdev**4*$N)-3;
1.24 ng 1480: return @output;
1481: }
1.5 albertel 1482:
1483: sub choose {
1.73 albertel 1484: my $num = $_[0];
1485: return $_[$num];
1.5 albertel 1486: }
1.23 ng 1487:
1.101 albertel 1488: #&sum1(1,$x,sub { &sum1($_[0],2*$_[0], sub { fact($_[0])**2 })});
1489: #sub sum1 {
1490: # my ($start,$end,$sub)=@_;
1491: # my $sum=0;
1492: # for (my $i=$start;$i<=$end;$i++) {
1493: # $sum+=&$sub($i);
1494: # }
1495: # return $sum
1496: #}
1497:
1498: #&sum2('a',1,$x,'&sum2(\'b\',$a,2*$a, \'&factorial($b)**2\')');
1499: #sub sum2 {
1500: # my ($varname,$start,$end,$line)=@_;
1501: # my $sum=0;
1502: # for (my $i=$start;$i<=$end;$i++) {
1503: # my $func=sub {
1504: # eval("\$".$varname."=$i");
1505: # eval($line);
1506: # };
1507: # $sum+=&$func($i);
1508: # }
1509: # return $sum
1510: #}
1511:
1.49 albertel 1512: # expiremental idea
1513: sub proper_path {
1.73 albertel 1514: my ($path)=@_;
1515: if ( $external::target eq "tex" ) {
1516: return '/home/httpd/html'.$path;
1517: } else {
1518: return $path;
1519: }
1.49 albertel 1520: }
1.23 ng 1521:
1.171 damieng 1522: sub input_id {
1523: my ($part_id, $response_id, $textline_id) = @_;
1524: return 'HWVAL_'.$part_id.'_'.$response_id.'_'.$textline_id;
1525: }
1526:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>