Annotation of loncom/homework/default_homework.lcpm, revision 1.117
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.117 ! albertel 4: # $Id: default_homework.lcpm,v 1.116 2006/09/29 20:55:33 albertel 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.22 ng 32: $pi=atan2(1,1)*4;
33: $rad2deg=180.0/$pi;
34: $deg2rad=$pi/180.0;
1.44 matthew 35: $"=' ';
1.116 albertel 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--;
1.117 ! albertel 61: return \@order;
1.116 albertel 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--;
1.117 ! albertel 95: return(\@order);
1.116 albertel 96: }
97:
98: sub get_permutations_left {
99: return $num_left;
100: }
101: }
1.3 albertel 102:
1.91 albertel 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:
1.117 ! albertel 129:
1.7 albertel 130: sub caparesponse_check {
1.74 albertel 131: my ($answer,$response)=@_;
1.73 albertel 132: #not properly used yet: calc
133: #not to be used: $ans_fmt
1.74 albertel 134: my $type=$LONCAPA::CAPAresponse_args{'type'};
135: my $tol=$LONCAPA::CAPAresponse_args{'tol'};
136: my $sig=$LONCAPA::CAPAresponse_args{'sig'};
1.88 albertel 137: my $ans_fmt=$LONCAPA::CAPAresponse_args{'format'};
1.74 albertel 138: my $unit=$LONCAPA::CAPAresponse_args{'unit'};
139: my $calc=$LONCAPA::CAPAresponse_args{'calc'};
140: my $samples=$LONCAPA::CAPAresponse_args{'samples'};
1.73 albertel 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
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;
1.117 ! albertel 155: #&LONCAPA_INTERNAL_DEBUG("Removed ws now :$response:");
1.73 albertel 156: }
1.116 albertel 157:
1.117 ! albertel 158: #&LONCAPA_INTERNAL_DEBUG(" type is $type ");
1.100 albertel 159: if ($type eq 'cs' || $type eq 'ci') {
1.76 albertel 160: #for string answers make surec 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;
1.100 albertel 164: } elsif ($type eq 'mc') {
165: $answer=~s/[\s,]//g;
166: $response=~s/[\s,]//g;
1.76 albertel 167: }
1.91 albertel 168: if ($type eq 'float' && $unit=~/\$/) {
1.117 ! albertel 169: if ($response!~/^\$/) { return ('NO_UNIT', undef); }
1.88 albertel 170: $response=~s/\$//g;
171: }
1.91 albertel 172: if ($type eq 'float' && $unit=~/\,/ && (&check_commas($response)<0)) {
173: return "COMMA_FAIL:";
174: }
1.88 albertel 175: $ans_fmt=~s/\W//g;
1.91 albertel 176: $unit=~s/[\$,]//g;
177: if ($type eq 'float') { $response=~s/,//g; }
1.88 albertel 178:
1.117 ! albertel 179: if (length($response) > 500) { return ('TOO_LONG',undef); }
1.73 albertel 180:
181: if ($type eq '' ) {
1.117 ! albertel 182: #&LONCAPA_INTERNAL_DEBUG("Didn't find a type :$type: defaulting");
1.73 albertel 183: if ( $answer eq ($answer *1.0)) { $type = 2;
184: } else { $type = 3; }
185: } else {
1.107 albertel 186: if ($type eq 'cs') { $type = 4; }
1.73 albertel 187: elsif ($type eq 'ci') { $type = 3 }
188: elsif ($type eq 'mc') { $type = 5; }
189: elsif ($type eq 'fml') { $type = 8; }
1.107 albertel 190: elsif ($type eq 'math') { $type = 9; }
1.73 albertel 191: elsif ($type eq 'subj') { $type = 7; }
192: elsif ($type eq 'float') { $type = 2; }
193: elsif ($type eq 'int') { $type = 1; }
1.117 ! albertel 194: else { return ('ERROR', "Unknown type of answer: $type") }
1.73 albertel 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);
1.117 ! albertel 202: #&LONCAPA_INTERNAL_DEBUG("Found :$id_list:$points: points in $samples");
1.73 albertel 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:
1.85 albertel 216: ($sig_ubound,$sig_lbound)=&LONCAPA_INTERNAL_get_sigrange($sig);
217:
1.73 albertel 218: my $reterror="";
1.107 albertel 219: my $result;
220: if ($type eq '9') {
1.108 www 221: $result = &maxima_check(&maxima_cas_formula_fix($response),&maxima_cas_formula_fix($answer),\$reterror);
1.107 albertel 222: } else {
1.109 albertel 223: if ($type eq '8') { # fml type
224: $response = &capa_formula_fix($response);
225: $answer = &capa_formula_fix($answer);
226: }
227: $result = &caparesponse_capa_check_answer($response,$answer,$type,
1.73 albertel 228: $tol_type,$tol,
229: $sig_lbound,$sig_ubound,
230: $ans_fmt,$unit,$calc,$id_list,
231: $points,$external::randomseed,
232: \$reterror);
1.107 albertel 233: }
1.73 albertel 234: if ($result == '1') { $result='EXACT_ANS'; }
235: elsif ($result == '2') { $result='APPROX_ANS'; }
236: elsif ($result == '3') { $result='SIG_FAIL'; }
237: elsif ($result == '4') { $result='UNIT_FAIL'; }
238: elsif ($result == '5') { $result='NO_UNIT'; }
239: elsif ($result == '6') { $result='UNIT_OK'; }
240: elsif ($result == '7') { $result='INCORRECT'; }
241: elsif ($result == '8') { $result='UNIT_NOTNEEDED'; }
242: elsif ($result == '9') { $result='ANS_CNT_NOT_MATCH'; }
243: elsif ($result =='10') { $result='SUB_RECORDED'; }
244: elsif ($result =='11') { $result='BAD_FORMULA'; }
1.94 albertel 245: elsif ($result =='12' && !$response) { $result='MISSING_ANSWER'; }
246: elsif ($result =='12') { $result='WANTED_NUMERIC'; }
1.77 albertel 247: elsif ($result =='13') { $result='UNIT_INVALID_INSTRUCTOR'; }
248: elsif ($result =='141') { $result='UNIT_INVALID_STUDENT'; }
249: elsif ($result =='142') { $result='UNIT_INVALID_STUDENT'; }
250: elsif ($result =='143') { $result='UNIT_INVALID_STUDENT'; }
251: elsif ($result =='15') { $result='UNIT_IRRECONCIBLE'; }
1.73 albertel 252: else {$result = "ERROR: Unknown Result:$result:$@:";}
253:
1.117 ! albertel 254: #&LONCAPA_INTERNAL_DEBUG("RetError $reterror: Answer $answer: Response $response: type-$type|$tol|$tol_type|$sig:$sig_lbound:$sig_ubound|$unit|");
! 255: #&LONCAPA_INTERNAL_DEBUG(" $answer $response $result ");
1.116 albertel 256: return ($result,$reterror)
1.37 albertel 257: }
258:
1.108 www 259: sub maxima_cas_formula_fix {
260: my ($expression)=@_;
261: return &implicit_multiplication($expression);
262: }
263:
264: sub capa_formula_fix {
265: my ($expression)=@_;
266: return &implicit_multiplication($expression);
267: }
268:
269: sub implicit_multiplication {
270: my ($expression)=@_;
1.111 www 271: # Escape scientific notation, so 3e8 does not become 3*e*8
272: # 3e8 -> 3&8; 3e-8 -> 3&-8; 3E+8 -> e&+8
1.110 www 273: $expression=~s/(\d+)e([\+\-]*\d+)/$1\&\($2\)/gsi;
1.111 www 274: # 3x10^8 -> 3&8; 3*10^-8 -> 3&-8
1.110 www 275: $expression=~s/(\d+)(?:x|\*)10(?:\^|\*\*)([\+\-]*\d+)/$1\&\($2\)/gsi;
1.111 www 276: # Fill in multiplication signs
1.114 albertel 277: # a b -> a*b;3 b -> 3*b;3 4 -> 3*4
278: $expression=~s/(\w)\s+(\w)/$1\*$2/gs;
1.115 www 279: # )( -> )*(; ) ( -> )*(
280: $expression=~s/\)\s*\(/\)\*\(/gs;
281: # 3a -> 3*a; 3( -> 3*(; 3 ( -> 3*(; 3A -> 3*A
282: $expression=~s/(\d)\s*([a-zA-Z\(])/$1\*$2/gs;
283: # a ( -> a*(
284: $expression=~s/(\w)\s+\(/$1\*\(/gs;
1.113 www 285: # a3 -> a*3;
1.110 www 286: $expression=~s/([a-zA-Z])(\d)/$1\*$2/gs;
1.115 www 287: # )a -> )*a; )3 -> )*3; ) 3 -> )*3
288: $expression=~s/\)\s*(\w)/\)\*$1/gs;
1.111 www 289: # 3&8 -> 3e8; 3&-4 -> 3e-4
1.110 www 290: $expression=~s/(\d+)\&\(([\+\-]*\d+)\)/$1e$2/gs;
1.108 www 291: return $expression;
292: }
1.73 albertel 293:
1.37 albertel 294: sub caparesponse_check_list {
1.74 albertel 295: my $response=$LONCAPA::CAPAresponse_args{'response'};
1.105 albertel 296: my $result="Got response :".join(':',@LONCAPA::CAPAresponse_answer).":\n";
297: &LONCAPA_INTERNAL_DEBUG("args ".join(':',%LONCAPA::CAPAresponse_args));
1.73 albertel 298: my @responselist;
1.74 albertel 299: my $type = $LONCAPA::CAPAresponse_args{'type'};
1.116 albertel 300: &LONCAPA_INTERNAL_DEBUG("Got type :$type:\n");
301: my $num_answers = scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}});
302: if ($type ne ''
303: && $num_answers > 1) {
1.104 albertel 304: (@responselist)=split(/,/,$response);
1.116 albertel 305: if (@responselist < $num_answers) {
1.105 albertel 306: return 'MISSING_ANSWER';
307: }
1.116 albertel 308: if (@responselist > $num_answers) {
1.105 albertel 309: return 'EXTRA_ANSWER';
310: }
1.73 albertel 311: } else {
312: (@responselist)=($response);
313: }
1.116 albertel 314: &LONCAPA_INTERNAL_DEBUG("Initial final response :$responselist['-1']:");
1.105 albertel 315: my $unit;
1.73 albertel 316: if ($type eq '' || $type eq 'float') {
317: #for numerical problems split off the unit
318: if ( $responselist['-1']=~ /(.*[^\s])\s+([^\s]+)/ ) {
319: $responselist['-1']=$1;
320: $unit=$2;
321: }
322: }
1.116 albertel 323: &LONCAPA_INTERNAL_DEBUG("Final final response :$responselist['-1']:$unit:");
1.73 albertel 324: $unit=~s/\s//;
1.105 albertel 325:
1.117 ! albertel 326: foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
! 327: if (!defined($thisanswer)) {
! 328: return ('ERROR','answer was undefined');
! 329: }
! 330: }
! 331:
! 332: if ($unit ne '') {
! 333: foreach my $response (@responselist) {
! 334: $response .= " $unit";
! 335: }
! 336: }
! 337:
! 338: my %memoized;
! 339: if ($LONCAPA::CAPAresponse_answer->{'type'} eq 'ordered') {
! 340: for (my $i=0; $i<scalar(@responselist);$i++) {
! 341: my $answer = $LONCAPA::CAPAresponse_answer->{'answers'}[$i];
! 342: my $response = $responselist[$i];
! 343: my $key = "$answer\0$response";
! 344: $memoized{$key} = [&caparesponse_check($answer, $response)];
! 345: }
! 346: } else {
! 347: foreach my $response (@responselist) {
! 348: foreach my $answer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
! 349: my $key = "$answer\0$response";
! 350: $memoized{$key} = [&caparesponse_check($answer, $response)];
! 351: }
! 352: }
! 353: }
! 354:
1.116 albertel 355: my ($final_award,$final_msg);
356: &init_permutation(scalar(@responselist),
357: $LONCAPA::CAPAresponse_answer->{'type'});
1.117 ! albertel 358:
! 359: my (@final_awards,@final_msg);
1.116 albertel 360: while( &get_permutations_left() ) {
1.117 ! albertel 361: my $order = &get_next_permutation();
1.116 albertel 362: my (@awards, @msgs, $i);
363: foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
1.117 ! albertel 364: my $key = "$thisanswer\0".$responselist[$order->[$i]];
! 365: push(@awards,$memoized{$key}[0]);
! 366: push(@msgs,$memoized{$key}[1]);
1.116 albertel 367: $i++;
368: }
369: my ($possible_award,$possible_msg) =
370: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
1.117 ! albertel 371: push(@final_awards,$possible_award);
! 372: push(@final_msg,$possible_msg);
1.73 albertel 373: }
1.117 ! albertel 374:
! 375: my ($final_award,$final_msg) =
! 376: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@final_awards,\@final_msg,undef,1);
1.116 albertel 377: return ($final_award,$final_msg);
1.7 albertel 378: }
379:
1.4 albertel 380: sub tex {
1.73 albertel 381: if ( $external::target eq "tex" ) {
382: return $_[0];
383: } else {
384: return $_[1];
385: }
1.4 albertel 386: }
387:
1.24 ng 388: sub var_in_tex {
1.73 albertel 389: if ( $external::target eq "tex" ) {
390: return $_[0];
391: } else {
392: return "";
393: }
1.24 ng 394: }
395:
1.4 albertel 396: sub web {
1.73 albertel 397: if ( $external::target eq "tex" ) {
398: return $_[1];
1.26 ng 399: } else {
1.73 albertel 400: if ( $external::target eq "web" || $external::target eq "answer") {
401: return $_[2];
402: } else {
403: return $_[0];
404: }
1.4 albertel 405: }
406: }
407:
1.24 ng 408: sub html {
1.73 albertel 409: if ( $external::target eq "web" ) {
410: return shift;
411: }
1.24 ng 412: }
413:
1.1 harris41 414: sub hinton {
1.73 albertel 415: return 0;
1.1 harris41 416: }
417:
418: sub random {
1.61 albertel 419: my ($start,$end,$step)=@_;
420: if ( ! $hidden::RANDOMINIT ) {
421: if ($external::randomseed == 0) { $external::randomseed=1; }
422: if ($external::randomseed =~/,/) {
1.84 albertel 423: my ($num1,$num2)=split(/,/,$external::randomseed);
424: &random_set_seed(1,abs($num1));
425: } elsif ($external::randomseed =~/:/) {
426: my ($num1,$num2)=split(/:/,$external::randomseed);
1.61 albertel 427: &random_set_seed(abs($num1),abs($num2));
428: } else {
429: &random_set_seed(1,int(abs($external::randomseed)));
430: }
431: &math_random_uniform();
432: $hidden::RANDOMINIT=1;
433: }
434: if (!defined($step)) { $step=1; }
435: my $num=1+int(($end-$start)/$step);
436: my $result=$start + int(&math_random_uniform() * $num)*$step;
437: return $result;
1.1 harris41 438: }
439:
1.26 ng 440: sub random_normal {
1.73 albertel 441: my ($item_cnt,$seed,$av,$std_dev) = @_;
442: my @oldseed=&random_get_seed();
443: my @retArray;
444: &random_set_seed_from_phrase($seed);
445: @retArray=&math_random_normal($item_cnt,$av,$std_dev);
446: &random_set_seed(@oldseed);
447: return @retArray;
1.26 ng 448: }
449:
450: sub random_beta {
1.73 albertel 451: my ($item_cnt,$seed,$aa,$bb) = @_;
452: my @oldseed=&random_get_seed();
453: my @retArray;
454: &random_set_seed_from_phrase($seed);
455: @retArray=&math_random_beta($item_cnt,$aa,$bb);
456: &random_set_seed(@oldseed);
457: return @retArray;
1.26 ng 458: }
459:
460: sub random_gamma {
1.73 albertel 461: my ($item_cnt,$seed,$a,$r) = @_;
462: my @oldseed=&random_get_seed();
463: my @retArray;
464: &random_set_seed_from_phrase($seed);
465: @retArray=&math_random_gamma($item_cnt,$a,$r);
466: &random_set_seed(@oldseed);
467: return @retArray;
1.26 ng 468: }
469:
470: sub random_exponential {
1.73 albertel 471: my ($item_cnt,$seed,$av) = @_;
472: my @oldseed=&random_get_seed();
473: my @retArray;
474: &random_set_seed_from_phrase($seed);
475: @retArray=&math_random_exponential($item_cnt,$av);
476: &random_set_seed(@oldseed);
477: return @retArray;
1.26 ng 478: }
479:
480: sub random_poisson {
1.73 albertel 481: my ($item_cnt,$seed,$mu) = @_;
482: my @oldseed=&random_get_seed();
483: my @retArray;
484: &random_set_seed_from_phrase($seed);
485: @retArray=&math_random_poisson($item_cnt,$mu);
486: &random_set_seed(@oldseed);
487: return @retArray;
1.26 ng 488: }
489:
490: sub random_chi {
1.73 albertel 491: my ($item_cnt,$seed,$df) = @_;
492: my @oldseed=&random_get_seed();
493: my @retArray;
494: &random_set_seed_from_phrase($seed);
495: @retArray=&math_random_chi_square($item_cnt,$df);
496: &random_set_seed(@oldseed);
497: return @retArray;
1.26 ng 498: }
499:
500: sub random_noncentral_chi {
1.73 albertel 501: my ($item_cnt,$seed,$df,$nonc) = @_;
502: my @oldseed=&random_get_seed();
503: my @retArray;
504: &random_set_seed_from_phrase($seed);
505: @retArray=&math_random_noncentral_chi_square($item_cnt,$df,$nonc);
506: &random_set_seed(@oldseed);
507: return @retArray;
1.26 ng 508: }
509:
510: sub random_f {
1.73 albertel 511: my ($item_cnt,$seed,$dfn,$dfd) = @_;
512: my @oldseed=&random_get_seed();
513: my @retArray;
514: &random_set_seed_from_phrase($seed);
515: @retArray=&math_random_f($item_cnt,$dfn,$dfd);
516: &random_set_seed(@oldseed);
517: return @retArray;
1.26 ng 518: }
519:
520: sub random_noncentral_f {
1.73 albertel 521: my ($item_cnt,$seed,$dfn,$dfd,$nonc) = @_;
522: my @oldseed=&random_get_seed();
523: my @retArray;
524: &random_set_seed_from_phrase($seed);
525: @retArray=&math_random_noncentral_f($item_cnt,$dfn,$dfd,$nonc);
526: &random_set_seed(@oldseed);
527: return @retArray;
1.26 ng 528: }
529:
530: sub random_multivariate_normal {
1.73 albertel 531: my ($item_cnt,$seed,$mean,$covar) = @_;
532: my @oldseed=&random_get_seed();
533: &random_set_seed_from_phrase($seed);
1.87 albertel 534: my @retArray=&math_random_multivariate_normal($item_cnt,@$mean,@$covar);
1.73 albertel 535: &random_set_seed(@oldseed);
536: return @retArray;
1.26 ng 537: }
538:
539: sub random_multinomial {
1.73 albertel 540: my ($item_cnt,$seed,@p) = @_;
541: my @oldseed=&random_get_seed();
542: my @retArray;
543: &random_set_seed_from_phrase($seed);
1.87 albertel 544: my @retArray=&math_random_multinomial($item_cnt,@p);
1.73 albertel 545: &random_set_seed(@oldseed);
546: return @retArray;
1.26 ng 547: }
548:
549: sub random_permutation {
1.73 albertel 550: my ($seed,@inArray) = @_;
551: my @oldseed=&random_get_seed();
552: my @retArray;
553: &random_set_seed_from_phrase($seed);
554: @retArray=&math_random_permutation(@inArray);
555: &random_set_seed(@oldseed);
556: return @retArray;
1.26 ng 557: }
558:
559: sub random_uniform {
1.73 albertel 560: my ($item_cnt,$seed,$low,$high) = @_;
561: my @oldseed=&random_get_seed();
562: my @retArray;
563: &random_set_seed_from_phrase($seed);
564: @retArray=&math_random_uniform($item_cnt,$low,$high);
565: &random_set_seed(@oldseed);
566: return @retArray;
1.26 ng 567: }
568:
569: sub random_uniform_integer {
1.73 albertel 570: my ($item_cnt,$seed,$low,$high) = @_;
571: my @oldseed=&random_get_seed();
572: my @retArray;
573: &random_set_seed_from_phrase($seed);
574: @retArray=&math_random_uniform_integer($item_cnt,$low,$high);
575: &random_set_seed(@oldseed);
576: return @retArray;
1.26 ng 577: }
578:
579: sub random_binomial {
1.73 albertel 580: my ($item_cnt,$seed,$nt,$p) = @_;
581: my @oldseed=&random_get_seed();
582: my @retArray;
583: &random_set_seed_from_phrase($seed);
584: @retArray=&math_random_binomial($item_cnt,$nt,$p);
585: &random_set_seed(@oldseed);
586: return @retArray;
1.26 ng 587: }
588:
589: sub random_negative_binomial {
1.73 albertel 590: my ($item_cnt,$seed,$ne,$p) = @_;
591: my @oldseed=&random_get_seed();
592: my @retArray;
593: &random_set_seed_from_phrase($seed);
594: @retArray=&math_random_negative_binomial($item_cnt,$ne,$p);
595: &random_set_seed(@oldseed);
596: return @retArray;
1.26 ng 597: }
598:
1.103 albertel 599: sub abs { CORE::abs(shift) }
600: sub sin { CORE::sin(shift) }
601: sub cos { CORE::cos(shift) }
602: sub exp { CORE::exp(shift) }
603: sub int { CORE::int(shift) }
604: sub log { CORE::log(shift) }
605: sub atan2 { CORE::atan2($_[0],$_[1]) }
606: sub sqrt { CORE::sqrt(shift) }
1.23 ng 607:
1.59 albertel 608: sub tan { CORE::sin($_[0]) / CORE::cos($_[0]) }
1.21 harris41 609: #sub atan { atan2($_[0], 1); }
610: #sub acos { atan2(sqrt(1 - $_[0] * $_[0]), $_[0] ); }
611: #sub asin { atan2($_[0], sqrt(1- $_[0] * $_[0]) ); }
1.22 ng 612:
1.59 albertel 613: sub log10 { CORE::log($_[0])/CORE::log(10); }
1.22 ng 614:
1.20 harris41 615: sub factorial {
1.59 albertel 616: my $input = CORE::int(shift);
1.20 harris41 617: return "Error - unable to take factorial of an negative number ($input)" if $input < 0;
618: return "Error - factorial result is greater than system limit ($input)" if $input > 170;
619: return 1 if $input == 0;
620: my $result = 1;
621: for (my $i=2; $i<=$input; $i++) { $result *= $i }
622: return $result;
623: }
624:
625: sub sgn {
626: return -1 if $_[0] < 0;
627: return 0 if $_[0] == 0;
628: return 1 if $_[0] > 0;
629: }
630:
631: sub min {
632: my @sorted = sort { $a <=> $b || $a cmp $b } @_;
633: return shift @sorted;
634: }
635:
636: sub max {
637: my @sorted = sort { $a <=> $b || $a cmp $b } @_;
638: return pop @sorted;
639: }
1.1 harris41 640:
1.20 harris41 641: sub roundto {
642: my ($input,$n) = @_;
643: return sprintf('%.'.$n.'f',$input);
644: }
645:
646: sub to_string {
647: my ($input,$n) = @_;
1.26 ng 648: return sprintf($input) if $n eq "";
649: $n = '.'.$n if $n !~ /^\./;
1.20 harris41 650: return sprintf('%'.$n,$input) if $n ne "";
651: }
652:
653: sub sub_string {
654: my ($str,$start,$len) = @_;
655: return substr($str,$start-1,$len);
656: }
1.1 harris41 657:
658: sub pow {return $_[0] ** $_[1]; }
1.59 albertel 659: sub ceil {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? (CORE::int($_[0])+ 1) : CORE::int($_[0])); }
660: sub floor {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? CORE::int($_[0]) : (CORE::int($_[0])-1)); }
1.27 ng 661: #sub floor {return int($_[0]); }
1.1 harris41 662:
1.2 albertel 663: sub format {
1.73 albertel 664: my ($value,$fmt)=@_;
1.81 albertel 665: my ($dollarmode,$commamode,$alwaysperiod,$options);
666: if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; }
667: #if ($options =~ /\$/) { $dollamode=1; }
668: #if ($options =~ /,/) { $commamode=1; }
1.82 albertel 669: if ($options =~ /\./) { $alwaysperiod=1; }
1.99 ng 670: my $result;
1.97 albertel 671: if ($fmt=~/s$/i) {
672: $result=&format_significant_figures($value,$fmt);
673: } else {
674: $fmt=~s/e/E/g;
1.99 ng 675: $result=sprintf('%.'.$fmt,$value);
1.97 albertel 676: if ($alwaysperiod && $fmt eq '0f') { $result .='.'; }
677: $result=~s/(E[+-]*)0/$1/;
678: }
1.81 albertel 679: #if ($dollarmode) {$result=&dollarformat($result);}
680: #if ($commamode) {$result=&commaformat($result);}
1.73 albertel 681: return $result;
1.46 albertel 682: }
683:
1.75 albertel 684: sub chemparse {
685: my ($reaction) = @_;
1.96 albertel 686: my @tokens = split(/(\s\+|\->|<=>|<\-|\.)/,$reaction);
1.75 albertel 687: my $formula = '';
688: foreach my $token (@tokens) {
689: if ($token eq '->' ) {
690: $formula .= '<m>\ensuremath{\rightarrow}</m> ';
691: next;
692: }
1.96 albertel 693: if ($token eq '<-' ) {
694: $formula .= '<m>\ensuremath{\leftarrow}</m> ';
695: next;
696: }
1.75 albertel 697: if ($token eq '<=>') {
698: if ($external::target eq 'web' &&
699: &EXT('request.browser.unicode')) {
1.76 albertel 700: $formula .= '⇌ ';
1.75 albertel 701: } else {
702: $formula .= &web('<=> ','<m>\ensuremath{\rightleftharpoons}</m> ',
1.95 albertel 703: '<=> ');
1.75 albertel 704: }
705: next;
706: }
1.96 albertel 707: if ($token eq '.') {
708: $formula =~ s/(\ \;| )$//;
709: $formula .= '·';
710: next;
711: }
712: $token =~ /^\s*([\d|\/]*(?:&frac\d\d)?)(.*)/;
1.90 albertel 713: $formula .= $1 if ($1 ne '1'); # stoichiometric coefficient
1.75 albertel 714:
715: my $molecule = $2;
716: # subscripts
1.78 albertel 717: $molecule =~ s|(?<=[a-zA-Z\)\]\s])(\d+)|<sub>$1</sub>|g;
1.75 albertel 718: # superscripts
719: $molecule =~ s|\^(\d*[+\-]*)|<sup>$1</sup>|g;
720: # strip whitespace
721: $molecule =~ s/\s*//g;
722: # forced space
723: $molecule =~ s/_/ /g;
1.96 albertel 724: $molecule =~ s/-/−/g;
1.75 albertel 725: $formula .= $molecule.' ';
726: }
727: # get rid of trailing space
1.87 albertel 728: $formula =~ s/(\ \;| )$//;
1.75 albertel 729: return &xmlparse($formula);
730: }
731:
1.46 albertel 732: sub prettyprint {
1.73 albertel 733: my ($value,$fmt,$target)=@_;
734: my $result;
735: if (!$target) { $target = $external::target; }
1.75 albertel 736: if ($fmt =~ /chem/i) { return(&chemparse($value)); }
1.81 albertel 737: my ($dollarmode,$commamode,$alwaysperiod,$options);
738: if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; }
1.86 albertel 739: if ($options =~ /\$/) { $dollarmode=1; }
1.81 albertel 740: if ($options =~ /,/) { $commamode=1; }
741: if ($options =~ /\./) { $alwaysperiod=1; }
1.97 albertel 742: if ($fmt=~/s$/i) {
743: $value=&format_significant_figures($value,$fmt);
744: } elsif ($fmt) {
745: $value=sprintf('%.'.$fmt,$value);
746: }
1.81 albertel 747: if ($alwaysperiod && $fmt eq '0f') {
748: if ($target eq 'tex') {
749: $value .='\\ensuremath{.}';
750: } else {
751: $value .='.';
752: }
753: }
1.73 albertel 754: if ($value =~ /([0-9\.\-\+]+)E([0-9\-\+]+)/i ) {
755: my $frac=$1;
756: if ($dollarmode) { $frac=&dollarformat($frac); }
1.80 albertel 757: if ($commamode) { $frac=&commaformat($frac); }
1.73 albertel 758: my $exponent=$2;
759: $exponent=~s/^\+0*//;
760: $exponent=~s/^-0*/-/;
761: $exponent=~s/^-0*/-/;
762: if ($exponent eq '-') { undef($exponent); }
763: if ($exponent) {
764: if ($target eq 'web') {
765: $result=$frac.'×10<sup>'.$exponent.'</sup>';
766: } elsif ($target eq 'tex') {
767: $result='\ensuremath{'.$frac.'\times 10^{'.$exponent.'}}';
768: } else {
769: $result=$value;
770: }
771: } else {
772: $result=$frac;
773: }
774: } else {
1.48 albertel 775: $result=$value;
1.86 albertel 776: if ($dollarmode) { $result=&dollarformat($result,$target); }
777: elsif ($commamode) { $result=&commaformat($result,$target); }
1.46 albertel 778: }
1.73 albertel 779: return $result;
1.48 albertel 780: }
781:
1.80 albertel 782: sub commaformat {
1.73 albertel 783: my ($number,$target) = @_;
784: if ($number =~ /\./) {
1.102 albertel 785: while ($number =~ /([^0-9]*)([0-9]+)([^\.,][^\.,][^\.,])([,0-9]*\.[0-9]*)$/) {
786: $number = $1.$2.','.$3.$4;
1.73 albertel 787: }
788: } else {
1.102 albertel 789: while ($number =~ /^([^0-9]*)([0-9]+)([^,][^,][^,])([,0-9]*)$/) {
790: $number = $1.$2.','.$3.$4;
1.73 albertel 791: }
792: }
1.80 albertel 793: return $number;
794: }
795:
796: sub dollarformat {
797: my ($number,$target) = @_;
798: if (!$target) { $target = $external::target; }
799: $number=&commaformat($number,$target);
1.73 albertel 800: if ($target eq 'tex') {
801: $number='\$'.$number; #' stupid emacs
802: } else {
803: $number='$'.$number; #' stupid emacs
804: }
805: return $number;
1.2 albertel 806: }
1.5 albertel 807:
1.97 albertel 808: # format of form ns or nS where n is an integer
809: sub format_significant_figures {
810: my ($number,$format) = @_;
811: return '0' if ($number == 0);
812: # extract number of significant figures needed
813: my ($sig) = ($format =~ /(\d+)s/i);
814: # arbitrary choice - suggestions ?? or throw error message?
815: $sig = 3 if ($sig eq '');
816: # save the minus sign
817: my $sign = ($number < 0) ? '-' : '';
818: $number = abs($number);
819: # needed to correct for a number greater than 1 (or
820: my $power = ($number < 1) ? 0 : 1;
821: # could round up. Take the integer part of log10.
822: my $x10 = int(log($number)/log(10));
823: # find number with values left of decimal pt = # of sign figs.
824: my $xsig = $number*10**($sig-$x10-$power);
825: # get just digits left of decimal pt - also rounds off correctly
826: my $xint = sprintf('%.0f',$xsig);
827: # save any trailing zero's
828: my ($zeros) = ($xint =~ /(0+)$/);
829: # return number to original magnitude
830: my $numSig = $xint*10**($x10-$sig+$power);
831: # insert trailing zero's if have decimal point
832: $numSig =~ s/^(\d+)\.(\d+)(\e?(.*)?)$/$1\.$2$zeros$3/;
1.98 albertel 833: # put a decimal pt for number ending with 0 and length = # of sig fig
834: $numSig.='.' if (length($numSig) == $sig && $numSig =~ /0$/);
835: if (length($numSig) < $sig) {
836: $numSig.='.'.substr($zeros,0,($sig-length($numSig)));
837: }
1.97 albertel 838: # return number with sign
839: return $sign.$numSig;
840:
841: }
842:
1.5 albertel 843: sub map {
1.27 ng 844: my ($phrase,$dest,$source)=@_;
1.51 albertel 845: my @oldseed=&random_get_seed();
1.27 ng 846: my @seed = &random_seed_from_phrase($phrase);
847: &random_set_seed(@seed);
848: my $destct = scalar(@$dest);
1.28 ng 849: if (!$source) {
850: my @output;
851: my @idx = &math_random_permuted_index($destct);
852: my $ctr = 0;
853: while ($ctr < $destct) {
854: $output[$ctr] = $$dest[$idx[$ctr]];
1.27 ng 855: $ctr++;
1.28 ng 856: }
1.51 albertel 857: &random_set_seed(@oldseed);
1.28 ng 858: return @output;
1.27 ng 859: } else {
1.28 ng 860: my $num = scalar(@$source);
861: my @idx = &math_random_permuted_index($num);
862: my $ctr = 0;
863: my $tot = $num;
864: $tot = $destct if $destct < $num;
865: if (ref($$dest[0])) {
866: while ($ctr < $tot) {
867: ${$$dest[$ctr]} = $$source[$idx[$ctr]];
868: $ctr++;
869: }
870: } else {
871: while ($ctr < $tot) {
872: $$dest[$ctr] = $$source[$idx[$ctr]];
873: $ctr++;
874: }
875: }
1.27 ng 876: }
1.56 albertel 877: &random_set_seed(@oldseed);
1.51 albertel 878: return '';
1.27 ng 879: }
880:
881: sub rmap {
882: my ($phrase,$dest,$source)=@_;
1.51 albertel 883: my @oldseed=&random_get_seed();
1.27 ng 884: my @seed = &random_seed_from_phrase($phrase);
885: &random_set_seed(@seed);
886: my $destct = scalar(@$dest);
1.28 ng 887: if (!$source) {
888: my @idx = &math_random_permuted_index($destct);
889: my $ctr = 0;
890: my @r_idx;
891: while ($ctr < $destct) {
892: $r_idx[$idx[$ctr]] = $ctr;
893: $ctr++;
894: }
895: my @output;
896: $ctr = 0;
897: while ($ctr < $destct) {
898: $output[$ctr] = $$dest[$r_idx[$ctr]];
1.27 ng 899: $ctr++;
1.28 ng 900: }
1.51 albertel 901: &random_set_seed(@oldseed);
1.28 ng 902: return @output;
1.27 ng 903: } else {
1.28 ng 904: my $num = scalar(@$source);
905: my @idx = &math_random_permuted_index($num);
906: my $ctr = 0;
907: my $tot = $num;
908: $tot = $destct if $destct < $num;
909: my @r_idx;
1.27 ng 910: while ($ctr < $tot) {
1.28 ng 911: $r_idx[$idx[$ctr]] = $ctr;
1.27 ng 912: $ctr++;
1.28 ng 913: }
914: $ctr = 0;
915: if (ref($$dest[0])) {
916: while ($ctr < $tot) {
917: ${$$dest[$ctr]} = $$source[$r_idx[$ctr]];
918: $ctr++;
919: }
920: } else {
921: while ($ctr < $tot) {
922: $$dest[$ctr] = $$source[$r_idx[$ctr]];
923: $ctr++;
924: }
925: }
1.6 albertel 926: }
1.51 albertel 927: &random_set_seed(@oldseed);
928: return '';
1.5 albertel 929: }
1.22 ng 930:
1.23 ng 931: sub capa_id { return }
932:
933: sub problem { return }
934:
1.22 ng 935: sub name{
1.73 albertel 936: my $fullname = &EXT('environment.lastname').', '.&EXT('environment.firstname').' '.&EXT('environment.middlename');
937: $fullname = "" if $fullname eq ", ";
938: $fullname =~ s/\%2d/-/g;
939: return $fullname;
1.22 ng 940: }
941:
942: sub student_number {
1.73 albertel 943: my $id = &EXT('environment.id');
944: $id = '' if $id eq "";
945: return $id;
1.22 ng 946: }
947:
948: sub class {
1.73 albertel 949: my $course = &EXT('course.description');
950: $course = '' if $course eq "";
951: return $course;
1.22 ng 952: }
953:
1.112 www 954: sub firstname {
955: my $firstname = &EXT('environment.firstname');
956: $firstname = '' if $firstname eq "";
957: return $firstname;
958: }
959:
960: sub lastname {
961: my $lastname = &EXT('environment.lastname');
962: $lastname = '' if $lastname eq "";
963: return $lastname;
964: }
965:
1.22 ng 966: sub sec {
1.73 albertel 967: my $sec = &EXT('request.course.sec');
968: $sec = '' if $sec eq "";
969: return $sec;
1.22 ng 970: }
971:
1.23 ng 972: sub open_date {
1.73 albertel 973: my @dc = split(/\s+/,localtime(&EXT('resource.0.opendate')));
974: return '' if ($dc[0] eq "Wed" and $dc[2] == 31 and $dc[4] == 1969);
975: my @hm = split(/:/,$dc[3]);
976: my $ampm = " am";
977: if ($hm[0] > 12) {
978: $hm[0]-=12;
979: $ampm = " pm";
980: }
981: return $dc[0].', '.$dc[1].' '.$dc[2].', '.$dc[4].' at '.$hm[0].':'.$hm[1].$ampm;
1.23 ng 982: }
983:
984: sub due_date {
1.73 albertel 985: my @dc = split(/\s+/,localtime(&EXT('resource.0.duedate')));
986: return '' if ($dc[0] eq "Wed" and $dc[2] == 31 and $dc[4] == 1969);
987: my @hm = split(/:/,$dc[3]);
988: my $ampm = " am";
989: if ($hm[0] > 12) {
990: $hm[0]-=12;
991: $ampm = " pm";
992: }
993: return $dc[0].', '.$dc[1].' '.$dc[2].', '.$dc[4].' at '.$hm[0].':'.$hm[1].$ampm;
1.23 ng 994: }
995:
996: sub answer_date {
1.73 albertel 997: my @dc = split(/\s+/,localtime(&EXT('resource.0.answerdate')));
998: return '' if ($dc[0] eq "Wed" and $dc[2] == 31 and $dc[4] == 1969);
999: my @hm = split(/:/,$dc[3]);
1000: my $ampm = " am";
1001: if ($hm[0] > 12) {
1002: $hm[0]-=12;
1003: $ampm = " pm";
1004: }
1005: return $dc[0].', '.$dc[1].' '.$dc[2].', '.$dc[4].' at '.$hm[0].':'.$hm[1].$ampm;
1.24 ng 1006: }
1007:
1008: sub array_moments {
1.73 albertel 1009: my @input=@_;
1010: my (@output,$N);
1011: $N=scalar (@input);
1012: $output[0]=$N;
1013: if ($N <= 1) {
1014: $output[1]=$input[0];
1015: $output[1]="Input array not defined" if ($N == 0);
1016: $output[2]="variance undefined for N<=1";
1017: $output[3]="skewness undefined for N<=1";
1018: $output[4]="kurtosis undefined for N<=1";
1019: return @output;
1020: }
1021: my $sum=0;
1022: foreach my $line (@input) {
1023: $sum+=$line;
1024: }
1025: $output[1] = $sum/$N;
1026: my ($x,$sdev,$var,$skew,$kurt) = 0;
1027: foreach my $line (@input) {
1028: $x=$line-$output[1];
1029: $var+=$x**2;
1030: $skew+=$x**3;
1031: $kurt+=$x**4;
1032: }
1033: $output[2]=$var/($N-1);
1034: $sdev=CORE::sqrt($output[2]);
1035: if ($sdev == 0) {
1036: $output[3]="inf-variance=0";
1037: $output[4]="inf-variance=0";
1038: return @output;
1039: }
1040: $output[3]=$skew/($sdev**3*$N);
1041: $output[4]=$kurt/($sdev**4*$N)-3;
1.24 ng 1042: return @output;
1043: }
1.5 albertel 1044:
1045: sub choose {
1.73 albertel 1046: my $num = $_[0];
1047: return $_[$num];
1.5 albertel 1048: }
1.23 ng 1049:
1.101 albertel 1050: #&sum1(1,$x,sub { &sum1($_[0],2*$_[0], sub { fact($_[0])**2 })});
1051: #sub sum1 {
1052: # my ($start,$end,$sub)=@_;
1053: # my $sum=0;
1054: # for (my $i=$start;$i<=$end;$i++) {
1055: # $sum+=&$sub($i);
1056: # }
1057: # return $sum
1058: #}
1059:
1060: #&sum2('a',1,$x,'&sum2(\'b\',$a,2*$a, \'&factorial($b)**2\')');
1061: #sub sum2 {
1062: # my ($varname,$start,$end,$line)=@_;
1063: # my $sum=0;
1064: # for (my $i=$start;$i<=$end;$i++) {
1065: # my $func=sub {
1066: # eval("\$".$varname."=$i");
1067: # eval($line);
1068: # };
1069: # $sum+=&$func($i);
1070: # }
1071: # return $sum
1072: #}
1073:
1.49 albertel 1074: # expiremental idea
1075: sub proper_path {
1.73 albertel 1076: my ($path)=@_;
1077: if ( $external::target eq "tex" ) {
1078: return '/home/httpd/html'.$path;
1079: } else {
1080: return $path;
1081: }
1.49 albertel 1082: }
1.23 ng 1083:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>