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

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.110   ! www         4: # $Id: default_homework.lcpm,v 1.109 2006/07/05 19:01:44 albertel 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)=@_;
1.110   ! www       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;
1.108     www       210:     return $expression;
                    211: }
1.73      albertel  212: 
1.37      albertel  213: sub caparesponse_check_list {
1.74      albertel  214:     my $response=$LONCAPA::CAPAresponse_args{'response'};
1.105     albertel  215:     my $result="Got response :".join(':',@LONCAPA::CAPAresponse_answer).":\n";
                    216:     &LONCAPA_INTERNAL_DEBUG("args ".join(':',%LONCAPA::CAPAresponse_args));
1.73      albertel  217:     my @responselist;
1.74      albertel  218:     my $type = $LONCAPA::CAPAresponse_args{'type'};
1.73      albertel  219:     $result.="Got type :$type:\n";
1.105     albertel  220:     if ($type ne '' && $#LONCAPA::CAPAresponse_answer > 0) {
1.104     albertel  221: 	(@responselist)=split(/,/,$response);
1.105     albertel  222: 	if (@responselist < @LONCAPA::CAPAresponse_answer) {
                    223: 	    return 'MISSING_ANSWER';
                    224: 	}
                    225: 	if (@responselist > @LONCAPA::CAPAresponse_answer) {
                    226: 	    return 'EXTRA_ANSWER';
                    227: 	}
1.73      albertel  228:     } else {
                    229: 	(@responselist)=($response);
                    230:     }
                    231:     $result.="Initial final response :$responselist['-1']:\n";
1.105     albertel  232:     my $unit;
1.73      albertel  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:     }
1.82      albertel  240:     $result.="Final final response :$responselist['-1']:$unit:\n";
1.73      albertel  241:     $unit=~s/\s//;
1.105     albertel  242: 
1.106     albertel  243:     my ($awards, @msgs, $i);
1.105     albertel  244:     foreach my $thisanswer (@LONCAPA::CAPAresponse_answer) {
                    245: 	my ($msg,$aresult);
1.73      albertel  246: 	$result.="trying answer :$thisanswer:\n";
1.105     albertel  247: 	if (defined($thisanswer)) {
1.104     albertel  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: 	    }
1.73      albertel  255: 	} else {
1.104     albertel  256: 	    $aresult='ERROR';
1.105     albertel  257: 	    $msg='answer was undefined';
1.73      albertel  258: 	}
1.105     albertel  259: 	&LONCAPA_INTERNAL_DEBUG("after if $aresult -- $msg");
1.104     albertel  260: 	my ($temp)=split(/:/, $aresult);
1.73      albertel  261: 	$awards.="$temp,";
                    262: 	$result.=$aresult;
                    263: 	push(@msgs,$msg);
1.106     albertel  264: 	$i++;
1.73      albertel  265:     }
1.104     albertel  266:     chop($awards);
1.73      albertel  267:     return ("$awards:\n$result",@msgs);
1.7       albertel  268: }
                    269: 
1.4       albertel  270: sub tex {
1.73      albertel  271:     if ( $external::target eq "tex" ) {
                    272: 	return $_[0];
                    273:     } else {
                    274: 	return $_[1];
                    275:     }
1.4       albertel  276: }
                    277: 
1.24      ng        278: sub var_in_tex {
1.73      albertel  279:     if ( $external::target eq "tex" ) {
                    280: 	return $_[0];
                    281:     } else {
                    282: 	return "";
                    283:     }
1.24      ng        284: }
                    285: 
1.4       albertel  286: sub web {
1.73      albertel  287:     if ( $external::target eq "tex" ) {
                    288: 	return $_[1];
1.26      ng        289:     } else {
1.73      albertel  290: 	if ( $external::target eq "web" || $external::target eq "answer") {
                    291: 	    return $_[2];
                    292: 	} else {
                    293: 	    return $_[0];
                    294: 	}
1.4       albertel  295:     }
                    296: }
                    297: 
1.24      ng        298: sub html {
1.73      albertel  299:     if ( $external::target eq "web" ) {
                    300: 	return shift;
                    301:     }
1.24      ng        302: }
                    303: 
