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