File:  [LON-CAPA] / loncom / homework / default_homework.lcpm
Revision 1.110: download - view: text, annotated - select for diffs
Mon Jul 17 21:11:21 2006 UTC (17 years, 9 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #4910: also in formula_response, 3e8 should not be turned into 3*e*8

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

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