1.1       harris41  304: sub hinton {
1.73      albertel  305:     return 0;
1.1       harris41  306: }
                    307: 
                    308: sub random {
1.61      albertel  309:     my ($start,$end,$step)=@_;
                    310:     if ( ! $hidden::RANDOMINIT ) {
                    311: 	if ($external::randomseed == 0) { $external::randomseed=1; }
                    312: 	if ($external::randomseed =~/,/) {
1.84      albertel  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);
1.61      albertel  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;
1.1       harris41  328: }
                    329: 
1.26      ng        330: sub random_normal {
1.73      albertel  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;
1.26      ng        338: }
                    339: 
                    340: sub random_beta {
1.73      albertel  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;
1.26      ng        348: }
                    349: 
                    350: sub random_gamma {
1.73      albertel  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;
1.26      ng        358: }
                    359: 
                    360: sub random_exponential {
1.73      albertel  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;
1.26      ng        368: }
                    369: 
                    370: sub random_poisson {
1.73      albertel  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;
1.26      ng        378: }
                    379: 
                    380: sub random_chi {
1.73      albertel  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;
1.26      ng        388: }
                    389: 
                    390: sub random_noncentral_chi {
1.73      albertel  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;
1.26      ng        398: }
                    399: 
                    400: sub random_f {
1.73      albertel  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;
1.26      ng        408: }
                    409: 
                    410: sub random_noncentral_f {
1.73      albertel  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;
1.26      ng        418: }
                    419: 
                    420: sub random_multivariate_normal {
1.73      albertel  421:     my ($item_cnt,$seed,$mean,$covar) = @_;
                    422:     my @oldseed=&random_get_seed();
                    423:     &random_set_seed_from_phrase($seed);
1.87      albertel  424:     my @retArray=&math_random_multivariate_normal($item_cnt,@$mean,@$covar);
1.73      albertel  425:     &random_set_seed(@oldseed);
                    426:     return @retArray;
1.26      ng        427: }
                    428: 
                    429: sub random_multinomial {
1.73      albertel  430:     my ($item_cnt,$seed,@p) = @_;
                    431:     my @oldseed=&random_get_seed();
                    432:     my @retArray;
                    433:     &random_set_seed_from_phrase($seed);
1.87      albertel  434:     my @retArray=&math_random_multinomial($item_cnt,@p);
1.73      albertel  435:     &random_set_seed(@oldseed);
                    436:     return @retArray;
1.26      ng        437: }
                    438: 
                    439: sub random_permutation {
1.73      albertel  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;
1.26      ng        447: }
                    448: 
                    449: sub random_uniform {
1.73      albertel  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;
1.26      ng        457: }
                    458: 
                    459: sub random_uniform_integer {
1.73      albertel  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;
1.26      ng        467: }
                    468: 
                    469: sub random_binomial {
1.73      albertel  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;
1.26      ng        477: }
                    478: 
                    479: sub random_negative_binomial {
1.73      albertel  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;
1.26      ng        487: }
                    488: 
1.103     albertel  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) }
1.23      ng        497: 
1.59      albertel  498: sub tan  { CORE::sin($_[0]) / CORE::cos($_[0]) }
1.21      harris41  499: #sub atan { atan2($_[0], 1); }
                    500: #sub acos { atan2(sqrt(1 - $_[0] * $_[0]), $_[0] ); }
                    501: #sub asin { atan2($_[0], sqrt(1- $_[0] * $_[0]) );  }
1.22      ng        502: 
1.59      albertel  503: sub log10 { CORE::log($_[0])/CORE::log(10); }
1.22      ng        504: 
1.20      harris41  505: sub factorial {
1.59      albertel  506:     my $input = CORE::int(shift);
1.20      harris41  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: }
1.1       harris41  530: 
1.20      harris41  531: sub roundto {
                    532:     my ($input,$n) = @_;
                    533:     return sprintf('%.'.$n.'f',$input);
                    534: }
                    535: 
                    536: sub to_string {
                    537:     my ($input,$n) = @_;
1.26      ng        538:     return sprintf($input) if $n eq "";
                    539:     $n = '.'.$n if $n !~ /^\./;
1.20      harris41  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: }
1.1       harris41  547: 
                    548: sub pow   {return $_[0] ** $_[1]; }
1.59      albertel  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)); }
1.27      ng        551: #sub floor {return int($_[0]); }
1.1       harris41  552: 
1.2       albertel  553: sub format {
1.73      albertel  554:     my ($value,$fmt)=@_;
1.81      albertel  555:     my ($dollarmode,$commamode,$alwaysperiod,$options);
                    556:     if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; } 
                    557:     #if ($options =~ /\$/) { $dollamode=1; }
                    558:     #if ($options =~ /,/)  { $commamode=1; }
1.82      albertel  559:     if ($options =~ /\./) { $alwaysperiod=1; }
1.99      ng        560:     my $result;
1.97      albertel  561:     if ($fmt=~/s$/i) {
                    562: 	$result=&format_significant_figures($value,$fmt);
                    563:     } else {
                    564: 	$fmt=~s/e/E/g;
1.99      ng        565: 	$result=sprintf('%.'.$fmt,$value);
1.97      albertel  566: 	if ($alwaysperiod && $fmt eq '0f') { $result .='.'; }
                    567: 	$result=~s/(E[+-]*)0/$1/;
                    568:     }
1.81      albertel  569:     #if ($dollarmode) {$result=&dollarformat($result);}
                    570:     #if ($commamode) {$result=&commaformat($result);}
