File:  [LON-CAPA] / loncom / homework / default_homework.lcpm
Revision 1.118: download - view: text, annotated - select for diffs
Mon Oct 2 18:23:38 2006 UTC (17 years, 7 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- saving some notes for future speed up possiblities

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

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