#!/usr/local/bin/perl -w # report the entropy of the markov process defined by the # given bigram distribution # expected input might be # (marginal first row, then conditional distbns) # 2 1 # # 1 1 # 1 0 # # for example, which says 0 goes 50-50 to 1 and 0. # and 1 always return to 0. # entropy of this is 2/3 per symbol $verbose = 1 ; $laplace = 0.5 ; $row = -1 ; $H = 0 ; if ( $verbose ) { printf "i & a_i & p_i & log_2(1/p_i) \n" ; } READROWS: while( <> ) { s/^\s*// ; ( @counts ) = split ; if ( $#counts <= 1 ) { next READROWS ; } $row ++ ; if ($row==0) { $W = $#counts + 1; print "$W words\n" ; # this first row is the marginal } else { if ( $row > $W ) { # we must be done by now print "ignoring lines from this on : $_" ; last READROWS ; } if ($W!=$#counts+1) { print "warning $W!=$#counts\n" ; } } $c = 0 ; foreach $count ( @counts ) { $c += ($count+$laplace) ; } $w = 0 ; $h = 0 ; foreach $count ( @counts ) { $w ++ ; $x = ($count+$laplace)/$c ; $l = 0.0 ; if ( $x > 0.0 ) { $l = - log ($x) / log ( 2.0 ) ; $h += $x * $l ; } if ($row==0) { $marg[$w] = $x ; # this first row is the marginal if ( $verbose ) { print 'a'+$w , " " ; printf "& & %4.2f & %5.1f \\\\ \n" , $x , $l ; } } } # $h /= log ( 2.0 ) ; if ($row == 0 ) { print "entropy of marginal is $h\n\n" ; } else { print "conditional entropy of row $row is $h\n" ; $H += $marg[$row] * $h ; } } print "\nentropy of model is $H\n" ; exit(0);