if count == len(encoding_dict) : index = index + 1 return rlt def compare(a, b) : if len(a) != len(b) : return False for i in range(len(a)) : if a[i] != b[i] : return False return True if __name__ == '__main__': # start by building Huffman tree from probabilities plist = ((0.34,'A'),(0.5,'B'),(0.08,'C'),(0.08,'D')) cdict = huffman(plist) # test case 1: decode a simple message message = ['A', 'B', 'C', 'D'] encoded_message = PS1_tests.encode(cdict,message) decoded_message = decode(cdict,encoded_message) assert message == decoded_message, \ "Decoding failed: expected %s, got %s" % \ (message,decoded_message) # test case 2: construct a random message and encode it message = [random.choice('ABCD') for i in xrange(100)] encoded_message = PS1_tests.encode(cdict,message) decoded_message = decode(cdict,encoded_message) assert message == decoded_message, \ "Decoding failed: expected %s, got %s" % \
print "\nBaseline 1:" print " total number of runs:",runs.size print " bits to encode runs with fixed-length code:",\ 8*runs.size print "\nBaseline 2:" print " bits in Lempel-Ziv compressed PNG file:",\ os.stat('PS1_fax_image.png').st_size*8 # Start by computing the probability of each run length # by simply counting how many of each run length we have plist = PS1_tests.histogram(runs) # Experiment 1: Huffman-encoding run lengths cdict = huffman(plist) encoded_runs = numpy.concatenate([cdict[r] for r in runs]) print "\nExperiment 1:" print " bits when Huffman-encoding runs:",\ len(encoded_runs) print " Top 10 run lengths [probability]:" for i in xrange(10): print " %d [%3.2f]" % (plist[i][1],plist[i][0]) # Experiment 2: Huffman-encoding white runs, black runs plist_white = PS1_tests.histogram(runs[0::2]) cwhite = huffman(plist_white) plist_black = PS1_tests.histogram(runs[1::2]) cblack = huffman(plist_black) encoded_runs = numpy.concatenate( [cwhite[runs[i]] if (i & 1) == 0 else cblack[runs[i]]
return rlt def compare(a, b): if len(a) != len(b): return False for i in range(len(a)): if a[i] != b[i]: return False return True if __name__ == '__main__': # start by building Huffman tree from probabilities plist = ((0.34, 'A'), (0.5, 'B'), (0.08, 'C'), (0.08, 'D')) cdict = huffman(plist) # test case 1: decode a simple message message = ['A', 'B', 'C', 'D'] encoded_message = PS1_tests.encode(cdict, message) decoded_message = decode(cdict, encoded_message) assert message == decoded_message, \ "Decoding failed: expected %s, got %s" % \ (message,decoded_message) # test case 2: construct a random message and encode it message = [random.choice('ABCD') for i in xrange(100)] encoded_message = PS1_tests.encode(cdict, message) decoded_message = decode(cdict, encoded_message) assert message == decoded_message, \ "Decoding failed: expected %s, got %s" % \