File:  [LON-CAPA] / loncom / homework / default_homework.lcpm
Revision 1.117: download - view: text, annotated - select for diffs
Fri Sep 29 23:10:22 2006 UTC (17 years, 7 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- speed up grading of unordered response (up to 8 values can be down in under 5 secs)

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

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>