Guest User

Untitled

a guest
Sep 25th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.33 KB | None | 0 0
  1. from math import factorial as fact
  2. from random import random
  3.  
  4. class Packet(object):
  5.    
  6.     def __init__(self, nDataBits, nOverheadBits, nRedundantBits):
  7.         self.u = nDataBits
  8.         self.o = nOverheadBits
  9.         self.k = nDataBits + nOverheadBits
  10.         self.n = nDataBits + nOverheadBits + nRedundantBits
  11.         self.computeHammingBound()
  12.        
  13.     def send(self, bitErrorRate):
  14.         '''
  15.        Repeatedly attempts to send the packet until successful while simulating
  16.        the specified bit error rate. Returns the efficiency of the packet.
  17.        '''
  18.         attempts = 0
  19.         sent = False
  20.         while not sent:
  21.             attempts += 1
  22.             errors = 0
  23.             for i in xrange(self.n):
  24.                 if random() < bitErrorRate:
  25.                     errors += 1
  26.             sent = (errors <= self.t)
  27.         return float(self.u)/(self.n*attempts)
  28.        
  29.     def computeHammingBound(self):
  30.         limit = 2**(self.n-self.k)
  31.         total = 0
  32.         t = 0
  33.         while total <= limit:
  34.             print total,limit
  35.             total += fact(self.n) / (fact(t)*fact(self.n-t))
  36.             t += 1
  37.         self.t = t-2
  38.        
  39.     def __repr__(self):
  40.         return ("=PACKET=======\n"+
  41.                  "Data bits: %d\n"%self.u+
  42.                  "Overhead bits: %d\n"%self.o+
  43.                  "Redundant bits: %d\n"%(self.n-self.k)+
  44.                  "Hamming bound: %d\n"%self.t+
  45.                  "==============")
  46.        
  47.        
  48. if __name__ == '__main__':
  49.     while True:
  50.         nDataBits = input("Input user data size: ")
  51.         nRedundantBits = input("Input redundant bits: ")
  52.         bitErrorRate = input("Input bit error rate: ")
  53.         packet = Packet(nDataBits, 100, nRedundantBits)
  54.         print "Packet ready:"
  55.         print packet
  56.         raw_input("Press enter to simulate 1,000,000 transmissions with bit "+
  57.                   "error rate of %f"%bitErrorRate)
  58.         efficiency = 0.0
  59.         N = 1000000
  60.         for i in xrange(100):
  61.             for _ in xrange(N/100):
  62.                 efficiency += packet.send(bitErrorRate)
  63.             print "%d%% complete..."%i
  64.         efficiency /= N
  65.         print "1,000,000 packets transferred with %2.3f efficiency"%efficiency
  66.         if raw_input("Again? y/n: ").lower() in ("n","no","x","q"):
  67.             exit()
Add Comment
Please, Sign In to add comment