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.152.2.1 2011/08/03 03:37:23 raeburn 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 sure 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') || ($type eq '8')) {
221: if ($response=~/\=/) {
222: return ('BAD_FORMULA','Please submit just an expression, not an equation.');
223: } elsif ($response =~ /\,/ and $response !~ /^\s*\{.*\}\s*$/) {
224: return ('BAD_FORMULA');
225: }
226: }
227: if ($type eq '9') {
228: $result = &maxima_check(&maxima_cas_formula_fix($response),&maxima_cas_formula_fix($answer),\$reterror);
229: } else {
230: if ($type eq '8') { # fml type
231: $response = &capa_formula_fix($response);
232: $answer = &capa_formula_fix($answer);
233: }
234: $result = &caparesponse_capa_check_answer($response,$answer,$type,
235: $tol_type,$tol,
236: $sig_lbound,$sig_ubound,
237: $ans_fmt,$unit,$calc,$id_list,
238: $points,$external::randomseed,
239: \$reterror);
240: }
241: if ($result == '1') { $result='EXACT_ANS'; }
242: elsif ($result == '2') { $result='APPROX_ANS'; }
243: elsif ($result == '3') { $result='SIG_FAIL'; }
244: elsif ($result == '4') { $result='UNIT_FAIL'; }
245: elsif ($result == '5') { $result='NO_UNIT'; }
246: elsif ($result == '6') { $result='UNIT_OK'; }
247: elsif ($result == '7') { $result='INCORRECT'; }
248: elsif ($result == '8') { $result='UNIT_NOTNEEDED'; }
249: elsif ($result == '9') { $result='ANS_CNT_NOT_MATCH'; }
250: elsif ($result =='10') { $result='SUB_RECORDED'; }
251: elsif ($result =='11') { $result='BAD_FORMULA'; }
252: elsif ($result =='12' && !$response) { $result='MISSING_ANSWER'; }
253: elsif ($result =='12') { $result='WANTED_NUMERIC'; }
254: elsif ($result =='13') { $result='UNIT_INVALID_INSTRUCTOR'; }
255: elsif ($result =='141') { $result='UNIT_INVALID_STUDENT'; }
256: elsif ($result =='142') { $result='UNIT_INVALID_STUDENT'; }
257: elsif ($result =='143') { $result='UNIT_INVALID_STUDENT'; }
258: elsif ($result =='15') { $result='UNIT_IRRECONCIBLE'; }
259: else {$result = "ERROR: Unknown Result:$result:$@:";}
260:
261: &LONCAPA_INTERNAL_DEBUG("RetError $reterror: Answer $answer: Response $response: type-$type|$tol|$tol_type|$sig:$sig_lbound:$sig_ubound|$unit|");
262: &LONCAPA_INTERNAL_DEBUG(" $answer $response $result ");
263: return ($result,$reterror);
264: }
265:
266:
267: sub caparesponse_check_list {
268: my $responses=$LONCAPA::CAPAresponse_args{'response'};
269: &LONCAPA_INTERNAL_DEBUG("args ".join(':',%LONCAPA::CAPAresponse_args));
270: my $type = $LONCAPA::CAPAresponse_args{'type'};
271: my $answerunit=$LONCAPA::CAPAresponse_args{'unit'};
272: &LONCAPA_INTERNAL_DEBUG("Got type :$type: answer unit :$answerunit:\n");
273:
274: my $num_input_lines =
275: scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}});
276:
277: if ($type ne '' ) {
278: if (scalar(@$responses) < $num_input_lines) {
279: return 'MISSING_ANSWER';
280: }
281: if (scalar(@$responses) > $num_input_lines) {
282: return 'EXTRA_ANSWER';
283: }
284:
285: }
286:
287: foreach my $which (0..($num_input_lines-1)) {
288: my $answer_size =
289: scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}[$which]});
290: if ($type ne ''
291: && $answer_size > 1) {
292: $responses->[$which]=[split(/,/,$responses->[$which])];
293: } else {
294: $responses->[$which]=[$responses->[$which]];
295: }
296: }
297: foreach my $which (0..($num_input_lines-1)) {
298: my $answer_size =
299: scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}[$which]});
300: my $response_size =
301: scalar(@{$responses->[$which]});
302: if ($answer_size > $response_size) {
303: return 'MISSING_ANSWER';
304: }
305: if ($answer_size < $response_size) {
306: return 'EXTRA_ANSWER';
307: }
308: }
309:
310: &LONCAPA_INTERNAL_DEBUG("Initial final response :$responses->[0][-1]:");
311: my $unit;
312: if ($type eq 'float' || $type eq '') {
313: #for numerical problems split off the unit
314: # if ( $responses->[0][-1]=~ /(.*[^\s])\s+([^\s]+)/ ) {
315: if ( $responses->[0][-1]=~ /^([\d\.\,\s\$]*(?:(?:[xX\*]10[\^\*]*|[eE]*)[\+\-]*\d*)*(?:^|\S)\d+)([\$\s\w\^\*\/\(\)\+\-]*[^\d\.\s\,][\$\s\w\^\*\/\(\)\+\-]*)$/ ) {
316: $responses->[0][-1]=$1;
317: $unit=&capa_formula_fix($2);
318: &LONCAPA_INTERNAL_DEBUG("Found unit :$unit:");
319: }
320: }
321: &LONCAPA_INTERNAL_DEBUG("Final final response :$responses->[0][-1]:$unit:");
322: $unit=~s/\s//;
323: my $error;
324: foreach my $response (@$responses) {
325: foreach my $element (@$response) {
326: if (($type eq 'float') || (($type eq '') && ($unit ne ''))) {
327: $element =~ s/\s//g;
328: }
329: my $appendunit=$unit;
330: # Deal with percentages
331: # unit is unit entered by student, answerunit is unit by author
332: # Deprecated: divide answer by 100 if student entered percent,
333: # but author did not. Too much confusion
334: # if (($unit=~/\%/) && ($answerunit ne '%')) {
335: # $element=$element/100;
336: # $appendunit=~s/\%//;
337: # }
338: # Author entered percent, student did not
339: if (($unit!~/\%/) && ($answerunit=~/\%/)) {
340: $element=$element*100;
341: $appendunit='%'.$appendunit;
342: }
343: # Zero does not need a dimension
344: if (($element =~ /^[0\.]+$/) && ($unit!~/\w/) && ($answerunit=~/\w/)) {
345: $appendunit=$answerunit;
346: }
347: if ($appendunit ne '') {
348: $element .= " $appendunit";
349: }
350: &LONCAPA_INTERNAL_DEBUG("Made response element :$element:");
351: }
352: }
353:
354: foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
355: if (!defined($thisanswer)) {
356: return ('ERROR','answer was undefined');
357: }
358: }
359:
360: my $allow_control_char = 0;
361: my $control_chars_removed = 0;
362: my $ansstring;
363: if ($type eq 'cs' || $type eq 'ci') {
364: if (ref($LONCAPA::CAPAresponse_answer->{'answers'}) eq 'ARRAY') {
365: foreach my $strans (@{$LONCAPA::CAPAresponse_answer->{'answers'}}) {
366: if (ref($strans) eq 'ARRAY') {
367: $ansstring = join("\0",@{$strans});
368: foreach my $item (@{$strans}) {
369: if ($item =~ /[\000-\037]/) {
370: $allow_control_char = 1;
371: }
372: }
373: }
374: }
375: }
376: }
377:
378: # &LONCAPA_INTERNAL_DEBUG(&LONCAPA_INTERNAL_Dumper($responses));
379: my %memoized;
380: if ($LONCAPA::CAPAresponse_answer->{'type'} eq 'ordered') {
381: for (my $i=0; $i<scalar(@$responses);$i++) {
382: my $answer = $LONCAPA::CAPAresponse_answer->{'answers'}[$i];
383: my $response = $responses->[$i];
384: my $key = "$answer\0$response";
385: my (@awards,@msgs);
386: for (my $j=0; $j<scalar(@$response); $j++) {
387: if ($type eq 'cs' || $type eq 'ci') {
388: unless ($allow_control_char) {
389: if ($response->[$j] =~ /[\000-\037]/) {
390: $response->[$j] =~ s/[\000-\037]//g;
391: $control_chars_removed = 1;
392: }
393: }
394: }
395: my ($award,$msg) = &caparesponse_check($answer->[$j],
396: $response->[$j]);
397: if ($type eq 'cs' || $type eq 'ci') {
398: $error = &verify_stringresponse($type,$award,$response->[$j],
399: $answer->[$j]);
400: }
401: push(@awards,$award);
402: push(@msgs, $msg);
403: }
404: my ($award,$msg) =
405: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
406: $memoized{$key} = [$award,$msg];
407: }
408: } else {
409: #FIXME broken with unorder responses where one is a <value>
410: # and the other is a <vector> (need to delay parse til
411: # inside the loop?)
412: foreach my $response (@$responses) {
413: my $response_size = scalar(@{$response});
414: foreach my $answer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
415: my $key = "$answer\0$response";
416: my $answer_size = scalar(@{$answer});
417: my ($award,$msg);
418: if ($answer_size > $response_size) {
419: $award = 'MISSING_ANSWER';
420: } elsif ($answer_size < $response_size) {
421: $award = 'EXTRA_ANSWER';
422: } else {
423: my (@awards,@msgs);
424: for (my $j=0; $j<scalar(@$response); $j++) {
425: if ($type eq 'cs' || $type eq 'ci') {
426: unless ($allow_control_char) {
427: if ($response->[$j] =~ /[\000-\037]/) {
428: $response->[$j] =~ s/[\000-\037]//g;
429: $control_chars_removed = 1;
430: }
431: }
432: }
433: my ($award,$msg) = &caparesponse_check($answer->[$j],
434: $response->[$j]);
435: if ($type eq 'cs' || $type eq 'ci') {
436: $error = &verify_stringresponse($type,$award,$response->[$j],
437: $answer->[$j]);
438: }
439: push(@awards,$award);
440: push(@msgs, $msg);
441: }
442: ($award,$msg) =
443: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
444: }
445: $memoized{$key} = [$award,$msg];
446: }
447: }
448: }
449:
450: my ($final_award,$final_msg);
451: &init_permutation(scalar(@$responses),
452: $LONCAPA::CAPAresponse_answer->{'type'});
453:
454: # possible FIXMEs
455: # - significant time is spent calling non-safe space routine
456: # from safe space
457: # - early outs could be possible with classifying awards is to stratas
458: # and stopping as so as hitting the top strata
459: # - some early outs also might be possible with check ing the
460: # memoized hash of results (is correct even possible? etc.)
461:
462: my (@final_awards,@final_msg);
463: while( &get_permutations_left() ) {
464: my $order = &get_next_permutation();
465: my (@awards, @msgs, $i);
466: foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
467: my $key = "$thisanswer\0".$responses->[$order->[$i]];
468: push(@awards,$memoized{$key}[0]);
469: push(@msgs,$memoized{$key}[1]);
470: $i++;
471:
472: }
473: &LONCAPA_INTERNAL_DEBUG(" all awards ".join(':',@awards));
474:
475: my ($possible_award,$possible_msg) =
476: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
477: &LONCAPA_INTERNAL_DEBUG(" pos awards ".$possible_award);
478: push(@final_awards,$possible_award);
479: push(@final_msg,$possible_msg);
480: }
481:
482: &LONCAPA_INTERNAL_DEBUG(" all final_awards ".join(':',@final_awards));
483: my ($final_award,$final_msg) =
484: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@final_awards,\@final_msg,undef,1);
485: return ($final_award,$final_msg,$error,$control_chars_removed,$ansstring);
486: }
487:
488: sub verify_stringresponse {
489: my ($type,$award,$resp,$ans) = @_;
490: return if ($award eq 'EXACT_ANS');
491: my $error;
492: if ($resp =~ /^\s|\s$/) {
493: $resp =~ s{^\s+|\s+$}{}g;
494: }
495: if ($ans =~ /^\s|\s$/) {
496: $ans =~ s{^\s+|\s+$}{}g;
497: }
498: if ($type eq 'ci') {
499: $resp = lc($resp);
500: $ans = lc($ans);
501: }
502: if ($resp eq $ans) {
503: if ($award eq 'INCORRECT') {
504: $error = 'MISGRADED';
505: }
506: }
507: return $error;
508: }
509:
510: sub cas {
511: my ($system,$input,$library)=@_;
512: my $output;
513: my $dump;
514: if ($system eq 'maxima') {
515: $output=&maxima_eval($input,$library);
516: } elsif ($system eq 'R') {
517: ($output,$dump)=&r_eval($input,$library,0);
518: } else {
519: $output='Error: unrecognized CAS';
520: }
521: return $output;
522: }
523:
524: sub cas_hashref {
525: my ($system,$input,$library)=@_;
526: if ($system eq 'maxima') {
527: return 'Error: unsupported CAS';
528: } elsif ($system eq 'R') {
529: return &r_eval($input,$library,1);
530: } else {
531: return 'Error: unrecognized CAS';
532: }
533: }
534:
535: #
536: # cas_hashref_entry takes a list of indices and gets the entry in a hash generated by Rreturn.
537: # Call: cas_hashref_entry(Rvalue, index1, index2, ...) where Rvalue is a hash returned by Rreturn.
538: # Rentry will return the first scalar value it encounters (ignoring excess indices).
539: # If an invalid key is given, it returns undef.
540: #
541: sub cas_hashref_entry {
542: return &Rentry(@_);
543: }
544:
545: #
546: # cas_hashref_array takes a list of indices and gets a column array from a hash generated by Rreturn.
547: # Call: cas_hashref_array(Rvalue, index1, index2, ...) where Rvalue is a hash returned by Rreturn.
548: # If an invalid key is given, it returns undef.
549: #
550: sub cas_hashref_array {
551: return &Rarray(@_);
552: }
553:
554: sub tex {
555: if ( $external::target eq "tex" ) {
556: return $_[0];
557: } else {
558: return $_[1];
559: }
560: }
561:
562: sub var_in_tex {
563: if ( $external::target eq "tex" ) {
564: return $_[0];
565: } else {
566: return "";
567: }
568: }
569:
570: sub web {
571: if ( $external::target eq "tex" ) {
572: return $_[1];
573: } else {
574: if ( $external::target eq "web" || $external::target eq "answer") {
575: return $_[2];
576: } else {
577: return $_[0];
578: }
579: }
580: }
581:
582: sub html {
583: if ( $external::target eq "web" ) {
584: return shift;
585: }
586: }
587:
588: sub hinton {
589: return 0;
590: }
591:
592: sub random {
593: my ($start,$end,$step)=@_;
594: if ( ! $hidden::RANDOMINIT ) {
595: if ($external::randomseed == 0) { $external::randomseed=1; }
596: if ($external::randomseed =~/,/) {
597: my ($num1,$num2)=split(/,/,$external::randomseed);
598: &random_set_seed(1,abs($num1));
599: } elsif ($external::randomseed =~/:/) {
600: my ($num1,$num2)=split(/:/,$external::randomseed);
601: &random_set_seed(abs($num1),abs($num2));
602: } else {
603: &random_set_seed(1,int(abs($external::randomseed)));
604: }
605: &math_random_uniform();
606: $hidden::RANDOMINIT=1;
607: }
608: if (!defined($step)) { $step=1; }
609: my $num=1+int(($end-$start)/$step);
610: my $result=$start + int(&math_random_uniform() * $num)*$step;
611: return $result;
612: }
613:
614: sub random_normal {
615: my ($item_cnt,$seed,$av,$std_dev) = @_;
616: my @oldseed=&random_get_seed();
617: my @retArray;
618: &random_set_seed_from_phrase($seed);
619: @retArray=&math_random_normal($item_cnt,$av,$std_dev);
620: &random_set_seed(@oldseed);
621: return @retArray;
622: }
623:
624: sub random_beta {
625: my ($item_cnt,$seed,$aa,$bb) = @_;
626: my @oldseed=&random_get_seed();
627: my @retArray;
628: &random_set_seed_from_phrase($seed);
629: @retArray=&math_random_beta($item_cnt,$aa,$bb);
630: &random_set_seed(@oldseed);
631: return @retArray;
632: }
633:
634: sub random_gamma {
635: my ($item_cnt,$seed,$a,$r) = @_;
636: my @oldseed=&random_get_seed();
637: my @retArray;
638: &random_set_seed_from_phrase($seed);
639: @retArray=&math_random_gamma($item_cnt,$a,$r);
640: &random_set_seed(@oldseed);
641: return @retArray;
642: }
643:
644: sub random_exponential {
645: my ($item_cnt,$seed,$av) = @_;
646: my @oldseed=&random_get_seed();
647: my @retArray;
648: &random_set_seed_from_phrase($seed);
649: @retArray=&math_random_exponential($item_cnt,$av);
650: &random_set_seed(@oldseed);
651: return @retArray;
652: }
653:
654: sub random_poisson {
655: my ($item_cnt,$seed,$mu) = @_;
656: my @oldseed=&random_get_seed();
657: my @retArray;
658: &random_set_seed_from_phrase($seed);
659: @retArray=&math_random_poisson($item_cnt,$mu);
660: &random_set_seed(@oldseed);
661: return @retArray;
662: }
663:
664: sub random_chi {
665: my ($item_cnt,$seed,$df) = @_;
666: my @oldseed=&random_get_seed();
667: my @retArray;
668: &random_set_seed_from_phrase($seed);
669: @retArray=&math_random_chi_square($item_cnt,$df);
670: &random_set_seed(@oldseed);
671: return @retArray;
672: }
673:
674: sub random_noncentral_chi {
675: my ($item_cnt,$seed,$df,$nonc) = @_;
676: my @oldseed=&random_get_seed();
677: my @retArray;
678: &random_set_seed_from_phrase($seed);
679: @retArray=&math_random_noncentral_chi_square($item_cnt,$df,$nonc);
680: &random_set_seed(@oldseed);
681: return @retArray;
682: }
683:
684: sub random_f {
685: my ($item_cnt,$seed,$dfn,$dfd) = @_;
686: my @oldseed=&random_get_seed();
687: my @retArray;
688: &random_set_seed_from_phrase($seed);
689: @retArray=&math_random_f($item_cnt,$dfn,$dfd);
690: &random_set_seed(@oldseed);
691: return @retArray;
692: }
693:
694: sub random_noncentral_f {
695: my ($item_cnt,$seed,$dfn,$dfd,$nonc) = @_;
696: my @oldseed=&random_get_seed();
697: my @retArray;
698: &random_set_seed_from_phrase($seed);
699: @retArray=&math_random_noncentral_f($item_cnt,$dfn,$dfd,$nonc);
700: &random_set_seed(@oldseed);
701: return @retArray;
702: }
703:
704: sub random_multivariate_normal {
705: my ($item_cnt,$seed,$mean,$covar) = @_;
706: my @oldseed=&random_get_seed();
707: &random_set_seed_from_phrase($seed);
708: my @retArray=&math_random_multivariate_normal($item_cnt,@$mean,@$covar);
709: &random_set_seed(@oldseed);
710: return @retArray;
711: }
712:
713: sub random_multinomial {
714: my ($item_cnt,$seed,@p) = @_;
715: my @oldseed=&random_get_seed();
716: my @retArray;
717: &random_set_seed_from_phrase($seed);
718: my @retArray=&math_random_multinomial($item_cnt,@p);
719: &random_set_seed(@oldseed);
720: return @retArray;
721: }
722:
723: sub random_permutation {
724: my ($seed,@inArray) = @_;
725: my @oldseed=&random_get_seed();
726: my @retArray;
727: &random_set_seed_from_phrase($seed);
728: @retArray=&math_random_permutation(@inArray);
729: &random_set_seed(@oldseed);
730: return @retArray;
731: }
732:
733: sub random_uniform {
734: my ($item_cnt,$seed,$low,$high) = @_;
735: my @oldseed=&random_get_seed();
736: my @retArray;
737: &random_set_seed_from_phrase($seed);
738: @retArray=&math_random_uniform($item_cnt,$low,$high);
739: &random_set_seed(@oldseed);
740: return @retArray;
741: }
742:
743: sub random_uniform_integer {
744: my ($item_cnt,$seed,$low,$high) = @_;
745: my @oldseed=&random_get_seed();
746: my @retArray;
747: &random_set_seed_from_phrase($seed);
748: @retArray=&math_random_uniform_integer($item_cnt,$low,$high);
749: &random_set_seed(@oldseed);
750: return @retArray;
751: }
752:
753: sub random_binomial {
754: my ($item_cnt,$seed,$nt,$p) = @_;
755: my @oldseed=&random_get_seed();
756: my @retArray;
757: &random_set_seed_from_phrase($seed);
758: @retArray=&math_random_binomial($item_cnt,$nt,$p);
759: &random_set_seed(@oldseed);
760: return @retArray;
761: }
762:
763: sub random_negative_binomial {
764: my ($item_cnt,$seed,$ne,$p) = @_;
765: my @oldseed=&random_get_seed();
766: my @retArray;
767: &random_set_seed_from_phrase($seed);
768: @retArray=&math_random_negative_binomial($item_cnt,$ne,$p);
769: &random_set_seed(@oldseed);
770: return @retArray;
771: }
772:
773: sub abs { CORE::abs(shift) }
774: sub sin { CORE::sin(shift) }
775: sub cos { CORE::cos(shift) }
776: sub exp { CORE::exp(shift) }
777: sub int { CORE::int(shift) }
778: sub log { CORE::log(shift) }
779: sub atan2 { CORE::atan2($_[0],$_[1]) }
780: sub sqrt { CORE::sqrt(shift) }
781:
782: sub tan { CORE::sin($_[0]) / CORE::cos($_[0]) }
783: #sub atan { atan2($_[0], 1); }
784: #sub acos { atan2(sqrt(1 - $_[0] * $_[0]), $_[0] ); }
785: #sub asin { atan2($_[0], sqrt(1- $_[0] * $_[0]) ); }
786:
787: sub log10 { CORE::log($_[0])/CORE::log(10); }
788:
789: sub factorial {
790: my $input = CORE::int(shift);
791: return "Error - unable to take factorial of an negative number ($input)" if $input < 0;
792: return "Error - factorial result is greater than system limit ($input)" if $input > 170;
793: return 1 if $input == 0;
794: my $result = 1;
795: for (my $i=2; $i<=$input; $i++) { $result *= $i }
796: return $result;
797: }
798:
799: sub sgn {
800: return -1 if $_[0] < 0;
801: return 0 if $_[0] == 0;
802: return 1 if $_[0] > 0;
803: }
804:
805: sub min {
806: my @sorted = sort { $a <=> $b || $a cmp $b } @_;
807: return shift @sorted;
808: }
809:
810: sub max {
811: my @sorted = sort { $a <=> $b || $a cmp $b } @_;
812: return pop @sorted;
813: }
814:
815: sub roundto {
816: my ($input,$n) = @_;
817: return sprintf('%.'.$n.'f',$input);
818: }
819:
820: sub to_string {
821: my ($input,$n) = @_;
822: return sprintf($input) if $n eq "";
823: $n = '.'.$n if $n !~ /^\./;
824: return sprintf('%'.$n,$input) if $n ne "";
825: }
826:
827: sub sub_string {
828: my ($str,$start,$len) = @_;
829: return substr($str,$start-1,$len);
830: }
831:
832: sub pow {return $_[0] ** $_[1]; }
833: sub ceil {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? (CORE::int($_[0])+ 1) : CORE::int($_[0])); }
834: sub floor {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? CORE::int($_[0]) : (CORE::int($_[0])-1)); }
835: #sub floor {return int($_[0]); }
836:
837: sub format {
838: my ($value,$fmt)=@_;
839: my ($dollarmode,$commamode,$alwaysperiod,$options);
840: if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; }
841: #if ($options =~ /\$/) { $dollamode=1; }
842: #if ($options =~ /,/) { $commamode=1; }
843: if ($options =~ /\./) { $alwaysperiod=1; }
844: my $result;
845: if ($fmt=~/s$/i) {
846: $result=&format_significant_figures($value,$fmt);
847: } else {
848: $fmt=~s/e/E/g;
849: $result=sprintf('%.'.$fmt,$value);
850: if ($alwaysperiod && $fmt eq '0f') { $result .='.'; }
851: $result=~s/(E[+-]*)0/$1/;
852: }
853: #if ($dollarmode) {$result=&dollarformat($result);}
854: #if ($commamode) {$result=&commaformat($result);}
855: return $result;
856: }
857:
858: sub chemparse {
859: my ($reaction) = @_;
860: my @tokens = split(/(\s\+|\->|<=>|<\-|\.)/,$reaction);
861: my $formula = '';
862: foreach my $token (@tokens) {
863: if ($token eq '->' ) {
864: $formula .= '<m>\ensuremath{\rightarrow}</m> ';
865: next;
866: }
867: if ($token eq '<-' ) {
868: $formula .= '<m>\ensuremath{\leftarrow}</m> ';
869: next;
870: }
871: if ($token eq '<=>') {
872: if ($external::target eq 'web' &&
873: &EXT('request.browser.unicode')) {
874: $formula .= '⇌ ';
875: } else {
876: $formula .= &web('<=> ','<m>\ensuremath{\rightleftharpoons}</m> ',
877: '<=> ');
878: }
879: next;
880: }
881: if ($token eq '.') {
882: $formula =~ s/(\ \;| )$//;
883: $formula .= '·';
884: next;
885: }
886: $token =~ /^\s*([\d|\/]*(?:&frac\d\d)?)(.*)/;
887: $formula .= $1 if ($1 ne '1'); # stoichiometric coefficient
888:
889: my $molecule = $2;
890: # subscripts
891: $molecule =~ s|(?<=[a-zA-Z\)\]\s])(\d+)|<sub>$1</sub>|g;
892: # superscripts
893: $molecule =~ s|\^(\d*[+\-]*)|<sup>$1</sup>|g;
894: # strip whitespace
895: $molecule =~ s/\s*//g;
896: # forced space
897: $molecule =~ s/_/ /g;
898: $molecule =~ s/-/−/g;
899: $formula .= $molecule.' ';
900: }
901: # get rid of trailing space
902: $formula =~ s/(\ \;| )$//;
903: return &xmlparse($formula);
904: }
905:
906: sub prettyprint {
907: my ($value,$fmt,$target)=@_;
908: my $result;
909: if (!$target) { $target = $external::target; }
910: if ($fmt =~ /chem/i) { return(&chemparse($value)); }
911: my ($dollarmode,$commamode,$alwaysperiod,$options);
912: if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; }
913: if ($options =~ /\$/) { $dollarmode=1; }
914: if ($options =~ /,/) { $commamode=1; }
915: if ($options =~ /\./) { $alwaysperiod=1; }
916: if ($fmt=~/s$/i) {
917: $value=&format_significant_figures($value,$fmt);
918: } elsif ($fmt) {
919: $value=sprintf('%.'.$fmt,$value);
920: }
921: if ($alwaysperiod && $fmt eq '0f') {
922: if ($target eq 'tex') {
923: $value .='\\ensuremath{.}';
924: } else {
925: $value .='.';
926: }
927: }
928: if ($value =~ /([0-9\.\-\+]+)E([0-9\-\+]+)/i ) {
929: my $frac=$1;
930: if ($dollarmode) { $frac=&dollarformat($frac); }
931: if ($commamode) { $frac=&commaformat($frac); }
932: my $exponent=$2;
933: $exponent=~s/^\+0*//;
934: $exponent=~s/^-0*/-/;
935: $exponent=~s/^-0*/-/;
936: if ($exponent eq '-') { undef($exponent); }
937: if ($exponent) {
938: if ($target eq 'web') {
939: $result=$frac.'×10<sup>'.$exponent.'</sup>';
940: } elsif ($target eq 'tex') {
941: $result='\ensuremath{'.$frac.'\times 10^{'.$exponent.'}}';
942: } else {
943: $result=$value;
944: }
945: } else {
946: $result=$frac;
947: }
948: } else {
949: $result=$value;
950: if ($dollarmode) { $result=&dollarformat($result,$target); }
951: elsif ($commamode) { $result=&commaformat($result,$target); }
952: }
953: return $result;
954: }
955:
956: sub commaformat {
957: my ($number,$target) = @_;
958: if ($number =~ /\./) {
959: while ($number =~ /([^0-9]*)([0-9]+)([^\.,][^\.,][^\.,])([,0-9]*\.[0-9]*)$/) {
960: $number = $1.$2.','.$3.$4;
961: }
962: } else {
963: while ($number =~ /^([^0-9]*)([0-9]+)([^,][^,][^,])([,0-9]*)$/) {
964: $number = $1.$2.','.$3.$4;
965: }
966: }
967: return $number;
968: }
969:
970: sub dollarformat {
971: my ($number,$target) = @_;
972: if (!$target) { $target = $external::target; }
973: $number=&commaformat($number,$target);
974: if ($target eq 'tex') {
975: $number='\$'.$number; #' stupid emacs
976: } else {
977: $number='$'.$number; #' stupid emacs
978: }
979: return $number;
980: }
981:
982: # format of form ns or nS where n is an integer
983: sub format_significant_figures {
984: my ($number,$format) = @_;
985: return '0' if ($number == 0);
986: # extract number of significant figures needed
987: my ($sig) = ($format =~ /(\d+)s/i);
988: # arbitrary choice - suggestions ?? or throw error message?
989: $sig = 3 if ($sig eq '');
990: # save the minus sign
991: my $sign = ($number < 0) ? '-' : '';
992: $number = abs($number);
993: # needed to correct for a number greater than 1 (or
994: my $power = ($number < 1) ? 0 : 1;
995: # could round up. Take the integer part of log10.
996: my $x10 = int(log($number)/log(10));
997: # find number with values left of decimal pt = # of sign figs.
998: my $xsig = $number*10**($sig-$x10-$power);
999: # get just digits left of decimal pt - also rounds off correctly
1000: my $xint = sprintf('%.0f',$xsig);
1001: # save any trailing zero's
1002: my ($zeros) = ($xint =~ /(0+)$/);
1003: # return number to original magnitude
1004: my $numSig = $xint*10**($x10-$sig+$power);
1005: # insert trailing zero's if have decimal point
1006: $numSig =~ s/^(\d+)\.(\d+)(\e?(.*)?)$/$1\.$2$zeros$3/;
1007: # put a decimal pt for number ending with 0 and length = # of sig fig
1008: $numSig.='.' if (length($numSig) == $sig && $numSig =~ /0$/);
1009: if (length($numSig) < $sig) {
1010: $numSig.='.'.substr($zeros,0,($sig-length($numSig)));
1011: }
1012: # return number with sign
1013: return $sign.$numSig;
1014:
1015: }
1016:
1017: sub map {
1018: my ($phrase,$dest,$source)=@_;
1019: my @oldseed=&random_get_seed();
1020: my @seed = &random_seed_from_phrase($phrase);
1021: &random_set_seed(@seed);
1022: my $destct = scalar(@$dest);
1023: if (!$source) {
1024: my @output;
1025: my @idx = &math_random_permuted_index($destct);
1026: my $ctr = 0;
1027: while ($ctr < $destct) {
1028: $output[$ctr] = $$dest[$idx[$ctr]];
1029: $ctr++;
1030: }
1031: &random_set_seed(@oldseed);
1032: return @output;
1033: } else {
1034: my $num = scalar(@$source);
1035: my @idx = &math_random_permuted_index($num);
1036: my $ctr = 0;
1037: my $tot = $num;
1038: $tot = $destct if $destct < $num;
1039: if (ref($$dest[0])) {
1040: while ($ctr < $tot) {
1041: ${$$dest[$ctr]} = $$source[$idx[$ctr]];
1042: $ctr++;
1043: }
1044: } else {
1045: while ($ctr < $tot) {
1046: $$dest[$ctr] = $$source[$idx[$ctr]];
1047: $ctr++;
1048: }
1049: }
1050: }
1051: &random_set_seed(@oldseed);
1052: return '';
1053: }
1054:
1055: sub rmap {
1056: my ($phrase,$dest,$source)=@_;
1057: my @oldseed=&random_get_seed();
1058: my @seed = &random_seed_from_phrase($phrase);
1059: &random_set_seed(@seed);
1060: my $destct = scalar(@$dest);
1061: if (!$source) {
1062: my @idx = &math_random_permuted_index($destct);
1063: my $ctr = 0;
1064: my @r_idx;
1065: while ($ctr < $destct) {
1066: $r_idx[$idx[$ctr]] = $ctr;
1067: $ctr++;
1068: }
1069: my @output;
1070: $ctr = 0;
1071: while ($ctr < $destct) {
1072: $output[$ctr] = $$dest[$r_idx[$ctr]];
1073: $ctr++;
1074: }
1075: &random_set_seed(@oldseed);
1076: return @output;
1077: } else {
1078: my $num = scalar(@$source);
1079: my @idx = &math_random_permuted_index($num);
1080: my $ctr = 0;
1081: my $tot = $num;
1082: $tot = $destct if $destct < $num;
1083: my @r_idx;
1084: while ($ctr < $tot) {
1085: $r_idx[$idx[$ctr]] = $ctr;
1086: $ctr++;
1087: }
1088: $ctr = 0;
1089: if (ref($$dest[0])) {
1090: while ($ctr < $tot) {
1091: ${$$dest[$ctr]} = $$source[$r_idx[$ctr]];
1092: $ctr++;
1093: }
1094: } else {
1095: while ($ctr < $tot) {
1096: $$dest[$ctr] = $$source[$r_idx[$ctr]];
1097: $ctr++;
1098: }
1099: }
1100: }
1101: &random_set_seed(@oldseed);
1102: return '';
1103: }
1104:
1105: sub capa_id { return }
1106:
1107: sub problem { return }
1108:
1109: sub name{
1110: my $fullname = &EXT('environment.lastname').', '.&EXT('environment.firstname').' '.&EXT('environment.middlename');
1111: $fullname = "" if $fullname eq ", ";
1112: $fullname =~ s/\%2d/-/g;
1113: return $fullname;
1114: }
1115:
1116: sub student_number {
1117: my $id = &EXT('environment.id');
1118: $id = '' if $id eq "";
1119: return $id;
1120: }
1121:
1122: sub class {
1123: my $course = &EXT('course.description');
1124: $course = '' if $course eq "";
1125: return $course;
1126: }
1127:
1128: sub firstname {
1129: my $firstname = &EXT('environment.firstname');
1130: $firstname = '' if $firstname eq "";
1131: return $firstname;
1132: }
1133:
1134: sub lastname {
1135: my $lastname = &EXT('environment.lastname');
1136: $lastname = '' if $lastname eq "";
1137: return $lastname;
1138: }
1139:
1140: sub sec {
1141: my $sec = &EXT('request.course.sec');
1142: $sec = '' if $sec eq "";
1143: return $sec;
1144: }
1145:
1146: sub submission {
1147: my ($partid,$responseid,$subnumber)=@_;
1148: my $sub='';
1149: if ($subnumber) { $sub=$subnumber.':'; }
1150: return &EXT('user.resource.'.$sub.'resource.'.$partid.'.'.$responseid.'.submission');
1151: }
1152:
1153: sub currentpart {
1154: return $external::part;
1155: }
1156:
1157: sub eval_time {
1158: my ($timestamp)=@_;
1159: unless ($timestamp) { return ''; }
1160: return &locallocaltime($timestamp);
1161: }
1162:
1163: sub open_date {
1164: my ($partid)=@_;
1165: unless ($partid) { $partid=0; }
1166: return &eval_time(&EXT('resource.'.$partid.'.opendate'));
1167: }
1168:
1169: sub due_date {
1170: my ($partid)=@_;
1171: unless ($partid) { $partid=0; }
1172: return &eval_time(&EXT('resource.'.$partid.'.duedate'));
1173: }
1174:
1175: sub answer_date {
1176: my ($partid)=@_;
1177: unless ($partid) { $partid=0; }
1178: return &eval_time(&EXT('resource.'.$partid.'.answerdate'));
1179: }
1180:
1181: sub open_date_epoch {
1182: my ($partid)=@_;
1183: unless ($partid) { $partid=0; }
1184: return &EXT('resource.'.$partid.'.opendate');
1185: }
1186:
1187: sub due_date_epoch {
1188: my ($partid)=@_;
1189: unless ($partid) { $partid=0; }
1190: return &EXT('resource.'.$partid.'.duedate');
1191: }
1192:
1193: sub answer_date_epoch {
1194: my ($partid)=@_;
1195: unless ($partid) { $partid=0; }
1196: return &EXT('resource.'.$partid.'.answerdate');
1197: }
1198:
1199: sub array_moments {
1200: my @input=@_;
1201: my (@output,$N);
1202: $N=scalar (@input);
1203: $output[0]=$N;
1204: if ($N <= 1) {
1205: $output[1]=$input[0];
1206: $output[1]="Input array not defined" if ($N == 0);
1207: $output[2]="variance undefined for N<=1";
1208: $output[3]="skewness undefined for N<=1";
1209: $output[4]="kurtosis undefined for N<=1";
1210: return @output;
1211: }
1212: my $sum=0;
1213: foreach my $line (@input) {
1214: $sum+=$line;
1215: }
1216: $output[1] = $sum/$N;
1217: my ($x,$sdev,$var,$skew,$kurt) = 0;
1218: foreach my $line (@input) {
1219: $x=$line-$output[1];
1220: $var+=$x**2;
1221: $skew+=$x**3;
1222: $kurt+=$x**4;
1223: }
1224: $output[2]=$var/($N-1);
1225: $sdev=CORE::sqrt($output[2]);
1226: if ($sdev == 0) {
1227: $output[3]="inf-variance=0";
1228: $output[4]="inf-variance=0";
1229: return @output;
1230: }
1231: $output[3]=$skew/($sdev**3*$N);
1232: $output[4]=$kurt/($sdev**4*$N)-3;
1233: return @output;
1234: }
1235:
1236: sub choose {
1237: my $num = $_[0];
1238: return $_[$num];
1239: }
1240:
1241: #&sum1(1,$x,sub { &sum1($_[0],2*$_[0], sub { fact($_[0])**2 })});
1242: #sub sum1 {
1243: # my ($start,$end,$sub)=@_;
1244: # my $sum=0;
1245: # for (my $i=$start;$i<=$end;$i++) {
1246: # $sum+=&$sub($i);
1247: # }
1248: # return $sum
1249: #}
1250:
1251: #&sum2('a',1,$x,'&sum2(\'b\',$a,2*$a, \'&factorial($b)**2\')');
1252: #sub sum2 {
1253: # my ($varname,$start,$end,$line)=@_;
1254: # my $sum=0;
1255: # for (my $i=$start;$i<=$end;$i++) {
1256: # my $func=sub {
1257: # eval("\$".$varname."=$i");
1258: # eval($line);
1259: # };
1260: # $sum+=&$func($i);
1261: # }
1262: # return $sum
1263: #}
1264:
1265: # expiremental idea
1266: sub proper_path {
1267: my ($path)=@_;
1268: if ( $external::target eq "tex" ) {
1269: return '/home/httpd/html'.$path;
1270: } else {
1271: return $path;
1272: }
1273: }
1274:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>