File:  [LON-CAPA] / loncom / homework / default_homework.lcpm
Revision 1.115: download - view: text, annotated - select for diffs
Fri Jul 28 15:22:28 2006 UTC (17 years, 9 months ago) by www
Branches: MAIN
CVS tags: version_2_2_X, version_2_2_2, version_2_2_1, version_2_2_0, version_2_1_99_3, version_2_1_99_2, HEAD
Trying to cover more implicit multiplication cases

    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.115 2006/07/28 15:22:28 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: 
   37: sub check_commas {
   38:     my ($response)=@_;
   39:     #print("$response ");
   40:     my @numbers=split(',',$response);
   41:     #print(" numbers ".join('-',@numbers)." ");
   42:     if (scalar(@numbers) > 1) {
   43:         #print(" numbers[0] ".$numbers[0]." "); 
   44: 	if (length($numbers[0]) > 3 || length($numbers[0]) == 0) { return -1; }
   45: 	shift(@numbers);
   46: 	#print(" numbers ".scalar(@numbers)." ");
   47: 	while (scalar(@numbers) > 1) {
   48: 	    #print(" numbers ".join('-',@numbers)." ");
   49: 	    if (length($numbers[0]) != 3) { return -2; }
   50: 	    shift(@numbers);
   51: 	}
   52: 	my ($number)=split('\.',$numbers[0]);
   53: 	#print(" number ".$number." ");
   54: 	#print(" numbers[0] ".$numbers[0]." ");
   55: 	if (length($number) != 3) { return -3; }
   56:     } else {
   57: 	my ($number)=split('\.',$numbers[0]);
   58: 	if (length($number) > 3) { return -4; }
   59:     }
   60:     return 1;
   61: }
   62: 
   63: sub caparesponse_check {
   64:     my ($answer,$response)=@_;
   65:     #not properly used yet: calc
   66:     #not to be used: $ans_fmt
   67:     my $type=$LONCAPA::CAPAresponse_args{'type'};
   68:     my $tol=$LONCAPA::CAPAresponse_args{'tol'};
   69:     my $sig=$LONCAPA::CAPAresponse_args{'sig'};
   70:     my $ans_fmt=$LONCAPA::CAPAresponse_args{'format'};
   71:     my $unit=$LONCAPA::CAPAresponse_args{'unit'};
   72:     my $calc=$LONCAPA::CAPAresponse_args{'calc'};
   73:     my $samples=$LONCAPA::CAPAresponse_args{'samples'};
   74:     
   75:     my $tol_type=''; # gets it's value from whether tol has a % or not done
   76:     my $sig_lbound=''; #done
   77:     my $sig_ubound=''; #done
   78: 
   79: 
   80:     #type's definitons come from capaParser.h
   81:     my $message='';
   82:     #remove leading and trailing whitespace
   83:     if (!defined($response)) {
   84: 	$response='';
   85:     }
   86:     if ($response=~ /^\s|\s$/) {
   87: 	$response=~ s:^\s+|\s+$::g;
   88: 	$message .="Removed ws now :$response:\n";
   89:     } else {
   90: 	$message .="no ws in :$response:\n";
   91:     }
   92:     &LONCAPA_INTERNAL_DEBUG(" type is $type ");
   93:     if ($type eq 'cs' || $type eq 'ci') {
   94: 	#for string answers make surec all places spaces occur, there is 
   95:         #really only 1 space, in both the answer and the response
   96: 	$answer=~s/ +/ /g;
   97: 	$response=~s/ +/ /g;
   98:     } elsif ($type eq 'mc') {
   99: 	$answer=~s/[\s,]//g;
  100: 	$response=~s/[\s,]//g;
  101:     }
  102:     if ($type eq 'float' && $unit=~/\$/) {
  103: 	if ($response!~/^\$/)  { return "NO_UNIT: Missing \$ "; }
  104: 	$response=~s/\$//g;
  105:     }
  106:     if ($type eq 'float' && $unit=~/\,/ && (&check_commas($response)<0)) {
  107: 	return "COMMA_FAIL:";
  108:     }
  109:     $ans_fmt=~s/\W//g;
  110:     $unit=~s/[\$,]//g;
  111:     if ($type eq 'float') { $response=~s/,//g; }
  112: 
  113:     if (length($response) > 500) { return "TOO_LONG: Answer too long"; }
  114: 
  115:     if ($type eq '' ) {
  116: 	$message .= "Didn't find a type :$type: defaulting\n";
  117: 	if ( $answer eq ($answer *1.0)) { $type = 2;
  118: 				      } else { $type = 3; }
  119:     } else {
  120: 	if    ($type eq 'cs')    { $type = 4; }
  121: 	elsif ($type eq 'ci')    { $type = 3 }
  122: 	elsif ($type eq 'mc')    { $type = 5; }
  123: 	elsif ($type eq 'fml')   { $type = 8; }
  124:         elsif ($type eq 'math')  { $type = 9; }
  125: 	elsif ($type eq 'subj')  { $type = 7; }
  126: 	elsif ($type eq 'float') { $type = 2; }
  127: 	elsif ($type eq 'int')   { $type = 1; }
  128: 	else { return "ERROR: Unknown type of answer: $type" }
  129:     }
  130: 
  131:     my $points;
  132:     my $id_list;
  133:     #formula type setup the sample points
  134:     if ($type eq '8') {
  135: 	($id_list,$points)=split(/@/,$samples);
  136: 	$message.="Found :$id_list:$points: points in $samples\n";
  137:     }
  138:     if ($tol eq '') {
  139: 	$tol=0.0;
  140: 	$tol_type=1; #TOL_ABSOLUTE
  141:     } else {
  142: 	if ($tol =~ /%$/) {
  143: 	    chop $tol;
  144: 	    $tol_type=2; #TOL_PERCENTAGE
  145: 	} else {
  146: 	    $tol_type=1; #TOL_ABSOLUTE
  147: 	}
  148:     }
  149: 
  150:     ($sig_ubound,$sig_lbound)=&LONCAPA_INTERNAL_get_sigrange($sig);
  151: 
  152:     my $reterror="";
  153:     my $result;
  154:     if ($type eq '9') {
  155:       $result = &maxima_check(&maxima_cas_formula_fix($response),&maxima_cas_formula_fix($answer),\$reterror);
  156:     } else {
  157: 	if ($type eq '8') { # fml type
  158: 	    $response = &capa_formula_fix($response);
  159: 	    $answer   = &capa_formula_fix($answer);
  160: 	}
  161:        $result = &caparesponse_capa_check_answer($response,$answer,$type,
  162: 						 $tol_type,$tol,
  163: 						 $sig_lbound,$sig_ubound,
  164: 						 $ans_fmt,$unit,$calc,$id_list,
  165: 						 $points,$external::randomseed,
  166: 						 \$reterror);
  167:     }
  168:     if    ($result == '1') { $result='EXACT_ANS'; } 
  169:     elsif ($result == '2') { $result='APPROX_ANS'; }
  170:     elsif ($result == '3') { $result='SIG_FAIL'; }
  171:     elsif ($result == '4') { $result='UNIT_FAIL'; }
  172:     elsif ($result == '5') { $result='NO_UNIT'; }
  173:     elsif ($result == '6') { $result='UNIT_OK'; }
  174:     elsif ($result == '7') { $result='INCORRECT'; }
  175:     elsif ($result == '8') { $result='UNIT_NOTNEEDED'; }
  176:     elsif ($result == '9') { $result='ANS_CNT_NOT_MATCH'; }
  177:     elsif ($result =='10') { $result='SUB_RECORDED'; }
  178:     elsif ($result =='11') { $result='BAD_FORMULA'; }
  179:     elsif ($result =='12' && !$response) { $result='MISSING_ANSWER'; }
  180:     elsif ($result =='12') { $result='WANTED_NUMERIC'; }
  181:     elsif ($result =='13') { $result='UNIT_INVALID_INSTRUCTOR'; }
  182:     elsif ($result =='141') { $result='UNIT_INVALID_STUDENT'; }
  183:     elsif ($result =='142') { $result='UNIT_INVALID_STUDENT'; }
  184:     elsif ($result =='143') { $result='UNIT_INVALID_STUDENT'; }
  185:     elsif ($result =='15') { $result='UNIT_IRRECONCIBLE'; }
  186:     else  {$result = "ERROR: Unknown Result:$result:$@:";}
  187: 
  188:     return ("$result:\nRetError $reterror:\nAnswer $answer:\nResponse $response:\n type-$type|$tol|$tol_type|$sig:$sig_lbound:$sig_ubound|$unit|\n$message",$reterror);
  189: }
  190: 
  191: sub maxima_cas_formula_fix {
  192:    my ($expression)=@_;
  193:    return &implicit_multiplication($expression);
  194: }
  195: 
  196: sub capa_formula_fix {
  197:    my ($expression)=@_;
  198:    return &implicit_multiplication($expression);
  199: }
  200: 
  201: sub implicit_multiplication {
  202:     my ($expression)=@_;
  203: # Escape scientific notation, so 3e8 does not become 3*e*8
  204: # 3e8 -> 3&8; 3e-8 -> 3&-8; 3E+8 -> e&+8
  205:     $expression=~s/(\d+)e([\+\-]*\d+)/$1\&\($2\)/gsi;
  206: # 3x10^8 -> 3&8; 3*10^-8 -> 3&-8
  207:     $expression=~s/(\d+)(?:x|\*)10(?:\^|\*\*)([\+\-]*\d+)/$1\&\($2\)/gsi;
  208: # Fill in multiplication signs
  209: # a b -> a*b;3 b -> 3*b;3 4 -> 3*4
  210:     $expression=~s/(\w)\s+(\w)/$1\*$2/gs;
  211: # )( -> )*(; ) ( -> )*(
  212:     $expression=~s/\)\s*\(/\)\*\(/gs;
  213: # 3a -> 3*a; 3( -> 3*(; 3 ( -> 3*(; 3A -> 3*A
  214:     $expression=~s/(\d)\s*([a-zA-Z\(])/$1\*$2/gs;
  215: # a ( -> a*(
  216:     $expression=~s/(\w)\s+\(/$1\*\(/gs;
  217: # a3 -> a*3;
  218:     $expression=~s/([a-zA-Z])(\d)/$1\*$2/gs;
  219: # )a -> )*a; )3 -> )*3; ) 3 -> )*3
  220:     $expression=~s/\)\s*(\w)/\)\*$1/gs;
  221: # 3&8 -> 3e8; 3&-4 -> 3e-4
  222:     $expression=~s/(\d+)\&\(([\+\-]*\d+)\)/$1e$2/gs;
  223:     return $expression;
  224: }
  225: 
  226: sub caparesponse_check_list {
  227:     my $response=$LONCAPA::CAPAresponse_args{'response'};
  228:     my $result="Got response :".join(':',@LONCAPA::CAPAresponse_answer).":\n";
  229:     &LONCAPA_INTERNAL_DEBUG("args ".join(':',%LONCAPA::CAPAresponse_args));
  230:     my @responselist;
  231:     my $type = $LONCAPA::CAPAresponse_args{'type'};
  232:     $result.="Got type :$type:\n";
  233:     if ($type ne '' && $#LONCAPA::CAPAresponse_answer > 0) {
  234: 	(@responselist)=split(/,/,$response);
  235: 	if (@responselist < @LONCAPA::CAPAresponse_answer) {
  236: 	    return 'MISSING_ANSWER';
  237: 	}
  238: 	if (@responselist > @LONCAPA::CAPAresponse_answer) {
  239: 	    return 'EXTRA_ANSWER';
  240: 	}
  241:     } else {
  242: 	(@responselist)=($response);
  243:     }
  244:     $result.="Initial final response :$responselist['-1']:\n";
  245:     my $unit;
  246:     if ($type eq '' || $type eq 'float') {
  247: 	#for numerical problems split off the unit
  248: 	if ( $responselist['-1']=~ /(.*[^\s])\s+([^\s]+)/ ) {
  249: 	    $responselist['-1']=$1;
  250: 	    $unit=$2;
  251: 	}
  252:     }
  253:     $result.="Final final response :$responselist['-1']:$unit:\n";
  254:     $unit=~s/\s//;
  255: 
  256:     my ($awards, @msgs, $i);
  257:     foreach my $thisanswer (@LONCAPA::CAPAresponse_answer) {
  258: 	my ($msg,$aresult);
  259: 	$result.="trying answer :$thisanswer:\n";
  260: 	if (defined($thisanswer)) {
  261: 	    if ($unit eq '') {
  262: 		($aresult,$msg)=&caparesponse_check($thisanswer,
  263: 						    $responselist[$i]);
  264: 	    } else {
  265: 		($aresult,$msg)=&caparesponse_check($thisanswer,
  266: 						    $responselist[$i]." $unit");
  267: 	    }
  268: 	} else {
  269: 	    $aresult='ERROR';
  270: 	    $msg='answer was undefined';
  271: 	}
  272: 	&LONCAPA_INTERNAL_DEBUG("after if $aresult -- $msg");
  273: 	my ($temp)=split(/:/, $aresult);
  274: 	$awards.="$temp,";
  275: 	$result.=$aresult;
  276: 	push(@msgs,$msg);
  277: 	$i++;
  278:     }
  279:     chop($awards);
  280:     return ("$awards:\n$result",@msgs);
  281: }
  282: 
  283: sub tex {
  284:     if ( $external::target eq "tex" ) {
  285: 	return $_[0];
  286:     } else {
  287: 	return $_[1];
  288:     }
  289: }
  290: 
  291: sub var_in_tex {
  292:     if ( $external::target eq "tex" ) {
  293: 	return $_[0];
  294:     } else {
  295: 	return "";
  296:     }
  297: }
  298: 
  299: sub web {
  300:     if ( $external::target eq "tex" ) {
  301: 	return $_[1];
  302:     } else {
  303: 	if ( $external::target eq "web" || $external::target eq "answer") {
  304: 	    return $_[2];
  305: 	} else {
  306: 	    return $_[0];
  307: 	}
  308:     }
  309: }
  310: 
  311: sub html {
  312:     if ( $external::target eq "web" ) {
  313: 	return shift;
  314:     }
  315: }
  316: 
  317: sub hinton {
  318:     return 0;
  319: }
  320: 
  321: sub random {
  322:     my ($start,$end,$step)=@_;
  323:     if ( ! $hidden::RANDOMINIT ) {
  324: 	if ($external::randomseed == 0) { $external::randomseed=1; }
  325: 	if ($external::randomseed =~/,/) {
  326: 	    my ($num1,$num2)=split(/,/,$external::randomseed);
  327: 	    &random_set_seed(1,abs($num1));
  328: 	} elsif ($external::randomseed =~/:/) {
  329: 	    my ($num1,$num2)=split(/:/,$external::randomseed);
  330: 	    &random_set_seed(abs($num1),abs($num2));
  331: 	} else {
  332: 	    &random_set_seed(1,int(abs($external::randomseed)));
  333: 	}
  334: 	&math_random_uniform();
  335: 	$hidden::RANDOMINIT=1;
  336:     }
  337:     if (!defined($step)) { $step=1; }
  338:     my $num=1+int(($end-$start)/$step);
  339:     my $result=$start + int(&math_random_uniform() * $num)*$step;
  340:     return $result;
  341: }
  342: 
  343: sub random_normal {
  344:     my ($item_cnt,$seed,$av,$std_dev) = @_;
  345:     my @oldseed=&random_get_seed();
  346:     my @retArray;
  347:     &random_set_seed_from_phrase($seed);
  348:     @retArray=&math_random_normal($item_cnt,$av,$std_dev);
  349:     &random_set_seed(@oldseed);
  350:     return @retArray;
  351: }
  352: 
  353: sub random_beta {
  354:     my ($item_cnt,$seed,$aa,$bb) = @_;
  355:     my @oldseed=&random_get_seed();
  356:     my @retArray;
  357:     &random_set_seed_from_phrase($seed);
  358:     @retArray=&math_random_beta($item_cnt,$aa,$bb);
  359:     &random_set_seed(@oldseed);
  360:     return @retArray;
  361: }
  362: 
  363: sub random_gamma {
  364:     my ($item_cnt,$seed,$a,$r) = @_;
  365:     my @oldseed=&random_get_seed();
  366:     my @retArray;
  367:     &random_set_seed_from_phrase($seed);
  368:     @retArray=&math_random_gamma($item_cnt,$a,$r);
  369:     &random_set_seed(@oldseed);
  370:     return @retArray;
  371: }
  372: 
  373: sub random_exponential {
  374:     my ($item_cnt,$seed,$av) = @_;
  375:     my @oldseed=&random_get_seed();
  376:     my @retArray;
  377:     &random_set_seed_from_phrase($seed);
  378:     @retArray=&math_random_exponential($item_cnt,$av);
  379:     &random_set_seed(@oldseed);
  380:     return @retArray;
  381: }
  382: 
  383: sub random_poisson {
  384:     my ($item_cnt,$seed,$mu) = @_;
  385:     my @oldseed=&random_get_seed();
  386:     my @retArray;
  387:     &random_set_seed_from_phrase($seed);
  388:     @retArray=&math_random_poisson($item_cnt,$mu);
  389:     &random_set_seed(@oldseed);
  390:     return @retArray;
  391: }
  392: 
  393: sub random_chi {
  394:     my ($item_cnt,$seed,$df) = @_;
  395:     my @oldseed=&random_get_seed();
  396:     my @retArray;
  397:     &random_set_seed_from_phrase($seed);
  398:     @retArray=&math_random_chi_square($item_cnt,$df);
  399:     &random_set_seed(@oldseed);
  400:     return @retArray;
  401: }
  402: 
  403: sub random_noncentral_chi {
  404:     my ($item_cnt,$seed,$df,$nonc) = @_;
  405:     my @oldseed=&random_get_seed();
  406:     my @retArray;
  407:     &random_set_seed_from_phrase($seed);
  408:     @retArray=&math_random_noncentral_chi_square($item_cnt,$df,$nonc);
  409:     &random_set_seed(@oldseed);
  410:     return @retArray;
  411: }
  412: 
  413: sub random_f {
  414:     my ($item_cnt,$seed,$dfn,$dfd) = @_;
  415:     my @oldseed=&random_get_seed();
  416:     my @retArray;
  417:     &random_set_seed_from_phrase($seed);
  418:     @retArray=&math_random_f($item_cnt,$dfn,$dfd);
  419:     &random_set_seed(@oldseed);
  420:     return @retArray;
  421: }
  422: 
  423: sub random_noncentral_f {
  424:     my ($item_cnt,$seed,$dfn,$dfd,$nonc) = @_;
  425:     my @oldseed=&random_get_seed();
  426:     my @retArray;
  427:     &random_set_seed_from_phrase($seed);
  428:     @retArray=&math_random_noncentral_f($item_cnt,$dfn,$dfd,$nonc);
  429:     &random_set_seed(@oldseed);
  430:     return @retArray;
  431: }
  432: 
  433: sub random_multivariate_normal {
  434:     my ($item_cnt,$seed,$mean,$covar) = @_;
  435:     my @oldseed=&random_get_seed();
  436:     &random_set_seed_from_phrase($seed);
  437:     my @retArray=&math_random_multivariate_normal($item_cnt,@$mean,@$covar);
  438:     &random_set_seed(@oldseed);
  439:     return @retArray;
  440: }
  441: 
  442: sub random_multinomial {
  443:     my ($item_cnt,$seed,@p) = @_;
  444:     my @oldseed=&random_get_seed();
  445:     my @retArray;
  446:     &random_set_seed_from_phrase($seed);
  447:     my @retArray=&math_random_multinomial($item_cnt,@p);
  448:     &random_set_seed(@oldseed);
  449:     return @retArray;
  450: }
  451: 
  452: sub random_permutation {
  453:     my ($seed,@inArray) = @_;
  454:     my @oldseed=&random_get_seed();
  455:     my @retArray;
  456:     &random_set_seed_from_phrase($seed);
  457:     @retArray=&math_random_permutation(@inArray);
  458:     &random_set_seed(@oldseed);
  459:     return @retArray;
  460: }
  461: 
  462: sub random_uniform {
  463:     my ($item_cnt,$seed,$low,$high) = @_;
  464:     my @oldseed=&random_get_seed();
  465:     my @retArray;
  466:     &random_set_seed_from_phrase($seed);
  467:     @retArray=&math_random_uniform($item_cnt,$low,$high);
  468:     &random_set_seed(@oldseed);
  469:     return @retArray;
  470: }
  471: 
  472: sub random_uniform_integer {
  473:     my ($item_cnt,$seed,$low,$high) = @_;
  474:     my @oldseed=&random_get_seed();
  475:     my @retArray;
  476:     &random_set_seed_from_phrase($seed);
  477:     @retArray=&math_random_uniform_integer($item_cnt,$low,$high);
  478:     &random_set_seed(@oldseed);
  479:     return @retArray;
  480: }
  481: 
  482: sub random_binomial {
  483:     my ($item_cnt,$seed,$nt,$p) = @_;
  484:     my @oldseed=&random_get_seed();
  485:     my @retArray;
  486:     &random_set_seed_from_phrase($seed);
  487:     @retArray=&math_random_binomial($item_cnt,$nt,$p);
  488:     &random_set_seed(@oldseed);
  489:     return @retArray;
  490: }
  491: 
  492: sub random_negative_binomial {
  493:     my ($item_cnt,$seed,$ne,$p) = @_;
  494:     my @oldseed=&random_get_seed();
  495:     my @retArray;
  496:     &random_set_seed_from_phrase($seed);
  497:     @retArray=&math_random_negative_binomial($item_cnt,$ne,$p);
  498:     &random_set_seed(@oldseed);
  499:     return @retArray;
  500: }
  501: 
  502: sub abs { CORE::abs(shift) }
  503: sub sin { CORE::sin(shift) }
  504: sub cos { CORE::cos(shift) }
  505: sub exp { CORE::exp(shift) }
  506: sub int { CORE::int(shift) }
  507: sub log { CORE::log(shift) }
  508: sub atan2 { CORE::atan2($_[0],$_[1]) }
  509: sub sqrt { CORE::sqrt(shift) }
  510: 
  511: sub tan  { CORE::sin($_[0]) / CORE::cos($_[0]) }
  512: #sub atan { atan2($_[0], 1); }
  513: #sub acos { atan2(sqrt(1 - $_[0] * $_[0]), $_[0] ); }
  514: #sub asin { atan2($_[0], sqrt(1- $_[0] * $_[0]) );  }
  515: 
  516: sub log10 { CORE::log($_[0])/CORE::log(10); }
  517: 
  518: sub factorial {
  519:     my $input = CORE::int(shift);
  520:     return "Error - unable to take factorial of an negative number ($input)" if $input < 0;
  521:     return "Error - factorial result is greater than system limit ($input)" if $input > 170;
  522:     return 1 if $input == 0;
  523:     my $result = 1; 
  524:     for (my $i=2; $i<=$input; $i++) { $result *= $i }
  525:     return $result;
  526: }
  527: 
  528: sub sgn {
  529:     return -1 if $_[0] < 0;
  530:     return 0 if $_[0] == 0;
  531:     return 1 if $_[0] > 0;
  532: }
  533: 
  534: sub min {
  535:     my @sorted = sort { $a <=> $b || $a cmp $b } @_;
  536:     return shift @sorted;
  537: }
  538: 
  539: sub max {
  540:     my @sorted = sort { $a <=> $b || $a cmp $b } @_;
  541:     return pop @sorted;
  542: }
  543: 
  544: sub roundto {
  545:     my ($input,$n) = @_;
  546:     return sprintf('%.'.$n.'f',$input);
  547: }
  548: 
  549: sub to_string {
  550:     my ($input,$n) = @_;
  551:     return sprintf($input) if $n eq "";
  552:     $n = '.'.$n if $n !~ /^\./;
  553:     return sprintf('%'.$n,$input) if $n ne "";
  554: }
  555: 
  556: sub sub_string {
  557:     my ($str,$start,$len) = @_;
  558:     return substr($str,$start-1,$len);
  559: }
  560: 
  561: sub pow   {return $_[0] ** $_[1]; }
  562: sub ceil  {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? (CORE::int($_[0])+ 1) : CORE::int($_[0])); }
  563: sub floor  {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? CORE::int($_[0]) : (CORE::int($_[0])-1)); }
  564: #sub floor {return int($_[0]); }
  565: 
  566: sub format {
  567:     my ($value,$fmt)=@_;
  568:     my ($dollarmode,$commamode,$alwaysperiod,$options);
  569:     if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; } 
  570:     #if ($options =~ /\$/) { $dollamode=1; }
  571:     #if ($options =~ /,/)  { $commamode=1; }
  572:     if ($options =~ /\./) { $alwaysperiod=1; }
  573:     my $result;
  574:     if ($fmt=~/s$/i) {
  575: 	$result=&format_significant_figures($value,$fmt);
  576:     } else {
  577: 	$fmt=~s/e/E/g;
  578: 	$result=sprintf('%.'.$fmt,$value);
  579: 	if ($alwaysperiod && $fmt eq '0f') { $result .='.'; }
  580: 	$result=~s/(E[+-]*)0/$1/;
  581:     }
  582:     #if ($dollarmode) {$result=&dollarformat($result);}
  583:     #if ($commamode) {$result=&commaformat($result);}
  584:     return $result;
  585: }
  586: 
  587: sub chemparse {
  588:     my ($reaction) = @_;
  589:     my @tokens = split(/(\s\+|\->|<=>|<\-|\.)/,$reaction);
  590:     my $formula = '';
  591:     foreach my $token (@tokens) {
  592: 	if ($token eq '->' ) {
  593: 	    $formula .= '<m>\ensuremath{\rightarrow}</m> ';
  594: 	    next;
  595: 	}
  596: 	if ($token eq '<-' ) {
  597: 	    $formula .= '<m>\ensuremath{\leftarrow}</m> ';
  598: 	    next;
  599: 	}  
  600: 	if ($token eq '<=>') {
  601: 	    if ($external::target eq 'web' &&
  602: 		&EXT('request.browser.unicode')) {
  603: 		$formula .= '&#8652; ';
  604: 	    } else {
  605: 		$formula .= &web('<=> ','<m>\ensuremath{\rightleftharpoons}</m> ',
  606: 				 '&lt;=&gt; ');
  607: 	    }
  608: 	    next;
  609: 	}
  610: 	if ($token eq '.') {
  611: 	  $formula =~ s/(\&nbsp\;| )$//;
  612: 	  $formula .= '&middot;';
  613: 	  next;
  614: 	}
  615: 	$token =~ /^\s*([\d|\/]*(?:&frac\d\d)?)(.*)/;
  616:         $formula .= $1 if ($1 ne '1');  # stoichiometric coefficient
  617: 	
  618: 	my $molecule = $2;
  619: 	# subscripts
  620: 	$molecule =~ s|(?<=[a-zA-Z\)\]\s])(\d+)|<sub>$1</sub>|g;
  621: 	# superscripts
  622: 	$molecule =~ s|\^(\d*[+\-]*)|<sup>$1</sup>|g;
  623: 	# strip whitespace
  624: 	$molecule =~ s/\s*//g;
  625: 	# forced space
  626: 	$molecule =~ s/_/ /g;
  627: 	$molecule =~ s/-/&minus;/g;
  628: 	$formula .= $molecule.'&nbsp;';
  629:     }
  630:     # get rid of trailing space
  631:     $formula =~ s/(\&nbsp\;| )$//;
  632:     return &xmlparse($formula);
  633: }
  634: 
  635: sub prettyprint {
  636:     my ($value,$fmt,$target)=@_;
  637:     my $result;
  638:     if (!$target) { $target = $external::target; }
  639:     if ($fmt =~ /chem/i) { return(&chemparse($value)); }
  640:     my ($dollarmode,$commamode,$alwaysperiod,$options);
  641:     if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; } 
  642:     if ($options =~ /\$/) { $dollarmode=1; }
  643:     if ($options =~ /,/)  { $commamode=1; }
  644:     if ($options =~ /\./) { $alwaysperiod=1; }
  645:     if ($fmt=~/s$/i) {
  646: 	$value=&format_significant_figures($value,$fmt);
  647:     } elsif ($fmt) {
  648: 	$value=sprintf('%.'.$fmt,$value);
  649:     }
  650:     if ($alwaysperiod && $fmt eq '0f') {
  651: 	if ($target eq 'tex') {
  652: 	    $value .='\\ensuremath{.}';
  653: 	} else {
  654: 	    $value .='.';
  655: 	}
  656:     }
  657:     if ($value =~ /([0-9\.\-\+]+)E([0-9\-\+]+)/i ) {
  658: 	my $frac=$1;
  659: 	if ($dollarmode) { $frac=&dollarformat($frac); }
  660: 	if ($commamode) { $frac=&commaformat($frac); }
  661: 	my $exponent=$2;
  662: 	$exponent=~s/^\+0*//;
  663: 	$exponent=~s/^-0*/-/;
  664: 	$exponent=~s/^-0*/-/;
  665: 	if ($exponent eq '-') { undef($exponent); }
  666: 	if ($exponent) {
  667: 	    if ($target eq 'web') {
  668: 		$result=$frac.'&#215;10<sup>'.$exponent.'</sup>';
  669: 	    } elsif ($target eq 'tex') {
  670: 		$result='\ensuremath{'.$frac.'\times 10^{'.$exponent.'}}';
  671: 	    } else {
  672: 		$result=$value;
  673: 	    }
  674: 	} else {
  675: 	    $result=$frac;
  676: 	}
  677:     } else {
  678: 	$result=$value;
  679: 	if    ($dollarmode) { $result=&dollarformat($result,$target); }
  680: 	elsif ($commamode)  { $result=&commaformat($result,$target); }
  681:     }
  682:     return $result;
  683: }
  684: 
  685: sub commaformat {
  686:     my ($number,$target) = @_;
  687:     if ($number =~ /\./) {
  688: 	while ($number =~ /([^0-9]*)([0-9]+)([^\.,][^\.,][^\.,])([,0-9]*\.[0-9]*)$/) {
  689: 	    $number = $1.$2.','.$3.$4;
  690: 	}
  691:     } else {
  692: 	while ($number =~ /^([^0-9]*)([0-9]+)([^,][^,][^,])([,0-9]*)$/) {
  693: 	    $number = $1.$2.','.$3.$4;
  694: 	}
  695:     }
  696:     return $number;
  697: }
  698: 
  699: sub dollarformat {
  700:     my ($number,$target) = @_;
  701:     if (!$target) { $target = $external::target; }
  702:     $number=&commaformat($number,$target);
  703:     if ($target eq 'tex') {
  704: 	$number='\$'.$number; #' stupid emacs
  705:     } else {
  706: 	$number='$'.$number; #' stupid emacs
  707:     }
  708:     return $number; 
  709: }
  710: 
  711: # format of form ns or nS where n is an integer
  712: sub format_significant_figures {
  713:     my ($number,$format) = @_; 
  714:     return '0' if ($number == 0);
  715:     # extract number of significant figures needed
  716:     my ($sig) = ($format =~ /(\d+)s/i);
  717:     # arbitrary choice - suggestions ?? or throw error message?
  718:     $sig = 3 if ($sig eq '');
  719:     # save the minus sign
  720:     my $sign = ($number < 0) ? '-' : '';
  721:     $number = abs($number);
  722:     # needed to correct for a number greater than 1 (or
  723:     my $power = ($number < 1) ? 0 : 1;
  724:     # could round up. Take the integer part of log10.
  725:     my $x10 = int(log($number)/log(10));
  726:     # find number with values left of decimal pt = # of sign figs.
  727:     my $xsig = $number*10**($sig-$x10-$power);
  728:     # get just digits left of decimal pt - also rounds off correctly
  729:     my $xint  = sprintf('%.0f',$xsig);
  730:     # save any trailing zero's
  731:     my ($zeros) = ($xint =~ /(0+)$/);
  732:     # return number to original magnitude
  733:     my $numSig = $xint*10**($x10-$sig+$power);
  734:     # insert trailing zero's if have decimal point
  735:     $numSig =~ s/^(\d+)\.(\d+)(\e?(.*)?)$/$1\.$2$zeros$3/;
  736:     # put a decimal pt for number ending with 0 and length = # of sig fig
  737:     $numSig.='.' if (length($numSig) == $sig && $numSig =~ /0$/);
  738:     if (length($numSig) < $sig) {
  739: 	$numSig.='.'.substr($zeros,0,($sig-length($numSig)));
  740:     }
  741:     # return number with sign
  742:     return $sign.$numSig;
  743: 
  744: }
  745: 
  746: sub map {
  747:     my ($phrase,$dest,$source)=@_;
  748:     my @oldseed=&random_get_seed();
  749:     my @seed = &random_seed_from_phrase($phrase);
  750:     &random_set_seed(@seed);
  751:     my $destct = scalar(@$dest);
  752:     if (!$source) {
  753: 	my @output;
  754: 	my @idx = &math_random_permuted_index($destct);
  755: 	my $ctr = 0;
  756: 	while ($ctr < $destct) {
  757: 	    $output[$ctr] = $$dest[$idx[$ctr]];
  758: 	    $ctr++;
  759: 	}
  760:         &random_set_seed(@oldseed);
  761: 	return @output;
  762:     } else {
  763: 	my $num = scalar(@$source);
  764: 	my @idx = &math_random_permuted_index($num);
  765: 	my $ctr = 0;
  766: 	my $tot = $num;
  767: 	$tot = $destct if $destct < $num;
  768: 	if (ref($$dest[0])) {
  769: 	    while ($ctr < $tot) {
  770: 		${$$dest[$ctr]} = $$source[$idx[$ctr]];
  771: 	        $ctr++;
  772:             }
  773:         } else {
  774: 	    while ($ctr < $tot) {
  775: 		$$dest[$ctr] = $$source[$idx[$ctr]];
  776: 		$ctr++;
  777: 	    }
  778: 	}
  779:     }
  780:     &random_set_seed(@oldseed);
  781:     return '';
  782: }
  783: 
  784: sub rmap {
  785:     my ($phrase,$dest,$source)=@_;
  786:     my @oldseed=&random_get_seed();
  787:     my @seed = &random_seed_from_phrase($phrase);
  788:     &random_set_seed(@seed);
  789:     my $destct = scalar(@$dest);
  790:     if (!$source) {
  791: 	my @idx = &math_random_permuted_index($destct);
  792: 	my $ctr = 0;
  793: 	my @r_idx;
  794: 	while ($ctr < $destct) {
  795: 	    $r_idx[$idx[$ctr]] = $ctr;
  796: 	    $ctr++;
  797: 	}
  798: 	my @output;
  799: 	$ctr = 0;
  800: 	while ($ctr < $destct) {
  801: 	    $output[$ctr] = $$dest[$r_idx[$ctr]];
  802: 	    $ctr++;
  803: 	}
  804:         &random_set_seed(@oldseed);
  805: 	return @output;
  806:     } else {
  807: 	my $num = scalar(@$source);
  808: 	my @idx = &math_random_permuted_index($num);
  809: 	my $ctr = 0;
  810: 	my $tot = $num;
  811: 	$tot = $destct if $destct < $num;
  812: 	my @r_idx;
  813: 	while ($ctr < $tot) {
  814: 	    $r_idx[$idx[$ctr]] = $ctr;
  815: 	    $ctr++;
  816: 	}
  817: 	$ctr = 0;
  818: 	if (ref($$dest[0])) {
  819: 	    while ($ctr < $tot) {
  820: 		${$$dest[$ctr]} = $$source[$r_idx[$ctr]];
  821: 	        $ctr++;
  822:             }
  823:         } else {
  824: 	    while ($ctr < $tot) {
  825: 		$$dest[$ctr] = $$source[$r_idx[$ctr]];
  826: 		$ctr++;
  827: 	    }
  828: 	}
  829:     }
  830:     &random_set_seed(@oldseed);
  831:     return '';
  832: }
  833: 
  834: sub capa_id { return }
  835: 
  836: sub problem { return }
  837: 
  838: sub name{
  839:     my $fullname = &EXT('environment.lastname').', '.&EXT('environment.firstname').' '.&EXT('environment.middlename');
  840:     $fullname = "" if $fullname eq ",  ";
  841:     $fullname =~ s/\%2d/-/g;
  842:     return $fullname;
  843: }
  844: 
  845: sub student_number { 
  846:     my $id = &EXT('environment.id');
  847:     $id = '' if $id eq "";
  848:     return $id;
  849: }
  850: 
  851: sub class {
  852:     my $course = &EXT('course.description');
  853:     $course = '' if $course eq "";
  854:     return $course;
  855: }
  856: 
  857: sub firstname {
  858:     my $firstname = &EXT('environment.firstname');
  859:     $firstname = '' if $firstname eq "";
  860:     return $firstname;
  861: }
  862:                                                                                 
  863: sub lastname {
  864:     my $lastname = &EXT('environment.lastname');
  865:     $lastname = '' if $lastname eq "";
  866:     return $lastname;
  867: }
  868: 
  869: sub sec { 
  870:     my $sec = &EXT('request.course.sec');
  871:     $sec = '' if $sec eq "";
  872:     return $sec;
  873: }
  874: 
  875: sub open_date { 
  876:     my @dc = split(/\s+/,localtime(&EXT('resource.0.opendate')));
  877:     return '' if ($dc[0] eq "Wed" and $dc[2] == 31 and $dc[4] == 1969);
  878:     my @hm = split(/:/,$dc[3]);
  879:     my $ampm = " am";
  880:     if ($hm[0] > 12) {
  881: 	$hm[0]-=12;
  882: 	$ampm = " pm";
  883:     }
  884:     return $dc[0].', '.$dc[1].' '.$dc[2].', '.$dc[4].' at '.$hm[0].':'.$hm[1].$ampm;
  885: }
  886: 
  887: sub due_date { 
  888:     my @dc = split(/\s+/,localtime(&EXT('resource.0.duedate')));
  889:     return '' if ($dc[0] eq "Wed" and $dc[2] == 31 and $dc[4] == 1969);
  890:     my @hm = split(/:/,$dc[3]);
  891:     my $ampm = " am";
  892:     if ($hm[0] > 12) {
  893: 	$hm[0]-=12;
  894: 	$ampm = " pm";
  895:     }
  896:     return $dc[0].', '.$dc[1].' '.$dc[2].', '.$dc[4].' at '.$hm[0].':'.$hm[1].$ampm;
  897: }
  898: 
  899: sub answer_date { 
  900:     my @dc = split(/\s+/,localtime(&EXT('resource.0.answerdate')));
  901:     return '' if ($dc[0] eq "Wed" and $dc[2] == 31 and $dc[4] == 1969);
  902:     my @hm = split(/:/,$dc[3]);
  903:     my $ampm = " am";
  904:     if ($hm[0] > 12) {
  905: 	$hm[0]-=12;
  906: 	$ampm = " pm";
  907:     }
  908:     return $dc[0].', '.$dc[1].' '.$dc[2].', '.$dc[4].' at '.$hm[0].':'.$hm[1].$ampm;
  909: }
  910: 
  911: sub array_moments {
  912:     my @input=@_;
  913:     my (@output,$N);
  914:     $N=scalar (@input);
  915:     $output[0]=$N;
  916:     if ($N <= 1) {
  917: 	$output[1]=$input[0];
  918: 	$output[1]="Input array not defined" if ($N == 0);
  919: 	$output[2]="variance undefined for N<=1";
  920: 	$output[3]="skewness undefined for N<=1";
  921: 	$output[4]="kurtosis undefined for N<=1";
  922: 	return @output;
  923:     }
  924:     my $sum=0;
  925:     foreach my $line (@input) {
  926: 	$sum+=$line;
  927:     }
  928:     $output[1] = $sum/$N;
  929:     my ($x,$sdev,$var,$skew,$kurt) = 0;
  930:     foreach my $line (@input) {
  931: 	$x=$line-$output[1];
  932: 	$var+=$x**2;
  933: 	$skew+=$x**3;
  934: 	$kurt+=$x**4;
  935:     }
  936:     $output[2]=$var/($N-1);
  937:     $sdev=CORE::sqrt($output[2]);
  938:     if ($sdev == 0) {
  939: 	$output[3]="inf-variance=0";
  940: 	$output[4]="inf-variance=0";
  941: 	return @output;
  942:     }
  943:     $output[3]=$skew/($sdev**3*$N);
  944:     $output[4]=$kurt/($sdev**4*$N)-3;
  945:     return @output;
  946: }
  947: 
  948: sub choose {
  949:     my $num = $_[0];
  950:     return $_[$num];
  951: }
  952: 
  953: #&sum1(1,$x,sub { &sum1($_[0],2*$_[0], sub { fact($_[0])**2 })});
  954: #sub sum1 {
  955: #    my ($start,$end,$sub)=@_;
  956: #    my $sum=0;
  957: #    for (my $i=$start;$i<=$end;$i++) {
  958: #        $sum+=&$sub($i);
  959: #    }
  960: #    return $sum
  961: #}
  962: 
  963: #&sum2('a',1,$x,'&sum2(\'b\',$a,2*$a, \'&factorial($b)**2\')');
  964: #sub sum2 {
  965: #    my ($varname,$start,$end,$line)=@_;
  966: #    my $sum=0;
  967: #    for (my $i=$start;$i<=$end;$i++) {
  968: #	my $func=sub {
  969: #	    eval("\$".$varname."=$i");
  970: #	    eval($line);
  971: #	};
  972: #        $sum+=&$func($i);
  973: #    }
  974: #    return $sum
  975: #}
  976: 
  977: # expiremental idea
  978: sub proper_path {
  979:     my ($path)=@_;
  980:     if ( $external::target eq "tex" ) {
  981: 	return '/home/httpd/html'.$path;
  982:     } else {
  983: 	return $path;
  984:     }
  985: }
  986: 

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