File:  [LON-CAPA] / loncom / homework / default_homework.lcpm
Revision 1.135: download - view: text, annotated - select for diffs
Tue Jun 10 16:20:29 2008 UTC (15 years, 10 months ago) by www
Branches: MAIN
CVS tags: HEAD
The &due_date, etc, functions now return correct timezones and languages.

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

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