1.73      albertel  571:     return $result;
1.46      albertel  572: }
                    573: 
1.75      albertel  574: sub chemparse {
                    575:     my ($reaction) = @_;
1.96      albertel  576:     my @tokens = split(/(\s\+|\->|<=>|<\-|\.)/,$reaction);
1.75      albertel  577:     my $formula = '';
                    578:     foreach my $token (@tokens) {
                    579: 	if ($token eq '->' ) {
                    580: 	    $formula .= '<m>\ensuremath{\rightarrow}</m> ';
                    581: 	    next;
                    582: 	}
1.96      albertel  583: 	if ($token eq '<-' ) {
                    584: 	    $formula .= '<m>\ensuremath{\leftarrow}</m> ';
                    585: 	    next;
                    586: 	}  
1.75      albertel  587: 	if ($token eq '<=>') {
                    588: 	    if ($external::target eq 'web' &&
                    589: 		&EXT('request.browser.unicode')) {
1.76      albertel  590: 		$formula .= '&#8652; ';
1.75      albertel  591: 	    } else {
                    592: 		$formula .= &web('<=> ','<m>\ensuremath{\rightleftharpoons}</m> ',
1.95      albertel  593: 				 '&lt;=&gt; ');
1.75      albertel  594: 	    }
                    595: 	    next;
                    596: 	}
1.96      albertel  597: 	if ($token eq '.') {
                    598: 	  $formula =~ s/(\&nbsp\;| )$//;
                    599: 	  $formula .= '&middot;';
                    600: 	  next;
                    601: 	}
                    602: 	$token =~ /^\s*([\d|\/]*(?:&frac\d\d)?)(.*)/;
1.90      albertel  603:         $formula .= $1 if ($1 ne '1');  # stoichiometric coefficient
1.75      albertel  604: 	
                    605: 	my $molecule = $2;
                    606: 	# subscripts
1.78      albertel  607: 	$molecule =~ s|(?<=[a-zA-Z\)\]\s])(\d+)|<sub>$1</sub>|g;
1.75      albertel  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;
1.96      albertel  614: 	$molecule =~ s/-/&minus;/g;
1.75      albertel  615: 	$formula .= $molecule.'&nbsp;';
                    616:     }
                    617:     # get rid of trailing space
1.87      albertel  618:     $formula =~ s/(\&nbsp\;| )$//;
1.75      albertel  619:     return &xmlparse($formula);
                    620: }
                    621: 
1.46      albertel  622: sub prettyprint {
1.73      albertel  623:     my ($value,$fmt,$target)=@_;
                    624:     my $result;
                    625:     if (!$target) { $target = $external::target; }
1.75      albertel  626:     if ($fmt =~ /chem/i) { return(&chemparse($value)); }
1.81      albertel  627:     my ($dollarmode,$commamode,$alwaysperiod,$options);
                    628:     if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; } 
1.86      albertel  629:     if ($options =~ /\$/) { $dollarmode=1; }
1.81      albertel  630:     if ($options =~ /,/)  { $commamode=1; }
                    631:     if ($options =~ /\./) { $alwaysperiod=1; }
1.97      albertel  632:     if ($fmt=~/s$/i) {
                    633: 	$value=&format_significant_figures($value,$fmt);
                    634:     } elsif ($fmt) {
                    635: 	$value=sprintf('%.'.$fmt,$value);
                    636:     }
1.81      albertel  637:     if ($alwaysperiod && $fmt eq '0f') {
                    638: 	if ($target eq 'tex') {
                    639: 	    $value .='\\ensuremath{.}';
                    640: 	} else {
                    641: 	    $value .='.';
                    642: 	}
                    643:     }
1.73      albertel  644:     if ($value =~ /([0-9\.\-\+]+)E([0-9\-\+]+)/i ) {
                    645: 	my $frac=$1;
                    646: 	if ($dollarmode) { $frac=&dollarformat($frac); }
1.80      albertel  647: 	if ($commamode) { $frac=&commaformat($frac); }
1.73      albertel  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 {
1.48      albertel  665: 	$result=$value;
1.86      albertel  666: 	if    ($dollarmode) { $result=&dollarformat($result,$target); }
                    667: 	elsif ($commamode)  { $result=&commaformat($result,$target); }
1.46      albertel  668:     }
1.73      albertel  669:     return $result;
1.48      albertel  670: }
                    671: 
