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