Annotation of loncom/homework/default_homework.lcpm, revision 1.109

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

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