1.80      albertel  672: sub commaformat {
1.73      albertel  673:     my ($number,$target) = @_;
                    674:     if ($number =~ /\./) {
1.102     albertel  675: 	while ($number =~ /([^0-9]*)([0-9]+)([^\.,][^\.,][^\.,])([,0-9]*\.[0-9]*)$/) {
                    676: 	    $number = $1.$2.','.$3.$4;
1.73      albertel  677: 	}
                    678:     } else {
1.102     albertel  679: 	while ($number =~ /^([^0-9]*)([0-9]+)([^,][^,][^,])([,0-9]*)$/) {
                    680: 	    $number = $1.$2.','.$3.$4;
1.73      albertel  681: 	}
                    682:     }
1.80      albertel  683:     return $number;
                    684: }
                    685: 
                    686: sub dollarformat {
                    687:     my ($number,$target) = @_;
                    688:     if (!$target) { $target = $external::target; }
                    689:     $number=&commaformat($number,$target);
1.73      albertel  690:     if ($target eq 'tex') {
                    691: 	$number='\$'.$number; #' stupid emacs
                    692:     } else {
                    693: 	$number='$'.$number; #' stupid emacs
                    694:     }
                    695:     return $number; 
1.2       albertel  696: }
1.5       albertel  697: 
1.97      albertel  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/;
1.98      albertel  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:     }
1.97      albertel  728:     # return number with sign
                    729:     return $sign.$numSig;
                    730: 
                    731: }
                    732: 
1.5       albertel  733: sub map {
1.27      ng        734:     my ($phrase,$dest,$source)=@_;
1.51      albertel  735:     my @oldseed=&random_get_seed();
1.27      ng        736:     my @seed = &random_seed_from_phrase($phrase);
                    737:     &random_set_seed(@seed);
                    738:     my $destct = scalar(@$dest);
1.28      ng        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]];
1.27      ng        745: 	    $ctr++;
1.28      ng        746: 	}
1.51      albertel  747:         &random_set_seed(@oldseed);
1.28      ng        748: 	return @output;
1.27      ng        749:     } else {
1.28      ng        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: 	}
1.27      ng        766:     }
1.56      albertel  767:     &random_set_seed(@oldseed);
1.51      albertel  768:     return '';
1.27      ng        769: }
                    770: 
                    771: sub rmap {
                    772:     my ($phrase,$dest,$source)=@_;
1.51      albertel  773:     my @oldseed=&random_get_seed();
1.27      ng        774:     my @seed = &random_seed_from_phrase($phrase);
                    775:     &random_set_seed(@seed);
                    776:     my $destct = scalar(@$dest);
1.28      ng        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]];
1.27      ng        789: 	    $ctr++;
1.28      ng        790: 	}
1.51      albertel  791:         &random_set_seed(@oldseed);
1.28      ng        792: 	return @output;
1.27      ng        793:     } else {
1.28      ng        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;
1.27      ng        800: 	while ($ctr < $tot) {
1.28      ng        801: 	    $r_idx[$idx[$ctr]] = $ctr;
1.27      ng        802: 	    $ctr++;
1.28      ng        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: 	}
1.6       albertel  816:     }
1.51      albertel  817:     &random_set_seed(@oldseed);
                    818:     return '';
1.5       albertel  819: }
1.22      ng        820: 
1.23      ng        821: sub capa_id { return }
                    822: 
                    823: sub problem { return }
                    824: 
1.22      ng        825: sub name{
1.73      albertel  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;
1.22      ng        830: }
                    831: 
                    832: sub student_number { 
1.73      albertel  833:     my $id = &EXT('environment.id');
                    834:     $id = '' if $id eq "";
                    835:     return $id;
1.22      ng        836: }
                    837: 
                    838: sub class {
1.73      albertel  839:     my $course = &EXT('course.description');
                    840:     $course = '' if $course eq "";
                    841:     return $course;
1.22      ng        842: }
                    843: 
                    844: sub sec { 
1.73      albertel  845:     my $sec = &EXT('request.course.sec');
                    846:     $sec = '' if $sec eq "";
                    847:     return $sec;
1.22      ng        848: }
                    849: 
1.23      ng        850: sub open_date { 
1.73      albertel  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;
1.23      ng        860: }
                    861: 
                    862: sub due_date { 
1.73      albertel  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;
1.23      ng        872: }
                    873: 
                    874: sub answer_date { 
1.73      albertel  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;
1.24      ng        884: }
                    885: 
                    886: sub array_moments {
1.73      albertel  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;
1.24      ng        920:     return @output;
                    921: }
1.5       albertel  922: 
                    923: sub choose {
1.73      albertel  924:     my $num = $_[0];
                    925:     return $_[$num];
1.5       albertel  926: }
1.23      ng        927: 
1.101     albertel  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: 
1.49      albertel  952: # expiremental idea
                    953: sub proper_path {
1.73      albertel  954:     my ($path)=@_;
                    955:     if ( $external::target eq "tex" ) {
                    956: 	return '/home/httpd/html'.$path;
                    957:     } else {
                    958: 	return $path;
                    959:     }
1.49      albertel  960: }
1.23      ng        961: 

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