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