Annotation of loncom/homework/default_homework.lcpm, revision 1.124
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.124 ! www 4: # $Id: default_homework.lcpm,v 1.123 2006/12/15 22:11:43 www 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.119 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.119 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.119 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.119 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.73 albertel 259:
1.37 albertel 260: sub caparesponse_check_list {
1.119 albertel 261: my $responses=$LONCAPA::CAPAresponse_args{'response'};
1.121 albertel 262: # &LONCAPA_INTERNAL_DEBUG(" answer is ".
263: # &LONCAPA_INTERNAL_Dumper($LONCAPA::CAPAresponse_answer).":\n");
264: # &LONCAPA_INTERNAL_DEBUG(" respons is ".
265: # &LONCAPA_INTERNAL_Dumper($responses).":\n");
1.105 albertel 266: &LONCAPA_INTERNAL_DEBUG("args ".join(':',%LONCAPA::CAPAresponse_args));
1.74 albertel 267: my $type = $LONCAPA::CAPAresponse_args{'type'};
1.116 albertel 268: &LONCAPA_INTERNAL_DEBUG("Got type :$type:\n");
1.119 albertel 269:
270: my $num_input_lines =
271: scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}});
1.120 albertel 272:
273: if ($type ne '' ) {
1.119 albertel 274: if (scalar(@$responses) < $num_input_lines) {
1.105 albertel 275: return 'MISSING_ANSWER';
276: }
1.119 albertel 277: if (scalar(@$responses) > $num_input_lines) {
278: return 'EXTRA_ANSWER';
279: }
280:
281: }
282:
283: foreach my $which (0..($num_input_lines-1)) {
284: my $answer_size =
285: scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}[$which]});
286: if ($type ne ''
287: && $answer_size > 1) {
288: $responses->[$which]=[split(/,/,$responses->[$which])];
289: } else {
290: $responses->[$which]=[$responses->[$which]];
291: }
292: }
1.121 albertel 293: # &LONCAPA_INTERNAL_DEBUG(" parsed response is ".
294: # &LONCAPA_INTERNAL_Dumper($responses).":\n");
1.119 albertel 295: foreach my $which (0..($num_input_lines-1)) {
296: my $answer_size =
297: scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}[$which]});
298: my $response_size =
299: scalar(@{$responses->[$which]});
300: if ($answer_size > $response_size) {
301: return 'MISSING_ANSWER';
302: }
303: if ($answer_size < $response_size) {
1.105 albertel 304: return 'EXTRA_ANSWER';
305: }
1.73 albertel 306: }
1.119 albertel 307:
308: &LONCAPA_INTERNAL_DEBUG("Initial final response :$responses->[0][-1]:");
1.105 albertel 309: my $unit;
1.73 albertel 310: if ($type eq '' || $type eq 'float') {
311: #for numerical problems split off the unit
1.119 albertel 312: if ( $responses->[0][-1]=~ /(.*[^\s])\s+([^\s]+)/ ) {
313: $responses->[0][-1]=$1;
1.73 albertel 314: $unit=$2;
315: }
316: }
1.119 albertel 317: &LONCAPA_INTERNAL_DEBUG("Final final response :$responses->[0][-1]:$unit:");
1.73 albertel 318: $unit=~s/\s//;
1.119 albertel 319: if ($unit ne '') {
320: foreach my $response (@$responses) {
321: foreach my $element (@$response) {
322: $element .= " $unit";
323: }
324: }
325: }
326:
1.117 albertel 327: foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
328: if (!defined($thisanswer)) {
329: return ('ERROR','answer was undefined');
330: }
331: }
332:
333:
1.121 albertel 334: # &LONCAPA_INTERNAL_DEBUG(&LONCAPA_INTERNAL_Dumper($responses));
1.117 albertel 335: my %memoized;
336: if ($LONCAPA::CAPAresponse_answer->{'type'} eq 'ordered') {
1.119 albertel 337: for (my $i=0; $i<scalar(@$responses);$i++) {
1.117 albertel 338: my $answer = $LONCAPA::CAPAresponse_answer->{'answers'}[$i];
1.119 albertel 339: my $response = $responses->[$i];
1.117 albertel 340: my $key = "$answer\0$response";
1.119 albertel 341: my (@awards,@msgs);
342: for (my $j=0; $j<scalar(@$response); $j++) {
343: my ($award,$msg) = &caparesponse_check($answer->[$j],
344: $response->[$j]);
345: push(@awards,$award);
346: push(@msgs, $msg);
347: }
348: my ($award,$msg) =
349: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
350: $memoized{$key} = [$award,$msg];
1.117 albertel 351: }
352: } else {
1.119 albertel 353: #FIXME broken with unorder responses where one is a <value>
354: # and the other is a <vector> (need to delay parse til
355: # inside the loop?)
356: foreach my $response (@$responses) {
357: my $response_size = scalar(@{$response});
1.117 albertel 358: foreach my $answer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
359: my $key = "$answer\0$response";
1.119 albertel 360: my $answer_size = scalar(@{$answer});
361: my ($award,$msg);
362: if ($answer_size > $response_size) {
363: $award = 'MISSING_ANSWER';
364: } elsif ($answer_size < $response_size) {
365: $award = 'EXTRA_ANSWER';
366: } else {
367: my (@awards,@msgs);
368: for (my $j=0; $j<scalar(@$response); $j++) {
369: my ($award,$msg) = &caparesponse_check($answer->[$j],
370: $response->[$j]);
371: push(@awards,$award);
372: push(@msgs, $msg);
373: }
374: ($award,$msg) =
375: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
376: }
377: $memoized{$key} = [$award,$msg];
1.117 albertel 378: }
379: }
380: }
381:
1.116 albertel 382: my ($final_award,$final_msg);
1.119 albertel 383: &init_permutation(scalar(@$responses),
1.116 albertel 384: $LONCAPA::CAPAresponse_answer->{'type'});
1.117 albertel 385:
1.118 albertel 386: # possible FIXMEs
387: # - significant time is spent calling non-safe space routine
388: # from safe space
389: # - early outs could be possible with classifying awards is to stratas
390: # and stopping as so as hitting the top strata
391: # - some early outs also might be possible with check ing the
392: # memoized hash of results (is correct even possible? etc.)
393:
1.117 albertel 394: my (@final_awards,@final_msg);
1.116 albertel 395: while( &get_permutations_left() ) {
1.117 albertel 396: my $order = &get_next_permutation();
1.116 albertel 397: my (@awards, @msgs, $i);
398: foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
1.119 albertel 399: my $key = "$thisanswer\0".$responses->[$order->[$i]];
1.117 albertel 400: push(@awards,$memoized{$key}[0]);
401: push(@msgs,$memoized{$key}[1]);
1.116 albertel 402: $i++;
1.119 albertel 403:
1.116 albertel 404: }
1.119 albertel 405: &LONCAPA_INTERNAL_DEBUG(" all awards ".join(':',@awards));
406:
1.116 albertel 407: my ($possible_award,$possible_msg) =
408: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
1.119 albertel 409: &LONCAPA_INTERNAL_DEBUG(" pos awards ".$possible_award);
1.117 albertel 410: push(@final_awards,$possible_award);
411: push(@final_msg,$possible_msg);
1.73 albertel 412: }
1.117 albertel 413:
1.119 albertel 414: &LONCAPA_INTERNAL_DEBUG(" all final_awards ".join(':',@final_awards));
1.117 albertel 415: my ($final_award,$final_msg) =
416: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@final_awards,\@final_msg,undef,1);
1.116 albertel 417: return ($final_award,$final_msg);
1.7 albertel 418: }
419:
1.124 ! www 420: sub cas {
! 421: my ($system,$input)=@_;
! 422: my $output;
! 423: if ($system eq 'maxima') {
! 424: $output=&maxima_eval($input);
! 425: }
! 426: return $output;
! 427: }
! 428:
1.4 albertel 429: sub tex {
1.73 albertel 430: if ( $external::target eq "tex" ) {
431: return $_[0];
432: } else {
433: return $_[1];
434: }
1.4 albertel 435: }
436:
1.24 ng 437: sub var_in_tex {
1.73 albertel 438: if ( $external::target eq "tex" ) {
439: return $_[0];
440: } else {
441: return "";
442: }
1.24 ng 443: }
444:
1.4 albertel 445: sub web {
1.73 albertel 446: if ( $external::target eq "tex" ) {
447: return $_[1];
1.26 ng 448: } else {
1.73 albertel 449: if ( $external::target eq "web" || $external::target eq "answer") {
450: return $_[2];
451: } else {
452: return $_[0];
453: }
1.4 albertel 454: }
455: }
456:
1.24 ng 457: sub html {
1.73 albertel 458: if ( $external::target eq "web" ) {
459: return shift;
460: }
1.24 ng 461: }
462:
1.1 harris41 463: sub hinton {
1.73 albertel 464: return 0;
1.1 harris41 465: }
466:
467: sub random {
1.61 albertel 468: my ($start,$end,$step)=@_;
469: if ( ! $hidden::RANDOMINIT ) {
470: if ($external::randomseed == 0) { $external::randomseed=1; }
471: if ($external::randomseed =~/,/) {
1.84 albertel 472: my ($num1,$num2)=split(/,/,$external::randomseed);
473: &random_set_seed(1,abs($num1));
474: } elsif ($external::randomseed =~/:/) {
475: my ($num1,$num2)=split(/:/,$external::randomseed);
1.61 albertel 476: &random_set_seed(abs($num1),abs($num2));
477: } else {
478: &random_set_seed(1,int(abs($external::randomseed)));
479: }
480: &math_random_uniform();
481: $hidden::RANDOMINIT=1;
482: }
483: if (!defined($step)) { $step=1; }
484: my $num=1+int(($end-$start)/$step);
485: my $result=$start + int(&math_random_uniform() * $num)*$step;
486: return $result;
1.1 harris41 487: }
488:
1.26 ng 489: sub random_normal {
1.73 albertel 490: my ($item_cnt,$seed,$av,$std_dev) = @_;
491: my @oldseed=&random_get_seed();
492: my @retArray;
493: &random_set_seed_from_phrase($seed);
494: @retArray=&math_random_normal($item_cnt,$av,$std_dev);
495: &random_set_seed(@oldseed);
496: return @retArray;
1.26 ng 497: }
498:
499: sub random_beta {
1.73 albertel 500: my ($item_cnt,$seed,$aa,$bb) = @_;
501: my @oldseed=&random_get_seed();
502: my @retArray;
503: &random_set_seed_from_phrase($seed);
504: @retArray=&math_random_beta($item_cnt,$aa,$bb);
505: &random_set_seed(@oldseed);
506: return @retArray;
1.26 ng 507: }
508:
509: sub random_gamma {
1.73 albertel 510: my ($item_cnt,$seed,$a,$r) = @_;
511: my @oldseed=&random_get_seed();
512: my @retArray;
513: &random_set_seed_from_phrase($seed);
514: @retArray=&math_random_gamma($item_cnt,$a,$r);
515: &random_set_seed(@oldseed);
516: return @retArray;
1.26 ng 517: }
518:
519: sub random_exponential {
1.73 albertel 520: my ($item_cnt,$seed,$av) = @_;
521: my @oldseed=&random_get_seed();
522: my @retArray;
523: &random_set_seed_from_phrase($seed);
524: @retArray=&math_random_exponential($item_cnt,$av);
525: &random_set_seed(@oldseed);
526: return @retArray;
1.26 ng 527: }
528:
529: sub random_poisson {
1.73 albertel 530: my ($item_cnt,$seed,$mu) = @_;
531: my @oldseed=&random_get_seed();
532: my @retArray;
533: &random_set_seed_from_phrase($seed);
534: @retArray=&math_random_poisson($item_cnt,$mu);
535: &random_set_seed(@oldseed);
536: return @retArray;
1.26 ng 537: }
538:
539: sub random_chi {
1.73 albertel 540: my ($item_cnt,$seed,$df) = @_;
541: my @oldseed=&random_get_seed();
542: my @retArray;
543: &random_set_seed_from_phrase($seed);
544: @retArray=&math_random_chi_square($item_cnt,$df);
545: &random_set_seed(@oldseed);
546: return @retArray;
1.26 ng 547: }
548:
549: sub random_noncentral_chi {
1.73 albertel 550: my ($item_cnt,$seed,$df,$nonc) = @_;
551: my @oldseed=&random_get_seed();
552: my @retArray;
553: &random_set_seed_from_phrase($seed);
554: @retArray=&math_random_noncentral_chi_square($item_cnt,$df,$nonc);
555: &random_set_seed(@oldseed);
556: return @retArray;
1.26 ng 557: }
558:
559: sub random_f {
1.73 albertel 560: my ($item_cnt,$seed,$dfn,$dfd) = @_;
561: my @oldseed=&random_get_seed();
562: my @retArray;
563: &random_set_seed_from_phrase($seed);
564: @retArray=&math_random_f($item_cnt,$dfn,$dfd);
565: &random_set_seed(@oldseed);
566: return @retArray;
1.26 ng 567: }
568:
569: sub random_noncentral_f {
1.73 albertel 570: my ($item_cnt,$seed,$dfn,$dfd,$nonc) = @_;
571: my @oldseed=&random_get_seed();
572: my @retArray;
573: &random_set_seed_from_phrase($seed);
574: @retArray=&math_random_noncentral_f($item_cnt,$dfn,$dfd,$nonc);
575: &random_set_seed(@oldseed);
576: return @retArray;
1.26 ng 577: }
578:
579: sub random_multivariate_normal {
1.73 albertel 580: my ($item_cnt,$seed,$mean,$covar) = @_;
581: my @oldseed=&random_get_seed();
582: &random_set_seed_from_phrase($seed);
1.87 albertel 583: my @retArray=&math_random_multivariate_normal($item_cnt,@$mean,@$covar);
1.73 albertel 584: &random_set_seed(@oldseed);
585: return @retArray;
1.26 ng 586: }
587:
588: sub random_multinomial {
1.73 albertel 589: my ($item_cnt,$seed,@p) = @_;
590: my @oldseed=&random_get_seed();
591: my @retArray;
592: &random_set_seed_from_phrase($seed);
1.87 albertel 593: my @retArray=&math_random_multinomial($item_cnt,@p);
1.73 albertel 594: &random_set_seed(@oldseed);
595: return @retArray;
1.26 ng 596: }
597:
598: sub random_permutation {
1.73 albertel 599: my ($seed,@inArray) = @_;
600: my @oldseed=&random_get_seed();
601: my @retArray;
602: &random_set_seed_from_phrase($seed);
603: @retArray=&math_random_permutation(@inArray);
604: &random_set_seed(@oldseed);
605: return @retArray;
1.26 ng 606: }
607:
608: sub random_uniform {
1.73 albertel 609: my ($item_cnt,$seed,$low,$high) = @_;
610: my @oldseed=&random_get_seed();
611: my @retArray;
612: &random_set_seed_from_phrase($seed);
613: @retArray=&math_random_uniform($item_cnt,$low,$high);
614: &random_set_seed(@oldseed);
615: return @retArray;
1.26 ng 616: }
617:
618: sub random_uniform_integer {
1.73 albertel 619: my ($item_cnt,$seed,$low,$high) = @_;
620: my @oldseed=&random_get_seed();
621: my @retArray;
622: &random_set_seed_from_phrase($seed);
623: @retArray=&math_random_uniform_integer($item_cnt,$low,$high);
624: &random_set_seed(@oldseed);
625: return @retArray;
1.26 ng 626: }
627:
628: sub random_binomial {
1.73 albertel 629: my ($item_cnt,$seed,$nt,$p) = @_;
630: my @oldseed=&random_get_seed();
631: my @retArray;
632: &random_set_seed_from_phrase($seed);
633: @retArray=&math_random_binomial($item_cnt,$nt,$p);
634: &random_set_seed(@oldseed);
635: return @retArray;
1.26 ng 636: }
637:
638: sub random_negative_binomial {
1.73 albertel 639: my ($item_cnt,$seed,$ne,$p) = @_;
640: my @oldseed=&random_get_seed();
641: my @retArray;
642: &random_set_seed_from_phrase($seed);
643: @retArray=&math_random_negative_binomial($item_cnt,$ne,$p);
644: &random_set_seed(@oldseed);
645: return @retArray;
1.26 ng 646: }
647:
1.103 albertel 648: sub abs { CORE::abs(shift) }
649: sub sin { CORE::sin(shift) }
650: sub cos { CORE::cos(shift) }
651: sub exp { CORE::exp(shift) }
652: sub int { CORE::int(shift) }
653: sub log { CORE::log(shift) }
654: sub atan2 { CORE::atan2($_[0],$_[1]) }
655: sub sqrt { CORE::sqrt(shift) }
1.23 ng 656:
1.59 albertel 657: sub tan { CORE::sin($_[0]) / CORE::cos($_[0]) }
1.21 harris41 658: #sub atan { atan2($_[0], 1); }
659: #sub acos { atan2(sqrt(1 - $_[0] * $_[0]), $_[0] ); }
660: #sub asin { atan2($_[0], sqrt(1- $_[0] * $_[0]) ); }
1.22 ng 661:
1.59 albertel 662: sub log10 { CORE::log($_[0])/CORE::log(10); }
1.22 ng 663:
1.20 harris41 664: sub factorial {
1.59 albertel 665: my $input = CORE::int(shift);
1.20 harris41 666: return "Error - unable to take factorial of an negative number ($input)" if $input < 0;
667: return "Error - factorial result is greater than system limit ($input)" if $input > 170;
668: return 1 if $input == 0;
669: my $result = 1;
670: for (my $i=2; $i<=$input; $i++) { $result *= $i }
671: return $result;
672: }
673:
674: sub sgn {
675: return -1 if $_[0] < 0;
676: return 0 if $_[0] == 0;
677: return 1 if $_[0] > 0;
678: }
679:
680: sub min {
681: my @sorted = sort { $a <=> $b || $a cmp $b } @_;
682: return shift @sorted;
683: }
684:
685: sub max {
686: my @sorted = sort { $a <=> $b || $a cmp $b } @_;
687: return pop @sorted;
688: }
1.1 harris41 689:
1.20 harris41 690: sub roundto {
691: my ($input,$n) = @_;
692: return sprintf('%.'.$n.'f',$input);
693: }
694:
695: sub to_string {
696: my ($input,$n) = @_;
1.26 ng 697: return sprintf($input) if $n eq "";
698: $n = '.'.$n if $n !~ /^\./;
1.20 harris41 699: return sprintf('%'.$n,$input) if $n ne "";
700: }
701:
702: sub sub_string {
703: my ($str,$start,$len) = @_;
704: return substr($str,$start-1,$len);
705: }
1.1 harris41 706:
707: sub pow {return $_[0] ** $_[1]; }
1.59 albertel 708: sub ceil {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? (CORE::int($_[0])+ 1) : CORE::int($_[0])); }
709: sub floor {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? CORE::int($_[0]) : (CORE::int($_[0])-1)); }
1.27 ng 710: #sub floor {return int($_[0]); }
1.1 harris41 711:
1.2 albertel 712: sub format {
1.73 albertel 713: my ($value,$fmt)=@_;
1.81 albertel 714: my ($dollarmode,$commamode,$alwaysperiod,$options);
715: if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; }
716: #if ($options =~ /\$/) { $dollamode=1; }
717: #if ($options =~ /,/) { $commamode=1; }
1.82 albertel 718: if ($options =~ /\./) { $alwaysperiod=1; }
1.99 ng 719: my $result;
1.97 albertel 720: if ($fmt=~/s$/i) {
721: $result=&format_significant_figures($value,$fmt);
722: } else {
723: $fmt=~s/e/E/g;
1.99 ng 724: $result=sprintf('%.'.$fmt,$value);
1.97 albertel 725: if ($alwaysperiod && $fmt eq '0f') { $result .='.'; }
726: $result=~s/(E[+-]*)0/$1/;
727: }
1.81 albertel 728: #if ($dollarmode) {$result=&dollarformat($result);}
729: #if ($commamode) {$result=&commaformat($result);}
1.73 albertel 730: return $result;
1.46 albertel 731: }
732:
1.75 albertel 733: sub chemparse {
734: my ($reaction) = @_;
1.96 albertel 735: my @tokens = split(/(\s\+|\->|<=>|<\-|\.)/,$reaction);
1.75 albertel 736: my $formula = '';
737: foreach my $token (@tokens) {
738: if ($token eq '->' ) {
739: $formula .= '<m>\ensuremath{\rightarrow}</m> ';
740: next;
741: }
1.96 albertel 742: if ($token eq '<-' ) {
743: $formula .= '<m>\ensuremath{\leftarrow}</m> ';
744: next;
745: }
1.75 albertel 746: if ($token eq '<=>') {
747: if ($external::target eq 'web' &&
748: &EXT('request.browser.unicode')) {
1.76 albertel 749: $formula .= '⇌ ';
1.75 albertel 750: } else {
751: $formula .= &web('<=> ','<m>\ensuremath{\rightleftharpoons}</m> ',
1.95 albertel 752: '<=> ');
1.75 albertel 753: }
754: next;
755: }
1.96 albertel 756: if ($token eq '.') {
757: $formula =~ s/(\ \;| )$//;
758: $formula .= '·';
759: next;
760: }
761: $token =~ /^\s*([\d|\/]*(?:&frac\d\d)?)(.*)/;
1.90 albertel 762: $formula .= $1 if ($1 ne '1'); # stoichiometric coefficient
1.75 albertel 763:
764: my $molecule = $2;
765: # subscripts
1.78 albertel 766: $molecule =~ s|(?<=[a-zA-Z\)\]\s])(\d+)|<sub>$1</sub>|g;
1.75 albertel 767: # superscripts
768: $molecule =~ s|\^(\d*[+\-]*)|<sup>$1</sup>|g;
769: # strip whitespace
770: $molecule =~ s/\s*//g;
771: # forced space
772: $molecule =~ s/_/ /g;
1.96 albertel 773: $molecule =~ s/-/−/g;
1.75 albertel 774: $formula .= $molecule.' ';
775: }
776: # get rid of trailing space
1.87 albertel 777: $formula =~ s/(\ \;| )$//;
1.75 albertel 778: return &xmlparse($formula);
779: }
780:
1.46 albertel 781: sub prettyprint {
1.73 albertel 782: my ($value,$fmt,$target)=@_;
783: my $result;
784: if (!$target) { $target = $external::target; }
1.75 albertel 785: if ($fmt =~ /chem/i) { return(&chemparse($value)); }
1.81 albertel 786: my ($dollarmode,$commamode,$alwaysperiod,$options);
787: if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; }
1.86 albertel 788: if ($options =~ /\$/) { $dollarmode=1; }
1.81 albertel 789: if ($options =~ /,/) { $commamode=1; }
790: if ($options =~ /\./) { $alwaysperiod=1; }
1.97 albertel 791: if ($fmt=~/s$/i) {
792: $value=&format_significant_figures($value,$fmt);
793: } elsif ($fmt) {
794: $value=sprintf('%.'.$fmt,$value);
795: }
1.81 albertel 796: if ($alwaysperiod && $fmt eq '0f') {
797: if ($target eq 'tex') {
798: $value .='\\ensuremath{.}';
799: } else {
800: $value .='.';
801: }
802: }
1.73 albertel 803: if ($value =~ /([0-9\.\-\+]+)E([0-9\-\+]+)/i ) {
804: my $frac=$1;
805: if ($dollarmode) { $frac=&dollarformat($frac); }
1.80 albertel 806: if ($commamode) { $frac=&commaformat($frac); }
1.73 albertel 807: my $exponent=$2;
808: $exponent=~s/^\+0*//;
809: $exponent=~s/^-0*/-/;
810: $exponent=~s/^-0*/-/;
811: if ($exponent eq '-') { undef($exponent); }
812: if ($exponent) {
813: if ($target eq 'web') {
814: $result=$frac.'×10<sup>'.$exponent.'</sup>';
815: } elsif ($target eq 'tex') {
816: $result='\ensuremath{'.$frac.'\times 10^{'.$exponent.'}}';
817: } else {
818: $result=$value;
819: }
820: } else {
821: $result=$frac;
822: }
823: } else {
1.48 albertel 824: $result=$value;
1.86 albertel 825: if ($dollarmode) { $result=&dollarformat($result,$target); }
826: elsif ($commamode) { $result=&commaformat($result,$target); }
1.46 albertel 827: }
1.73 albertel 828: return $result;
1.48 albertel 829: }
830:
1.80 albertel 831: sub commaformat {
1.73 albertel 832: my ($number,$target) = @_;
833: if ($number =~ /\./) {
1.102 albertel 834: while ($number =~ /([^0-9]*)([0-9]+)([^\.,][^\.,][^\.,])([,0-9]*\.[0-9]*)$/) {
835: $number = $1.$2.','.$3.$4;
1.73 albertel 836: }
837: } else {
1.102 albertel 838: while ($number =~ /^([^0-9]*)([0-9]+)([^,][^,][^,])([,0-9]*)$/) {
839: $number = $1.$2.','.$3.$4;
1.73 albertel 840: }
841: }
1.80 albertel 842: return $number;
843: }
844:
845: sub dollarformat {
846: my ($number,$target) = @_;
847: if (!$target) { $target = $external::target; }
848: $number=&commaformat($number,$target);
1.73 albertel 849: if ($target eq 'tex') {
850: $number='\$'.$number; #' stupid emacs
851: } else {
852: $number='$'.$number; #' stupid emacs
853: }
854: return $number;
1.2 albertel 855: }
1.5 albertel 856:
1.97 albertel 857: # format of form ns or nS where n is an integer
858: sub format_significant_figures {
859: my ($number,$format) = @_;
860: return '0' if ($number == 0);
861: # extract number of significant figures needed
862: my ($sig) = ($format =~ /(\d+)s/i);
863: # arbitrary choice - suggestions ?? or throw error message?
864: $sig = 3 if ($sig eq '');
865: # save the minus sign
866: my $sign = ($number < 0) ? '-' : '';
867: $number = abs($number);
868: # needed to correct for a number greater than 1 (or
869: my $power = ($number < 1) ? 0 : 1;
870: # could round up. Take the integer part of log10.
871: my $x10 = int(log($number)/log(10));
872: # find number with values left of decimal pt = # of sign figs.
873: my $xsig = $number*10**($sig-$x10-$power);
874: # get just digits left of decimal pt - also rounds off correctly
875: my $xint = sprintf('%.0f',$xsig);
876: # save any trailing zero's
877: my ($zeros) = ($xint =~ /(0+)$/);
878: # return number to original magnitude
879: my $numSig = $xint*10**($x10-$sig+$power);
880: # insert trailing zero's if have decimal point
881: $numSig =~ s/^(\d+)\.(\d+)(\e?(.*)?)$/$1\.$2$zeros$3/;
1.98 albertel 882: # put a decimal pt for number ending with 0 and length = # of sig fig
883: $numSig.='.' if (length($numSig) == $sig && $numSig =~ /0$/);
884: if (length($numSig) < $sig) {
885: $numSig.='.'.substr($zeros,0,($sig-length($numSig)));
886: }
1.97 albertel 887: # return number with sign
888: return $sign.$numSig;
889:
890: }
891:
1.5 albertel 892: sub map {
1.27 ng 893: my ($phrase,$dest,$source)=@_;
1.51 albertel 894: my @oldseed=&random_get_seed();
1.27 ng 895: my @seed = &random_seed_from_phrase($phrase);
896: &random_set_seed(@seed);
897: my $destct = scalar(@$dest);
1.28 ng 898: if (!$source) {
899: my @output;
900: my @idx = &math_random_permuted_index($destct);
901: my $ctr = 0;
902: while ($ctr < $destct) {
903: $output[$ctr] = $$dest[$idx[$ctr]];
1.27 ng 904: $ctr++;
1.28 ng 905: }
1.51 albertel 906: &random_set_seed(@oldseed);
1.28 ng 907: return @output;
1.27 ng 908: } else {
1.28 ng 909: my $num = scalar(@$source);
910: my @idx = &math_random_permuted_index($num);
911: my $ctr = 0;
912: my $tot = $num;
913: $tot = $destct if $destct < $num;
914: if (ref($$dest[0])) {
915: while ($ctr < $tot) {
916: ${$$dest[$ctr]} = $$source[$idx[$ctr]];
917: $ctr++;
918: }
919: } else {
920: while ($ctr < $tot) {
921: $$dest[$ctr] = $$source[$idx[$ctr]];
922: $ctr++;
923: }
924: }
1.27 ng 925: }
1.56 albertel 926: &random_set_seed(@oldseed);
1.51 albertel 927: return '';
1.27 ng 928: }
929:
930: sub rmap {
931: my ($phrase,$dest,$source)=@_;
1.51 albertel 932: my @oldseed=&random_get_seed();
1.27 ng 933: my @seed = &random_seed_from_phrase($phrase);
934: &random_set_seed(@seed);
935: my $destct = scalar(@$dest);
1.28 ng 936: if (!$source) {
937: my @idx = &math_random_permuted_index($destct);
938: my $ctr = 0;
939: my @r_idx;
940: while ($ctr < $destct) {
941: $r_idx[$idx[$ctr]] = $ctr;
942: $ctr++;
943: }
944: my @output;
945: $ctr = 0;
946: while ($ctr < $destct) {
947: $output[$ctr] = $$dest[$r_idx[$ctr]];
1.27 ng 948: $ctr++;
1.28 ng 949: }
1.51 albertel 950: &random_set_seed(@oldseed);
1.28 ng 951: return @output;
1.27 ng 952: } else {
1.28 ng 953: my $num = scalar(@$source);
954: my @idx = &math_random_permuted_index($num);
955: my $ctr = 0;
956: my $tot = $num;
957: $tot = $destct if $destct < $num;
958: my @r_idx;
1.27 ng 959: while ($ctr < $tot) {
1.28 ng 960: $r_idx[$idx[$ctr]] = $ctr;
1.27 ng 961: $ctr++;
1.28 ng 962: }
963: $ctr = 0;
964: if (ref($$dest[0])) {
965: while ($ctr < $tot) {
966: ${$$dest[$ctr]} = $$source[$r_idx[$ctr]];
967: $ctr++;
968: }
969: } else {
970: while ($ctr < $tot) {
971: $$dest[$ctr] = $$source[$r_idx[$ctr]];
972: $ctr++;
973: }
974: }
1.6 albertel 975: }
1.51 albertel 976: &random_set_seed(@oldseed);
977: return '';
1.5 albertel 978: }
1.22 ng 979:
1.23 ng 980: sub capa_id { return }
981:
982: sub problem { return }
983:
1.22 ng 984: sub name{
1.73 albertel 985: my $fullname = &EXT('environment.lastname').', '.&EXT('environment.firstname').' '.&EXT('environment.middlename');
986: $fullname = "" if $fullname eq ", ";
987: $fullname =~ s/\%2d/-/g;
988: return $fullname;
1.22 ng 989: }
990:
991: sub student_number {
1.73 albertel 992: my $id = &EXT('environment.id');
993: $id = '' if $id eq "";
994: return $id;
1.22 ng 995: }
996:
997: sub class {
1.73 albertel 998: my $course = &EXT('course.description');
999: $course = '' if $course eq "";
1000: return $course;
1.22 ng 1001: }
1002:
1.112 www 1003: sub firstname {
1004: my $firstname = &EXT('environment.firstname');
1005: $firstname = '' if $firstname eq "";
1006: return $firstname;
1007: }
1008:
1009: sub lastname {
1010: my $lastname = &EXT('environment.lastname');
1011: $lastname = '' if $lastname eq "";
1012: return $lastname;
1013: }
1014:
1.22 ng 1015: sub sec {
1.73 albertel 1016: my $sec = &EXT('request.course.sec');
1017: $sec = '' if $sec eq "";
1018: return $sec;
1.22 ng 1019: }
1020:
1.23 ng 1021: sub open_date {
1.73 albertel 1022: my @dc = split(/\s+/,localtime(&EXT('resource.0.opendate')));
1023: return '' if ($dc[0] eq "Wed" and $dc[2] == 31 and $dc[4] == 1969);
1024: my @hm = split(/:/,$dc[3]);
1025: my $ampm = " am";
1026: if ($hm[0] > 12) {
1027: $hm[0]-=12;
1028: $ampm = " pm";
1029: }
1030: return $dc[0].', '.$dc[1].' '.$dc[2].', '.$dc[4].' at '.$hm[0].':'.$hm[1].$ampm;
1.23 ng 1031: }
1032:
1033: sub due_date {
1.73 albertel 1034: my @dc = split(/\s+/,localtime(&EXT('resource.0.duedate')));
1035: return '' if ($dc[0] eq "Wed" and $dc[2] == 31 and $dc[4] == 1969);
1036: my @hm = split(/:/,$dc[3]);
1037: my $ampm = " am";
1038: if ($hm[0] > 12) {
1039: $hm[0]-=12;
1040: $ampm = " pm";
1041: }
1042: return $dc[0].', '.$dc[1].' '.$dc[2].', '.$dc[4].' at '.$hm[0].':'.$hm[1].$ampm;
1.23 ng 1043: }
1044:
1045: sub answer_date {
1.73 albertel 1046: my @dc = split(/\s+/,localtime(&EXT('resource.0.answerdate')));
1047: return '' if ($dc[0] eq "Wed" and $dc[2] == 31 and $dc[4] == 1969);
1048: my @hm = split(/:/,$dc[3]);
1049: my $ampm = " am";
1050: if ($hm[0] > 12) {
1051: $hm[0]-=12;
1052: $ampm = " pm";
1053: }
1054: return $dc[0].', '.$dc[1].' '.$dc[2].', '.$dc[4].' at '.$hm[0].':'.$hm[1].$ampm;
1.24 ng 1055: }
1056:
1057: sub array_moments {
1.73 albertel 1058: my @input=@_;
1059: my (@output,$N);
1060: $N=scalar (@input);
1061: $output[0]=$N;
1062: if ($N <= 1) {
1063: $output[1]=$input[0];
1064: $output[1]="Input array not defined" if ($N == 0);
1065: $output[2]="variance undefined for N<=1";
1066: $output[3]="skewness undefined for N<=1";
1067: $output[4]="kurtosis undefined for N<=1";
1068: return @output;
1069: }
1070: my $sum=0;
1071: foreach my $line (@input) {
1072: $sum+=$line;
1073: }
1074: $output[1] = $sum/$N;
1075: my ($x,$sdev,$var,$skew,$kurt) = 0;
1076: foreach my $line (@input) {
1077: $x=$line-$output[1];
1078: $var+=$x**2;
1079: $skew+=$x**3;
1080: $kurt+=$x**4;
1081: }
1082: $output[2]=$var/($N-1);
1083: $sdev=CORE::sqrt($output[2]);
1084: if ($sdev == 0) {
1085: $output[3]="inf-variance=0";
1086: $output[4]="inf-variance=0";
1087: return @output;
1088: }
1089: $output[3]=$skew/($sdev**3*$N);
1090: $output[4]=$kurt/($sdev**4*$N)-3;
1.24 ng 1091: return @output;
1092: }
1.5 albertel 1093:
1094: sub choose {
1.73 albertel 1095: my $num = $_[0];
1096: return $_[$num];
1.5 albertel 1097: }
1.23 ng 1098:
1.101 albertel 1099: #&sum1(1,$x,sub { &sum1($_[0],2*$_[0], sub { fact($_[0])**2 })});
1100: #sub sum1 {
1101: # my ($start,$end,$sub)=@_;
1102: # my $sum=0;
1103: # for (my $i=$start;$i<=$end;$i++) {
1104: # $sum+=&$sub($i);
1105: # }
1106: # return $sum
1107: #}
1108:
1109: #&sum2('a',1,$x,'&sum2(\'b\',$a,2*$a, \'&factorial($b)**2\')');
1110: #sub sum2 {
1111: # my ($varname,$start,$end,$line)=@_;
1112: # my $sum=0;
1113: # for (my $i=$start;$i<=$end;$i++) {
1114: # my $func=sub {
1115: # eval("\$".$varname."=$i");
1116: # eval($line);
1117: # };
1118: # $sum+=&$func($i);
1119: # }
1120: # return $sum
1121: #}
1122:
1.49 albertel 1123: # expiremental idea
1124: sub proper_path {
1.73 albertel 1125: my ($path)=@_;
1126: if ( $external::target eq "tex" ) {
1127: return '/home/httpd/html'.$path;
1128: } else {
1129: return $path;
1130: }
1.49 albertel 1131: }
1.23 ng 1132:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>